text:
Q: Difference between document.addEventListener and window.addEventListener? While using PhoneGap, it has some default JavaScript code that uses document.addEventListener, but I have my own code which uses window.addEventListener:
function onBodyLoad(){
  document.addEventListener("deviceready", onDeviceReady, false);
  document.addEventListener("touchmove", preventBehavior, false);

  window.addEventListener('shake', shakeEventDidOccur, false);
}

What is the difference and which is better to use?

A: The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

Some paragraph.

Following points should be noted before select window or document to addEventListners

*

*Most of the events are same for window or document but
some events like resize, and other events related to loading,
unloading, and opening/closing should all be set on the window.

*Since window has the document it is good practice to use document to
    handle (if it can handle) since event will hit document first.

*Internet Explorer doesn't respond to many events registered on the
    window,so you will need to use document for registering event.

A: You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).
From mozilla dev network:

addEventListener() registers a single event listener on a single
  target. The event target may be a single element in a document, the
  document itself, a window, or an XMLHttpRequest.

So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.

A: The document and window are different objects and they have some different events.  Using addEventListener() on them listens to events destined for a different object.  You should use the one that actually has the event you are interested in.
For example, there is a "resize" event on the window object that is not on the document object.
For example, the "readystatechange" event is only on the document object.
So basically, you need to know which object receives the event you are interested in and use .addEventListener() on that particular object.
Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference

If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object.  The only main difference for propagated events is in timing.  The event will hit the document object before the window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either.  I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events.  That would suggest that you pick document over window when either will work.  But, I'd often move even closer to the source and use document.body or even some closer common parent in the document (if possible).

A: In my opinion, it is generally better to pick the closest object to the source of the event that meets your needs when handling propagated events.
So, if you want the event to happen to the element, it's better to use window.addEventListener() (assume the window variable is an element) because the most important thing here when listening to an event is that the code and event execution work faster: the only thing that matters in this case.


text:
Q: How get device rotation in lenovo A3000? Salaam. I get data from my gyro in android 4.2 in my samsung device, but get nothing in lenovo a3000,
in samsung i have rotation in front of my textviews, but in lenovo i haven't anything, even zero. it is empty.
How should i read rotation (roll, pitch, Heading) in Lenovo A3000?
my code is below:
public class CalculateDataService extends Service{

final static String TAG = "Roshan java";
SensorManager sensorManager;

private int currentDataIndex = 0;

int orientationSensor;
float headingAngle;
float pitchAngle;
float rollAngle;

LocationManager locationManager;
double latitude;
double longitude;
double altitude;

@Override
public void onCreate() {
    super.onCreate();

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 2, locationListener);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    orientationSensor = Sensor.TYPE_ORIENTATION;

    sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(orientationSensor), SensorManager.SENSOR_DELAY_GAME);

}

LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        altitude = location.getAltitude();

        Log.d(TAG, "Latitude: " + String.valueOf(latitude));
        Log.d(TAG, "Longitude: " + String.valueOf(longitude));
        Log.d(TAG, "Altitude: " + String.valueOf(altitude));
    }

    public void onProviderDisabled(String arg0) {}

    public void onProviderEnabled(String arg0) {}

    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
};

final SensorEventListener sensorEventListener = new SensorEventListener() {
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION)
        {
            headingAngle = sensorEvent.values[0];
            pitchAngle = sensorEvent.values[1];
            rollAngle = sensorEvent.values[2];

            Log.d(TAG, "Heading: " + String.valueOf(headingAngle));
            Log.d(TAG, "Pitch: " + String.valueOf(pitchAngle));
            Log.d(TAG, "Roll: " + String.valueOf(rollAngle));

            try {
                File myFile = new File("/sdcard/roshan");
                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                myOutWriter.append(
                        currentDataIndex+","+
                        makePrecision2(rollAngle)+","+
                        makePrecision2(pitchAngle)+","+
                        makePrecision2(headingAngle)+","+
                        latitude+","+
                        longitude+","+
                        altitude
                        );
                currentDataIndex++;
                myOutWriter.close();
                fOut.close();
            } catch (Exception e) {
                Log.v(TAG, e.getMessage());
            }

        }
    }

    public void onAccuracyChanged (Sensor senor, int accuracy) {
        //Not used
    }
};

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onDestroy() {
      locationManager.removeUpdates(locationListener);
      sensorManager.unregisterListener(sensorEventListener);
    super.onDestroy();
}

private float makePrecision2(float input){
    return ((float)((int)(input*100f)))/100f;
}

}

A: Sou May should use getRotation() or getOrientation() both report the same values:
•0 (default, portrait),
•1 (device 90 degree counterclockwise),
•3 (device 90 degree clockwise)
It does not report when you put it "on its head" (rotate 180, that would be the value 2). This result is possibly device-specific.
First of all you should make clear if you use an emulator or a device. Do you know how to rotate the emulator? Then I would recommend to create a small test program with a onCreate() Method like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display mDisplay = mWindowManager.getDefaultDisplay();

Log.d("ORIENTATION_TEST", "getOrientation(): " + mDisplay.getOrientation());
}

Check if the screen of your your device has been locked in the device settings Settings > Display > Auto-Rotate Screen. If that checkbox is unchecked, Android will not report orientation changes to your Activity. To be clear: it will not restart the activity. In my case I get only 0, like you described.
You can check this from your program if you add these lines to onCreate()
int sysAutoRotate = 0;
try {
    sysAutoRotate = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION);
} catch (SettingNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Log.d("ORIENTATION_TEST", "Auto-rotate Screen from Device Settings:" + sysAutoRotate);
It will return 0 if Auto-Rotate is off and 1 if Auto-Rotate is on. Another try. In your original program you might have set in manifest
android:screenOrientation="portrait"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I add both a form and a set key value pair into MongoDB using Python? I've got a system set up where a user can create an object (a jam) using a form.
I also want to add another key-value pair to this form on creation: jam_creator : session['username'], but I can't seem to figure out how to go about this using python.
Any help you be massively appreciated!
I've been messing around with update, insert, but none have worked.
@app.route('/add_jam')
    def add_jam():
        return render_template('addjam.html',
        instruments=mongo.db.instruments.find(),
        counties=mongo.db.counties.find(),
        username=session['username'])

@app.route('/insert_jam', methods=['POST'])
    def insert_jam():
        jams =  mongo.db.jam_or_event
        jams.insert_one(request.form.to_dict())

    print(request.form)
    return redirect(url_for('get_jams'))

The 'add_jam' is to bring up the form to fill out, the 'insert_jam' is to create an object with the contents of the form.


text:
Q: Abrir y envía parámetros a un activity desde una clase service Tengo el siguiente código en el servicio:
Intent intent = new Intent(servicio.this, Main.class);
intent.putExtra("idVariable", "Hola mundo");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Y así lo recibo en el Main :
try{
Bundle bundle = getIntent().getExtras();
String variable = bundle.getString("idVariable");

Toast.makeText(Main.this, variable, Toast.LENGTH_SHORT).show();

}catch (Exception e){
System.out.println("Hooola "+e.getMessage());
}

A: El código para recepción del bundle en la clase Main debe estar dentro del método onCreate(), esto para recibir correctamente el valor:
  @Override
    protected void onCreate(Bundle savedInstanceState) {
    ...
    ...

    try{
    Bundle bundle = getIntent().getExtras();
    String variable = bundle.getString("idVariable");

    Toast.makeText(Main.this, variable, Toast.LENGTH_SHORT).show();

    }catch (Exception e){
      System.out.println("Hooola "+e.getMessage());
    }
    ...
    ...
   }


text:
Q: Image upload not Properly in magento I want to upload image by custom module.In this module if i upload image the image name is
images (1).jpg

when image upload name saved it
images_1_.jpg

My code is
if (isset($_FILES['vendor_gallery']['name']) && $_FILES['vendor_gallery']['name'] != '') {
                try {
                    $path     = Mage::getBaseDir('media') . DS . 'vendors' . DS . 'profile';
                     $fname    = $_FILES['vendor_gallery']['name'];
                    $uploader = new Varien_File_Uploader('vendor_gallery');

                    $uploader->setAllowCreateFolders(false);
                    $uploader->setAllowRenameFiles(false);
                    $uploader->setFilesDispersion(false);
                    $uploader->save($path, $fname);
                }
                catch (Exception $e) {
                    echo 'Error Message: ' . $e->getMessage();
                }
            }

            if ($fname != "") {
                $data['vendor_gallery'] = $fname;
            }
            echo $fname;exit;

            try {
                $gallery = Mage::getModel('marketplace/gallery');
                if(isset($data['vendor_gallery']) && ($data['vendor_gallery'])!=''){
                $gallery->setData($data);
                $gallery->save();
                }

so how to do correct image name?

A: You can get the uploaded file by the following code.
$uploader->getUploadedFileName()
// Here $uploader is object of the Varien_File_Uploader class

This will return uploaded file name.
refer this link

A: You can change name of the image after this point:
$fname    = $_FILES['vendor_gallery']['name'];

You can play with $fname and change it accordingly. But be careful with spaces, they are not accepted at all.


text:
Q: White gap between TextBox in ItemsControl I create ItemsControl template like this:
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <TextBox Text="{Binding }" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

It works when I run on simulator. But I notice there are gaps between each TextBox.
I check the margins for TextBox are 0s. And ItemsControl Margins are 0s.
So can you please tell me where there are gaps in each items control?
Thank you.

A: The gap is created by the TextBox and not by the ItemsControl.
To get rid of the gap, you have to edit the style of TextBox and remove the PhoneTouchTargetOverhang margin of the Outer most border within the Control Template.
Here is the style,
   <Style x:Key="TextBoxStyle1" TargetType="TextBox">
        <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilyNormal}"/>
        <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
        <Setter Property="Background" Value="{StaticResource PhoneTextBoxBrush}"/>
        <Setter Property="Foreground" Value="{StaticResource PhoneTextBoxForegroundBrush}"/>
        <Setter Property="BorderBrush" Value="{StaticResource PhoneTextBoxBrush}"/>
        <Setter Property="SelectionBackground" Value="{StaticResource PhoneAccentBrush}"/>
        <Setter Property="SelectionForeground" Value="{StaticResource PhoneTextBoxSelectionForegroundBrush}"/>
        <Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/>
        <Setter Property="Padding" Value="2"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Grid Background="Transparent">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="MouseOver"/>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="MainBorder">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="MainBorder">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="ReadOnly">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="MainBorder">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <Visibility>Collapsed</Visibility>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="ReadonlyBorder">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <Visibility>Visible</Visibility>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ReadonlyBorder">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneTextBoxBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ReadonlyBorder">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneTextBoxBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneTextBoxReadOnlyBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="FocusStates">
                                <VisualState x:Name="Focused">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="MainBorder">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneTextBoxEditBackgroundBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="MainBorder">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneTextBoxEditBorderBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Unfocused"/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="MainBorder" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Margin="0"/>
                        <Border x:Name="ReadonlyBorder" BorderBrush="{StaticResource PhoneDisabledBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="Transparent" Margin="0" Visibility="Collapsed"/>
                        <Border BorderBrush="Transparent" BorderThickness="{TemplateBinding BorderThickness}" Background="Transparent" Margin="{StaticResource PhoneTouchTargetOverhang}">
                            <ContentControl x:Name="ContentElement" BorderThickness="0" HorizontalContentAlignment="Stretch" Margin="{StaticResource PhoneTextBoxInnerMargin}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="Stretch"/>
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

And Here is the ItemsControl XAML,
        <ItemsControl>
            <ItemsControl.Items>
                <StackPanel>
                    <TextBox Style="{StaticResource TextBoxStyle1}"  ></TextBox>
                    <TextBox Style="{StaticResource TextBoxStyle1}"  ></TextBox>
                    <TextBox Style="{StaticResource TextBoxStyle1}"  ></TextBox>
                </StackPanel>
            </ItemsControl.Items>
        </ItemsControl>


text:
Q: Django With MSSQL using Pyodbc: Model Forms not being saved Django version 1.8.16
pyodbc Version: 3.0.11b16
I have been trying to make a view/submit form for a project.
The basic aim I need to achieve is to view and edit/save the data in the form using stored procedure in MS SQL Server 2014. I am able to use stored procedure in the view page but have not been able to do so with the edit item and add a new item .
models.py
class procedures():
def view_patientsp(self, patid):
    cursor = connection.cursor()
    ret = cursor.execute("EXEC PR_PRES_viewpatient @uid=?  ", (patid))
    cursor.close()
    return ret

class Patient(models.Model):
    patientid = models.AutoField(db_column='PatientID', primary_key=True)
    pyear = models.DecimalField(db_column='Pyear', max_digits=10, decimal_places=0, blank=True, null=True)
    dref = models.DecimalField(db_column='DRef', max_digits=10, decimal_places=0, blank=True, null=True)
    title = models.TextField(db_column='Title', blank=True, null=True)
    fname = models.TextField(db_column='FName', blank=True, null=True)
    lname = models.TextField(db_column='LName', blank=True, null=True)
    dob = models.DateTimeField(db_column='DOB', blank=True, null=True)
    pamonth = models.TextField(db_column='PAMonth', blank=True, null=True)
    payear = models.TextField(db_column='PAYear', blank=True, null=True)
    padays = models.TextField(db_column='PADays', blank=True, null=True)
    sex = models.TextField(db_column='Sex', blank=True, null=True)

views.py
def view_patient(request):
    if request.method == 'POST':
        form = viewpatientform(request.POST)
        return render(request, 'lis/view.html', {'form': form})
    else:
        form = viewpatientform()
        if form.is_valid():
            procedure = procedures()
            ret = procedure.view_patientsp(request.POST['fields'])
        return render_to_response('lis/view.html', {'form': form})

urls.py
urlpatterns = [
url(r'^$', views.pat_list, name='index'),
url(r'^view/(?P<patid>\d+/)$', views.view_patient, name='viewpatient'), ]

view.html
{% block body %}
{% load materializecss %}
{{ form|materializecss }}
<button type="submit" class="btn btn-primary">Submit</button>
{% endblock  %}

A: You have a few options. I'll try to outline them here, as I have a similar project where we're taking a very large site written in another language and backed by SQL Server with stored procedures, that we are slowly but surely migrating to Django.
We are aiming for a full rewrite over time. This means replacing the logic in stored procedures with Django's models and views, as the ORM is very powerful. We find it a cutting back on repetition and drastically improving reusability, thus reducing the total amount of code.
You can use features like Django's inspectdb to generate an initial set of Django models to interact with your database. It will need some touching up, but this has enabled us to use some features (like Django's admin) for crud operations on the old database, rather than coding up three layers to do simple lookup table updates. I wouldn't recommend customizing the admin, but using it for what it does well is a good way to start to get familiar with how Django does things.
You can use many of Django's features, like templates and forms, to call a stored procedure. For example, in a FormView, you can do things like this:
class MyFormView(FormView):
    template_name = 'home.html'
    form_class = MyForm
    success_url = '/hooray/'

    def form_valid(self, form):
        sender = form.cleaned_data['sender']
        message = form.cleaned_data['message']

        cursor = connections['default'].cursor()
        cursor.execute('EXEC usp_insert_message @sender = ?, message = ?', sender, message)

        return super(MyFormView, self).form_valid(form)

Please be wary of coding up a FrankenDjango, however. We have taken pains during our transition to ensure that both web sites can run in parallel, with authentication shared between the two. This allows us to move features over to the new Django site over time, while doing things in the new code base the right way. After you get in the flow of using the Models, Views and Templates the right way, you will likely be pleasantly surprised at how quickly you can start moving things over, especially with Django's rich ecosystem of ready-to-go packages.
One final note: I would highly recommend the using django-pyodbc-azure (it works with SQL Server or Azure) for your Django database engine. I've found over time that it is the most actively maintained, and just worked. You can install it for Django 1.8 like this:
pip install django-pyodbc-azure<1.9

More details can be found here: https://github.com/michiya/django-pyodbc-azure
Good luck!


text:
Q: windows 10 constantly at ~50% cpu with no apparant cause This morning I started my laptop and noticed it was very loud, task manager said it was continuously around 50% cpu usage with windows defender eating up most of (which is apparently a common issue). After a frustratingly long time of trying to figure out how to fix it, I ended up disabling windows defender and installing McAfee, and now windows defender doesn't appear in the task manager anymore. But I'm still at a near-constant 50% cpu usage, even without anything open aside from task manager, and I can't figure out why. Yesterday everything was just fine - I could video call without the fans becoming audible no problem.
I really don't know what to do, I'm not very tech-savvy and I've spent the past 2 hours gently weeping onto my laptop trying to figure out how to get this thing to work.
laptop is Dell Inspiron with processor - Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz   2.90 GHz

A: I had exactly the same issue on my Dell laptop.
More than 50% CPU in Idle state.
In Task manager I saw "TrueColorALS" and multiple (~10) instances of "igfxext Module".
Once I closed TrueColorALS, all igfxext Module instances except 1 disappeared and CPU utilization dropped to 2%.
So I removed TrueColor from Startup application and now my laptop is back to life.

A: In your screenshot, all the CPU usage values add up to almost the reported 53% figure. So one of the processes visible is likely to blame.
From the active processes, we can deduce that the root cause may be some DCOM problem. Some operation is likely failing and retried at a very high rate. This causes errors in Windows Event Log which results in disk usage which in turn is scanned by McAfee.
Because errors are apparently getting logged, you can use Event Viewer to investigate. It may directly or indirectly list the cause.

You indicate that TrueColorALS.exe was to blame. Its installation may have been damaged by a Windows update or something the like.

A: Just the tasks you have shown in your screenshot sum up to a total usage of 45.5%, it is feasible that the rest of your tasks make up the other 7.5% to get to the 53% figure you see here. As to why these regular processes are taking up such a large amount of usage, there may be power saving settings which reduce the performance of your CPU.
You can check if this is the case by right clicking the battery icon on your taskbar and then left clicking "Power Options." From there you can enable high performance mode if it is not already enabled, though this will reduce the battery life of your laptop.
If you are already on high performance mode, you can try clicking "Change plan settings" next to it and then "Change advanced power settings," and verify that "Processor power management > Maximum processor state" is set to 100%.

A: I had issues of a similar kind and went through a process of disabling non Microsoft programs of which I had about 24.
My cpu was always 51%+ even at startup with nothing else open.
I isolated the problem to TrueColorALS and uninstalled the program.
Now at startup once it settles down my cpu is at 1%.
Hope it helps someone, it was bugging me for ages.

A: Just looked back at this and noticed that I am running the same processor as the opening poster. That cpu profile usage is about what I was having with TrueColorALS installed.
At the moment with TrueColorALS uninstalled and a fair amount open I am at 3-6%


text:
Q: Reference request: Cover times, Mixing Times and DGFF applied in statistics? I am trying to find if in active research in statistics, there is interest in mixing times, cover times of graphs, and/or the discrete Gaussian free field?
I haven't found anything so far for the cover time and the discrete gaussian free field. Mixing times give information on the duration of Markov Chain Monte Carlo, but I haven't seen this used in recent research.
Many thanks!

A: The annals paper of Ding-Lee-Peres is a good start:
http://annals.math.princeton.edu/2012/175-3/p08 or https://arxiv.org/abs/1004.4371
Further progress is in solo work of Ding https://arxiv.org/abs/1103.4402


text:
Q: embedded Neo4j in JVM I am trying to access a neo4j database from my java program. I tried to create a fresh db and query it, and it ran successfully as per: http://neo4j.com/docs/java-reference/current/#tutorials-java-embedded
Code:
String DB_PATH = "C:/Users/singsand/Documents/Neo4j/newdb";
    File f=new File(DB_PATH);
    GraphDatabaseService graphDb =   new GraphDatabaseFactory().newEmbeddedDatabase(f);
    try (Transaction tx=graphDb.beginTx()){
        graphDb.execute("CREATE (table1:car {name:'car1'})");
        tx.success();
    }

But then I started this db as a server through the Neo4j community edition tool and also accessed it through my browser.
After that, when i executed the same java program I used above, it throws the following error:
    Exception in thread "main" java.lang.RuntimeException: Error starting org.neo4j.kernel.impl.factory.CommunityFacadeFactory, C:\Users\singsand\Documents\Neo4j\newdb
    at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.newFacade(GraphDatabaseFacadeFactory.java:144)
    at org.neo4j.kernel.impl.factory.CommunityFacadeFactory.newFacade(CommunityFacadeFactory.java:40)
    at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.newFacade(GraphDatabaseFacadeFactory.java:108)
    at org.neo4j.graphdb.factory.GraphDatabaseFactory.newDatabase(GraphDatabaseFactory.java:100)
    at org.neo4j.graphdb.factory.GraphDatabaseFactory.lambda$createDatabaseCreator$193(GraphDatabaseFactory.java:89)
    at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:183)
    at org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(GraphDatabaseFactory.java:65)
    at neo4j.neo4jdemo.App.main(App.java:41)
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.recovery.Recovery@62fca613' failed to initialize. Please see attached cause exception.
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.init(LifeSupport.java:416)
    at org.neo4j.kernel.lifecycle.LifeSupport.init(LifeSupport.java:62)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:98)
    at org.neo4j.kernel.NeoStoreDataSource.start(NeoStoreDataSource.java:508)
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:434)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
    at org.neo4j.kernel.impl.transaction.state.DataSourceManager.start(DataSourceManager.java:99)
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:434)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
    at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.newFacade(GraphDatabaseFacadeFactory.java:140)
    ... 7 more
Caused by: java.lang.IllegalArgumentException: Unrecognized log entry version -9. At position LogPosition{logVersion=0, byteOffset=16} and entry version null
    at org.neo4j.kernel.impl.transaction.log.entry.LogEntryVersion.byVersion(LogEntryVersion.java:147)
    at org.neo4j.kernel.impl.transaction.log.entry.VersionAwareLogEntryReader.readLogEntry(VersionAwareLogEntryReader.java:83)
    at org.neo4j.kernel.impl.transaction.log.LogEntryCursor.next(LogEntryCursor.java:50)
    at org.neo4j.kernel.recovery.LatestCheckPointFinder.find(LatestCheckPointFinder.java:77)
    at org.neo4j.kernel.recovery.PositionToRecoverFrom.apply(PositionToRecoverFrom.java:53)
    at org.neo4j.kernel.recovery.DefaultRecoverySPI.getPositionToRecoverFrom(DefaultRecoverySPI.java:112)
    at org.neo4j.kernel.recovery.Recovery.init(Recovery.java:72)
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.init(LifeSupport.java:406)
    ... 16 more

I have seen similar errors in other Stack Overflow questions, but wasn't able to solve my issue using their solutions.

A: If I understand correctly. You are using embedded version of Neo4j in your app and than you are trying to start Neo4j server on your localhost. Is that right?
Neo4j Server vs Embedded mode
The thing is Neo4j embedded is running as part of your Java application. Neo4j server is standalone service which is run separately. And you can't combine those two on the same db.
If you want to use Neo4j browser with your embedded db this should help you - http://graphaware.com/neo4j/2014/11/21/neo4j-browser-with-embedded.html


text:
Q: Reading multiple Files with different columns and different row lengths I have a number of .tsv files. Unfortunately, they have differences in two ways - a different number of rows (I want to rbind to deal with this) and some have an extra column (which I want to exclude on import). I also want to remove "_raw" from the file names and insert this into a column
My starting point has been:
filenames <- dir_ls("Data/", regexp = "raw")

names <- filenames %>%
  path_file() %>%
  path_ext_remove()

data_raw <- map(filenames, read_tsv) %>%
  set_names(names)

A: library(dplyr)

# Empty list to hold results
ll <- list()
# Target source files
fs <- list.files(pattern = ".tsv")

for(f in fs){
  # Read from file
  temp <- read_tsv(f)
  # Save modified filename as field value
  temp$file <- sub(pattern = "_raw.tsv", replacement = "", x = f)
  # Save within a list
  ll[[f]] <- temp
}

# Compile list elements into a two dimensional object (matrix or dataframe)
# Using bind_rows, you don't need to worry about all columns
# matching among input datasets.
do.call(dplyr::bind_rows, ll)


text:
Q: Unsigned Long in LotusScript? How to turn off overflow detection on long? Context: I'm implementing a SHA-256 hashing to Lotusscript.
Hashing works on 32bits. LotusScript has only signed Long. When result are bigger than 2,147,483,647 we get overflow.
QUESTION: how to turn off overflow detection on Long?
If impossible, is there a working around? I was thinking at what Richard Schwartz has wroten in http://femkegoedhart.com/2012/02/05/lotusscript-timedifference-long-data-type-grrr/, how could I use NotesDateTime to help work around my problem?
Should I "forget this" but then how to hash in Lotusscript (ok I can think to use LS2J and use a standard java SHA 256)
Of course if you've got a LS implementation of SHA-256 it's also a good response :-)
Thank for your help, I feel a bit lost...
part of the code:
Dim T1 As Long
Dim h2 As Long
Dim Sigma1 As Long
Dim K_t As Long

h2=1541459225
Sigma1 = 21895337
K_t=1116352408

MsgBox String(32-Len(Bin$(h2)),"0")+Bin$(h2)+" " +"Bin$(h2)"+Chr$(13)+ _
String(32-Len(Bin$(Sigma1)),"0")+Bin$(Sigma1)+" " +"Bin$(Sigma1)"+Chr$(13)+ _
String(32-Len(Bin$(K_t)),"0")+Bin$(K_t)+" " +"Bin$(K_t)",,"DEBUG"

T1 = h2 + Sigma1
MsgBox "T1 = " & T1 & " binary representation:" + String(32-Len(Bin$(T1)),"0")+  Bin$(T1)

T1 = h2 + Sigma1 + K_t  ' **this line cause overflow**
MsgBox "T1 = " & T1 & " binary representation:" + String(32-Len(Bin$(T1)),"0")+  Bin$(T1)

NB I based my implementation on the work of Chris Veness: http://www.movable-type.co.uk/scripts/sha256.html

A: You can't turn off the overflow detection on a LONG in LotusScript. Also your sample above the BIN() function will attempt to convert to a long, so that rules out the use of DOUBLE.
The dateTime, object while it treats the number as LONG unsigned, it is probably a bit of hack to use.
Personally I'd recommend creating a small C DLL which does the work and passes it back as a string.
Alternatively create your code in Java as it doesn't have the same limitations that LS has.

A: As answered Simon O'Doherty, there is no way to turn off the overflow detection on a LONG in LotusScript.
I abandon the LS way... for now (maybe will I do an other attempt one day. Frantisek Kossuth, your right I need to take from the begining the variable limits... that the tricky part here)
Thanks for your help!
*Simon: I prefere to do LS2J than DLL!
I join the very simple class in java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256 {
public String sha256(String message) throws NoSuchAlgorithmException {
    MessageDigest md1 = MessageDigest.getInstance("SHA-256");
    String resu = A9Utility.bytesToHex(md1.digest(message.getBytes()));

    System.out.println("here SHA256: resu ="+resu);
    return resu;
}
}

for A9Utility.bytesToHex, I used the https://code.google.com/p/a9cipher/source/browse/src/cosc385final/A9Utility.java
so my call in LS is now:
UseLSX "*javacon"
Use "SHA256"
[...]
Dim mySession As JavaSession
Dim myClass As JavaClass
Dim myObject As JavaObject
Set mySession = New JavaSession()

Set myClass = mySession.GetClass("SHA256")
Set myObject = myClass.CreateObject()

Dim resu As String
resu = myObject.sha256(message)

A: You can use an COM component in LS and call it. There are a number of well developed and proven SHA-256 (and other hashes) COM components out there.
If you follow this route, you will need to 'handle' the return value as a string or some other binary encoding (base64?) as the result may (or may not) require unsigned longs to hold a raw value. Most of these components provide methods for doing this.
Bit 'old fashioned' for todays apps, but hey, you're using LS, so maybe that is not a concern.


text:
Q: Custom (OData) routes in Restangular On the server side, I'm using Web API with the OData routing convention, which means that my route for getting a single entity looks something like this:
/api/v1/Products(1)

rather than:
/api/v1/Products/1

Normally, in Restangular, I'd be able to get a single entity with something like this:
Restangular.one('Product', 1);

But that doesn't work for my OData endpoint.  I've looked at customGET, and setRequestInterceptor but I can't seem to find an example of or figure out how to change the route to match my endpoint.  Preferably globally since all of my entities will have this same format.
Any help is greatly appreciated.

A: Restangular documentation details how to create a custom configuration, you could do the same by editing the source restangular.js but this extensibility point allows us to keep a clean implementation that should be compatible with most customisations or future versions of RestAngular as well as allowing side-by-side standard REST APIs and OData v4 APIs.
How to create a Restangular service with a different configuration from the global one
// Global configuration
app.config(function(RestangularProvider) {
  RestangularProvider.setBaseUrl('http://localhost:16486');
  RestangularProvider.setRestangularFields({ id: 'Id' });
});

// Restangular service targeting OData v4 on a the specified route
app.factory('ODataRestangular', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setBaseUrl(RestangularConfigurer.baseUrl + '/odata');

    // OData v4 controller(key) Item Route convention
    RestangularConfigurer.urlCreatorFactory.path.prototype.base = function(current) {
      var __this = this;
      return _.reduce(this.parentsArray(current), function(acum, elem) {
        var elemUrl;
        var elemSelfLink = RestangularConfigurer.getUrlFromElem(elem);
        if (elemSelfLink) {
          if (RestangularConfigurer.isAbsoluteUrl(elemSelfLink)) {
            return elemSelfLink;
          } else {
            elemUrl = elemSelfLink;
          }
        } else {
          elemUrl = elem[RestangularConfigurer.restangularFields.route];

          if (elem[RestangularConfigurer.restangularFields.restangularCollection]) {
            var ids = elem[RestangularConfigurer.restangularFields.ids];
            if (ids) {
              // Crude Implementation of 'several', don't try this with more than
              // 60 Ids, performance degrades exponentially for large lists of ids.
              elemUrl += '?$filter=((Id eq ' + ids.join(')or(Id eq ') + '))';
            }
          } else {
            var elemId;
            if (RestangularConfigurer.useCannonicalId) {
              elemId = RestangularConfigurer.getCannonicalIdFromElem(elem);
            } else {
              elemId = RestangularConfigurer.getIdFromElem(elem);
            }

            if (RestangularConfigurer.isValidId(elemId) && !elem.singleOne) {
              elemUrl += '(' + (RestangularConfigurer.encodeIds ? encodeURIComponent(elemId) : elemId) + ')';
            }
          }
        }
        acum = acum.replace(/\/$/, '') + '/' + elemUrl;
        return __this.normalizeUrl(acum);

      }, RestangularConfigurer.baseUrl);
    };

    // add a response interceptor for OData v4:
    RestangularConfigurer.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
      var extractedData;
      // Collection requests are 'getList' operations
      if (operation === "getList") {
        // return the value array
        extractedData = data.value;
      } else {
        // return the first item in the array
        if(data.value.length > 0)
          extractedData = data.value[0];
      }
      // pass the metadata back
      if(extractedData) {
        extractedData.meta = { context: data['@odata.context'] };
        if(data['@odata.count'])
          extractedData.meta.count = data['@odata.count'];
      }
      return extractedData;
    });
  });
});

Implementation example:
// Controller for list route
function ListCtrl($scope, ODataRestangular) {
  $scope.providers = ODataRestangular.all("providers").getList({ $count:true }).$object;
  $scope.some = ODataRestangular.several("providers", 15,16,17,18).getList();
  $scope.single = ODataRestangular.one("providers", 15).get();
}

Captured URLs from network Traffic:
http://localhost:16486/odata/providers?$count=true
http://localhost:16486/odata/providers?$filter=((Id eq 15)or(Id eq 16)or(Id eq 17)or(Id eq 18))
http://localhost:16486/odata/providers(15)

I struggled to try to write a custom service factory and to modify BreezeJS to work with OData v4 and only recently stumbled into Restangular, I can now really appreciate the extensible design that went into restangular, the general lack of documented client side framework support has been the Achilles heel that has prevented a wider adoption of OData v4. I hope this answer contributes to getting more developers onboard with version 4.

A: Restangular does not explicitly support OData APIs. You can make the basics work, but you would probably be better off using a library that does support querying an OData API, like breeze.js.


text:
Q: How can I sign a Firefox WebExtension without using the web-ext tool? To build/sign WebExtensions, Mozilla suggests the web-ext CLI tool:

web-ext is a node-based application that you can install with the nodejs/npm tool.

From the Mozdev distribution article (bolding is mine):

Only Mozilla can sign your add-on so that Firefox will install it by default. Add-ons are signed by submitting them to AMO or using the API and passing either an automated or manual code review.

If I'd rather not have node/npm on my development box, how can I sign my WebExtension without using web-ext?

A: I never use any such tools (not for webext nor for SDK/JPM).
I always develop on my own computer with a text editor, so to answer your question, no, it is not necessary to use such tools.
AFA signing, you will then have to do it manually by visiting AMO, and uploading the add-on as Unlisted. In fact, I think the tool does the same (uploads to AMO and gets a signed response).


text:
Q: Pass combobox selected item as parameter value to class function in winform c# I have a combo box that allow user to select month and year:

when I click the check button, the program will send the month and year to dbConnect.Select class there is where the programs do the select query.
private void cmdSend_Click(object sender, System.EventArgs e)
{
    List<string>[] list;
    list = dbConnect.Select(month_list.SelectedItem.ToString(),year_list.SelectedItem.ToString());

    //submit the value month and year to dbConnect.select class.
}

I have debug the code line by line and figure out that the line
list = dbConnect.Select(month_list.SelectedItem.ToString(),year_list.SelectedItem.ToString());

does hold the value. It suppose to pass the value to dbConnect.select class as parameter month and year.
public List<string>[] Select(string month,string year)
{
    string query = "SELECT * FROM page_counter WHERE month = @month AND year = @year;";
    //some operations
}

But I found out that the public List[] Select(string month,string year) does'nt hold any value when I start the debugging.
Can someone correct me if there's any mistake in my code?

A: Modify your code as follows and execute and do accordingly
private void cmdSend_Click(object sender, System.EventArgs e)
{
MessageBox.show(month_list.SelectedItem.ToString());
MessageBox.show(month_list.SelectedText.ToString());
MessageBox.show(month_list.SelectedValue.ToString());

MessageBox.show(year_list.SelectedItem.ToString());
MessageBox.show(year_list.SelectedText.ToString());
MessageBox.show(year_list.SelectedValue.ToString());
}

i think now you can understand what value to use.

A: The SelectedItem should be from your combobox, not from the List
   private void cmdSend_Click(object sender, System.EventArgs e)
    {
        List<string>[] list;
        list = dbConnect.Select(cmdSendMonth.SelectedItem.ToString(),cmbYear.SelectedItem.ToString());

        //submit the value month and year to dbConnect.select class.
    }


text:
Q: Pandas, Filter not None values and against list multiple values I have the following DataFrame:
            Item  Weight  Bags    Must  quantity  must quantity  bags column  length assigned bag
0     planes bag    8.50  planes   v       1              1          6                None
1  Full Bandolera   3.76  planes   v       3              2          6                None
2  tail             0.30  planes  <NA>     3              2          6                None
3  central wing     1.08  planes  <NA>     3              2          6                None
4  engine           0.44  planes  <NA>     3              2          6                None
5  height steer     0.12  planes  <NA>     3              2          6                None
6  dihedral         0.40  planes  <NA>     3              2          6                None
7  pods bag         8.72  pods     v       1              1          4                None
8  Pod              1.74  pods     v       3              2          4                None
9  optic            0.86  pods     v       2              2          4                None
10 thermal          1.20  pods     v       3              2          4                None
11 Encryption Cable 0.20  Ground  <NA>    1              0          25                None
                          System,
                          planes,
                          pods,
                          low bag

I'm trying to assign the value of the Bags column to length assigned bag under the following condition:
if Must column value is not null and the length of the bags column matches one of the items in the following list:
[6,4,13]

This is my try:
class AssignBagMusts:
    df = ITEMS_DF
    _bags: dict = BAGS

    @classmethod
    def create_bag_df(cls):
        """
        Add len of string in Bags column to a column named beg_len.
        """
        cls.df['bags column length'] = cls.df['Bags'].map(len)
        cls.df['assigned bag'] = None
        return cls.df

    @classmethod
    def assign_to_bag(cls):
        bags_lens = list(cls._bags.values())
        df = cls.df[pd.notnull(cls.df[cls.df['Must']]) &
                    cls.df[cls.df['bags column length']] == any(bags_lens)]
        print(df)
if __name__ == '__main__':
    AssignBagMusts.create_bag_df()
    AssignBagMusts.assign_to_bag()

And I got this error:
raise KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: "None of [Index([ 'v',  'v', <NA>, <NA>, <NA>, <NA>, <NA>,  'v',  'v',  'v',  'v',  'v',\n        'v',  'v',  'v',  'v',  'v',  'v', <NA>,  'v', <NA>,  'v',  'v',  'v',\n        'v',  'v',  'v', <NA>, <NA>,  'v', <NA>,  'v', <NA>, <NA>, <NA>, <NA>,\n        'v', <NA>, <NA>,  'v',  'v',  'v',  'v',  'v'],\n      dtype='object')] are in the [columns]"

A: your should change this line
cls.df[cls.df['bags column length']] == any(bags_lens)]

to this
(cls.df['bags column length'] == any(bags_lens)])

Here is my df

import pandas as pd
df = pd.read_clipboard()
bags_lens = [6,4,13]
df[(pd.notnull(df['Must'])) &(df['bags'] == any(bags_lens))]

print(df)
 Item  Weight Bags  Must quantity must  quantity.1  bags column length
0    0  planes  bag  8.50   planes    v         1.0   1.0      6   None
7    7    pods  bag  8.72     pods    v         1.0   1.0      4   None


text:
Q: Charting libaray: How to let the custom indicator unmerge down? I am using charting libaray to create custom indicator, like following screenshot:

But how to let the test_indicator move down from main chart?
I can click the unmerge down to move it down, but how to do it in code?


text:
Q: Which would be the correct software license i developed some software and i like provide is as open source for private use only. It's should not be allowed to distribute the software in a commercial without my allowance.
What would be the best license for the software? Is there some standard license which fulfill my requirements?

A: I don't think there is such license. You just want to add a Copyright Notice (all rights reserved).
You want the license to be open-source, but it will violate the definition of "open-source" if you don't allow it to be completely open-source.

A: opensource.org says:

Can Open Source software be used for commercial purposes?
Absolutely.
  All Open Source software can be used for commercial purpose; the Open
  Source Definition guarantees this. You can even sell Open Source
  software.
  However, note that commercial is not the same as proprietary. [...]
Can I restrict how people use an Open Source licensed program?
No. The freedom to use the program for any purpose is part of the Open
  Source Definition. Open source licenses do not discriminate against
  fields of endeavor. [...]

See these links:
Faq: http://opensource.org/faq#commercial
Licenses & Standards: https://opensource.org/licenses


text:
Q: SharePoint Document Library after drag and drop file, status bar does not get closed automatically I have one document library in SharePoint online.
When I drag and drop any file to this library, the status bar does not get closed automatically. However, file uploading is already completed (testFile.txt).
Here. everytime user has to click cancel button to close/hide the status bar.
Please refer below screenshot :

If Anybody have any idea about this behaviour, please suggest me.
Thanks.

A: Refresh the page.
Add site into trusted site, clear cache and close IE, reopen the site and compare the results.
Does the issue exists in all libraries, try to drag and drop documents in other libraries and compare the results.


text:
Q: 'I wouldn't lie' vs 'I wouldn't be lying' Is there any difference between those two forms:

*

*I wouldn't be lying

*I wouldn't lie

For example:

*

*I wouldn't be lying if I said this is the best evening in my life!

*I wouldn't lie if I said this is the best evening in my life!

Do both forms could be used interchangeably? Or second one sounds a bit unnatural?

A: "Wouldn't lie" is a hypothetical about a future condition.  It doesn't refer to the thing you are currently speaking about, but something you might say in the future.
You might say

I wouldn't lie if you ask me how you look tonight.

(He is speaking about a lie he would not make in the future)
But in the expression in the question, you are speaking about the words you are in the process of saying, and so the continuous form is correct.

I wouldn't be lying if ...

So the two forms are rather different in meaning.

A: The two sentences are quite different. The second one has a very odd meaning.
"I wouldn't be lying if I said..." means "It is true that...", so the first sentence means, "It is true that this is the best evening of my life!"
On the other hand, "I wouldn't lie if [condition]" means "I might lie if the condition isn't met." In your example it means, "If I don't say ..., I might lie (after)." It means that saying the words "This is the best evening of my life!" somehow prevents you from telling lies, like it's a magical incantation.


text:
Q: Multiple Views of Observable Collection with Datagrid I have the same problem like this. But I´m using a DataGrid instead of a ListBox and it does not seem to work like this (it might also be because i never used visual basic and didnt translate the code correcly into c#).
I basicly want two DataGrids on the same data with different filters.
    ICollectionView view_dataLinesUnfiltered;
    ICollectionView view_dataLinesFiltered;

 public MainWindow()
    {
        ...
        //view_dataLines = CollectionViewSource.GetDefaultView(dataLines); // <- Filter works on both
        view_dataLinesUnfiltered = new CollectionView(dataLines); // <- Filter doesn´t work at all
        view_dataLinesFiltered = new CollectionView(dataLines);
        ....
        // Control Events
        this.ShowAA.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ToggleButton.UncheckedEvent));

    }

    private void ShowAA_Checked(object sender, RoutedEventArgs e)
    {
        view_dataLinesUnfiltered.Filter = null;
    }

    private void ShowAA_UnChecked(object sender, RoutedEventArgs e)
    {
        view_dataLinesUnfiltered.Filter = delegate(object o) { return FilterContent(o as ErrorDetection.stDataLine, "AA", ""); };
    }

    bool FilterContent(ErrorDetection.stDataLine line, string sFilterAA, string sFilter)
    {
        shortArrayToHexStringConverter converter = new shortArrayToHexStringConverter();

        string comBuffer = converter.Convert(line.ComBufferP as object,typeof(string),0,System.Globalization.CultureInfo.CurrentCulture) as string;

        return false;// !comBuffer.Contains("AA");
    }

The FilterContent method is being called without problems, but the DataGrid shows the lines anyway. If I use GetDefaultView the Filter works on both Datagrids. Do I have to use some other view instead of CollectionView (ListCollectionView does also not work)?
i have made a small sample project to show the problem sample. It only consists of an constructor and an observable collection.

A: You need to specify which ICollectionVIew is used on which DataGrid.
If you just bind to the collection (dataLines in this case) WPF will use the 'default view' (or create one if necessary), this is why the first commented out line works for filtering.
There are a few ways you could specify which view is used for which datagrid, depending on what patterns, etc. you are using
1) Like the linked question, you could set the ItemsSource for each DataGrid in the window's code behind, after initializing the views, e.g.:
filteredDataGrid.ItemsSource = view_dataLinesFiltered;
unfilteredDataGrid.ItemsSource = view_dataLinesUnfiltered;

2) You could set the DataContext of the window to itself, or make a view model for the screen that contains the view, and make the views public properties and then bind to the intended view for each grid, e.g.
<DataGrid ItemsSource="{Binding View_dataLinesFiltered}"> ....

Edit:
Now I'm not at work and can get to dropbox and play with your example it seems like the cause of the weird behaviour is the use of CollectionView directly. On the msdn page for CollectionView it says

You should not create objects of this class in your code. To create a
  collection view for a collection that only implements IEnumerable,
  create a CollectionViewSource object, add your collection to the
  Source property, and get the collection view from the View property.

However, if you don't want to set up the views in XAML, you could also change your CollectionViews to ListCollectionViews and it should work as expected (this is likely the view type that CollectionViewSource is making for you behind the scenes anyway).

A: I got it to work somehow. I used CollectionViewSources now instead of ICollectionView.
 <Window.Resources>
    <CollectionViewSource x:Key="viewSource_dataLinesUnfiltered"/>
    <CollectionViewSource x:Key="viewSource_dataLinesFiltered"/>
 </Window.Resources>
 ...
 <DataGrid Name="Filtered_Datagrid" ItemsSource="{Binding Source={StaticResource viewSource_dataLinesFiltered}}" >
  ...
 </DataGrid>
  ...
 <DataGrid Name="Unfiltered_Datagrid" ItemsSource="{Binding Source={StaticResource viewSource_dataLinesUnfiltered}}">
  ...
 </DataGrid>

and the c Code:
    CollectionViewSource viewSource_dataLinesUnfiltered;
    CollectionViewSource viewSource_dataLinesFiltered;
    ...
    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = dataLines;

        viewSource_dataLinesUnfiltered = (CollectionViewSource)this.Resources["viewSource_dataLinesUnfiltered"];
        viewSource_dataLinesUnfiltered.Source = dataLines;
        viewSource_dataLinesFiltered = (CollectionViewSource)this.Resources["viewSource_dataLinesFiltered"];
        viewSource_dataLinesFiltered.Source = dataLines;

        // Control Events
        this.ShowAA.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ToggleButton.UncheckedEvent));

    }

    private void ShowAA_Checked(object sender, RoutedEventArgs e)
    {
        viewSource_dataLinesUnfiltered.View.Filter = null;
    }

    private void ShowAA_UnChecked(object sender, RoutedEventArgs e)
    {
        viewSource_dataLinesUnfiltered.View.Filter = delegate(object o) { return FilterContent(o as ErrorDetection.stDataLine, "AA", ""); };
    }

    bool FilterContent(ErrorDetection.stDataLine line, string sFilterAA, string sFilter)
    {
        shortArrayToHexStringConverter converter = new shortArrayToHexStringConverter();

        string comBuffer = converter.Convert(line.ComBufferP as object,typeof(string),0,System.Globalization.CultureInfo.CurrentCulture) as string;

        return !comBuffer.Contains("AA");
    }

But I´m not sure why it works this way and the filter is not applied on window repaints when ICollectionView is used.


text:
Q: Type mismatch with VBA while other computer works well On access in VBA, I use the Graph.Chart object to rezise all the text so it fits well and change the titles to match the data displayed.
I tested severals computer and everything works well, but in a presentation room, its not working.
I get a Error 13, Type mismatch
Dim oGraph As Graph.Chart

'Error after oGraph set. (Type mismatch)
Set oGraph = Me.Graphique0.Object

Dim chSeries As Series
For Each chSeries In oGraph.SeriesCollection
    chSeries.DataLabels.Orientation = 45
    With chSeries.DataLabels.Font
        .Name = "Calibri"
        .FontStyle = "Normal"
        .Size = 10
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ColorIndex = vbBlack
        .Background = xlAutomatic
    End With
Next

I had a problem with reference with ADO, but the reference was not set on the references in access
DAO: C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEDAO.DLL
Graph: C:\Program Files\Microsoft Office\Office14\GRAPH.EXE

Graph is the one that doesnt work i think, but there is NO difference in version between the two computer.
I tried to decompile, compile and compact the database, no luck. Tried deleting the reference, no luck. No references shows "MISSING"

A: Use late-binding to allow the code to run:
Dim oGraph As Object
Dim chSeries As Object

It may be that the Graph is not correctly registered on the computer. You could register it manually. I would create a Restore Point before doing this, just in case (possibly even back up the registry, but this is perhaps over cautious).

*

*Click the Start button, Run

*"C:\Program Files\Microsoft Office\Office14\GRAPH.EXE" /REGSERVER
Re-installing Access and making sure it is up-to-date with all Windows Updates is another possibility.


text:
Q: Solidity getting different selector I was playing around with selectors and particularly how they are computed (I am using Foundry for the test). I have the following example contract:
contract Token2 {
    uint a = 1;

    function foo2(uint b) external {
        for (uint i = 0; i < 10; ++i)
            a += b;
    }
}

and in a test:
function testToken2() public {
    console.logBytes4(bytes4(keccak256(bytes("function foo2(uint b) external")))); // [1] 0x2e88fa8a
    console.logBytes(abi.encodeWithSignature("foo2(uint)")); // [2] 0x2e88fa8a
    console.logBytes4(Token2.foo2.selector); // [3] 0x7d5f3b35
}

[1] and [2] returns the same thing: 0x2e88fa8a. But [3] returns 0x7d5f3b35. (I am taking reference from https://solidity-by-example.org/function-selector/ to manually calculate the selector).
My question is why I cannot get the same selector as [3] ?


text:
Q: How to fix: 'undefined is not an object'? Trying to run the iOS simulator for an app made with React Native via Atom text editor. I previously had an error message saying "react native module does not exist in module map ". I tried to fix it by updating react native, re-ran the iOS simulator via command line with 'react-native run-ios' and got this. How can I fix this through command line?
Here is the screenshot


text:
Q: Define pointer variable using auto I want to declare a pointer variable (for the sake of this question lets assume of type int) and initialize it by nullptr, e.g.
int* ptr = nullptr;

For consistency purposes I want to deduce its type using auto, but the following looks cumbersome
auto* ptr = static_cast<int*>(nullptr); // compiles

Is there a cleaner way? Something along the lines of
auto* ptr = int*{nullptr}; // doesn't compile


text:
Q: ggplot2 log transformation for data and scales This is a follow-up to my previous question Integrating ggplot2 with user-defined stat_function(), which I've answered myself yesterday. My current problem is that, in the following reproducible example, lines, which are supposed to plot components of the data values' mixture distribution, neither appear in the expected places, nor they're of expected shape, as shown below (see the red lines at y=0 in the second figure).

Complete reproducible example:
library(ggplot2)
library(scales)
library(RColorBrewer)
library(mixtools)

NUM_COMPONENTS <- 2

set.seed(12345) # for reproducibility

data(diamonds, package='ggplot2')  # use built-in data
myData <- diamonds$price

# extract 'k' components from mixed distribution 'data'
mix.info <- normalmixEM(myData, k = NUM_COMPONENTS,
                        maxit = 100, epsilon = 0.01)
summary(mix.info)

numComponents <- length(mix.info$sigma)
message("Extracted number of component distributions: ",
        numComponents)

calc.components <- function(x, mix, comp.number) {

  mix$lambda[comp.number] *
    dnorm(x, mean = mix$mu[comp.number], sd = mix$sigma[comp.number])
}

g <- ggplot(data.frame(x = myData)) +
  scale_fill_continuous("Count", low="#56B1F7", high="#132B43") +
  scale_x_log10("Diamond Price [log10]",
                breaks = trans_breaks("log10", function(x) 10^x),
                labels = prettyNum) +
  scale_y_continuous("Count") +
  geom_histogram(aes(x = myData, fill = 0.01 * ..density..),
                 binwidth = 0.01)
print(g)

# we could select needed number of colors randomly:
#DISTRIB_COLORS <- sample(colors(), numComponents)

# or, better, use a palette with more color differentiation:
DISTRIB_COLORS <- brewer.pal(numComponents, "Set1")

distComps <- lapply(seq(numComponents), function(i)
  stat_function(fun = calc.components,
                arg = list(mix = mix.info, comp.number = i),
                geom = "line", # use alpha=.5 for "polygon"
                size = 1,
                color = "red")) # DISTRIB_COLORS[i]
print(g + distComps)

UPDATE: Just a quick note on my efforts. I have additionally tried several other options, including converting the plot's x-axis scale to normal and requesting original data values' log transformation in the histogram part, like this: geom_histogram(aes(x = log10(data), fill = ..count..), binwidth = 0.01), but the end result still remains the same. In regard to my first comment, I realized that the transformation I have mentioned is not needed as long as I'm using reference to the ..count.. object.
UPDATE 2: Changed color of line, produced by stat_function(), to red, to clarify the problem.

A: Finally, I have figured out the issues, removed my previous answer and I'm providing my latest solution below (the only thing I haven't solved is legend panel for components - it doesn't appear for some reason, but for an EDA to demonstrate the presence of mixture distribution I think that it is good enough). The complete reproducible solution follows. Thanks to everybody on SO who helped w/this directly or indirectly.
library(ggplot2)
library(scales)
library(RColorBrewer)
library(mixtools)

NUM_COMPONENTS <- 2

set.seed(12345) # for reproducibility

data(diamonds, package='ggplot2')  # use built-in data
myData <- diamonds$price

calc.components <- function(x, mix, comp.number) {

  mix$lambda[comp.number] *
    dnorm(x, mean = mix$mu[comp.number], sd = mix$sigma[comp.number])
}

overlayHistDensity <- function(data, calc.comp.fun) {

  # extract 'k' components from mixed distribution 'data'
  mix.info <- normalmixEM(data, k = NUM_COMPONENTS,
                          maxit = 100, epsilon = 0.01)
  summary(mix.info)

  numComponents <- length(mix.info$sigma)
  message("Extracted number of component distributions: ",
          numComponents)

  DISTRIB_COLORS <-
    suppressWarnings(brewer.pal(NUM_COMPONENTS, "Set1"))

  # create (plot) histogram and ...
  g <- ggplot(as.data.frame(data), aes(x = data)) +
    geom_histogram(aes(y = ..density..),
                   binwidth = 0.01, alpha = 0.5) +
    theme(legend.position = 'top', legend.direction = 'horizontal')

  comp.labels <- lapply(seq(numComponents),
                        function (i) paste("Component", i))

  # ... fitted densities of components
  distComps <- lapply(seq(numComponents), function (i)
    stat_function(fun = calc.comp.fun,
                  args = list(mix = mix.info, comp.number = i),
                  size = 2, color = DISTRIB_COLORS[i]))

  legend <- list(scale_colour_manual(name = "Legend:",
                                     values = DISTRIB_COLORS,
                                     labels = unlist(comp.labels)))

  return (g + distComps + legend)
}

overlayPlot <- overlayHistDensity(log10(myData), 'calc.components')
print(overlayPlot)

Result:


text:
Q: What is the best practice to develop CD/CI when you use ML studio APIs? In our backend development process, we have two environments: testing and production. We develop our code, and then we push the code into the testing repository. Then on the release date, we push everything into production.
Now that we are going to use ML studio, I'm struggling with setting up testing and production environments for my ML studio experiments.
I created two identical experiments with independent APIs; one experiment for testing and the other experiment is used by the production. When it comes to moving the trained experiment from testing to production, I make all the changes I made in the testing environment to the production environment, which is a very time demanding process.
Do you know any better solution so we can deploy and test our changes and then deploy the latest changes to the production? How people use ML studio in their CD/CI process?
The attached image shows the design that I have now. I'd appreciate if you can help me in improving this process. Maybe ML studio has some features to manage this scenario that I don't know.

A: In MLStudio, when you doing publishing an experiment as a API, the current API get replaced with a prevailing one. One of the practices you can do is like this.
Maintain a test experiment.
Maintain an identical copy of that and push it for the production.
When you done with the changes in the test experiment keep it as that (Then you can change it later) and make a copy of that(Using Save as) - publish it as the production service.
There are some drawbacks in this too. You have to update the API endpoints on the production code once you going to release and you may have to document the versions going for the production manually. The only advantage is the time of updating two experiments goes off.


text:
Q: Ping time = 0 with boost asio Here is my code to measure ping time based on boost asio :
void PingServiceImpl::pingHost(  const std::string& remoteIp,
                                 const PingService::TimeDuration& timeout )
{
   sendRequestTo(remoteIp, timeout);
   receiveResponseFrom(remoteIp);
}

void PingServiceImpl::sendRequestTo(const std::string& remoteIp, const TimeDuration& timeout)
{
   boost::asio::ip::icmp::resolver remoteEndpointResolver(m_ioService);
   boost::asio::ip::icmp::endpoint remoteEndpoint = *remoteEndpointResolver.resolve(boost::asio::ip::icmp::resolver::query(boost::asio::ip::icmp::v4(), remoteIp.c_str(), ""));

   std::string body = "icmp request to " + remoteIp;

   IcmpHeader echoRequest;
   echoRequest.type(IcmpHeader::echo_request);
   echoRequest.code(0);
   echoRequest.identifier(getProcId());
   echoRequest.sequence_number(++m_sequenceNumber);

   boost::uint16_t checksum = compute_checksum( echoRequest,
                                                body.begin(),
                                                body.end());
   echoRequest.checksum(checksum);

   boost::asio::streambuf requestBuffer;
   std::ostream outStream(&requestBuffer);
   outStream << echoRequest << body;

   m_timeBeforeRequestSend = boost::posix_time::microsec_clock::universal_time();

   m_socket.send_to(requestBuffer.data(), remoteEndpoint);

   m_timer.expires_at(m_timeBeforeRequestSend + timeout);
   m_timer.async_wait(boost::bind(&PingServiceImpl::handleTimeout, this));
}

void PingServiceImpl::receiveResponseFrom(const std::string& remoteIp)
{
   m_replyBuffer.consume(m_replyBuffer.size());
   m_socket.async_receive(m_replyBuffer.prepare(65536),
                         boost::bind(&PingServiceImpl::handleReceiveResponse, this, _1, remoteIp, _2));
}

void PingServiceImpl::handleReceiveResponse( const boost::system::error_code& error,
                                             std::string remoteIp,
                                             std::size_t responseSize)
{
   if(!error)
   {
      m_replyBuffer.commit(responseSize);

      std::istream inputStream(&m_replyBuffer);
      ipv4_header ipv4Header;
      IcmpHeader icmpHeader;

      inputStream >> ipv4Header >> icmpHeader;

      std::string expectedBody = "icmp request to " + remoteIp;

      if (icmpHeader.type() == IcmpHeader::echo_reply
      && icmpHeader.identifier() == getProcId()
      && icmpHeader.sequence_number() == m_sequenceNumber
      && icmpHeader.checksum() == compute_checksum(icmpHeader, expectedBody.begin(), expectedBody.end()))
      {
         m_timer.cancel();
         m_timeAfterResponseReceive = boost::posix_time::microsec_clock::universal_time();

         boost::system::error_code ec = boost::system::errc::make_error_code(boost::system::errc::success);
         this->m_pingHandler( m_timeAfterResponseReceive - m_timeBeforeRequestSend, ec );
      }
   }
}

m_timeAfterResponseReceive - is the current time when RX message is obtained
m_timeBeforeRequestSend - is the current time when TX happened
With this I get ping time = 0. How that could be? Even Windows cmd ping utility gives 1 ms for localhost. What am I doing wrong ?
BR,
Dmitry


text:
Q: Attempted import error: 'useNavigate' is not exported from 'react-router-dom' I have used all the solutions i found but still getting same error. my react-router-dom is v6.0.0 and I'm using the latest react version.
import React from "react";
import TopNav from "./TopNav/TopNav";
import logo from "../assets/logo.png";
import styles from "./LandingPage.module.css";
import SearchBar from "../SearchBar/SearchBar";
import SearchSuggestions from "./SearchSuggestions/SearchSuggestions";
import { useNavigate } from "react-router-dom";

export function LandingPage() {
  const Navigate  = useNavigate();

  function search(term, location) {
    const urlEncodedTerm = encodeURI(term);
    const urlEncodedLocation = encodeURI(location);
    Navigate.push(
      `/search?find_desc=${urlEncodedTerm}&find_loc=${urlEncodedLocation}`
    );
  }

  return (

        <TopNav />

        <SearchBar search={search} />
        <SearchSuggestions />

  );
}

export default LandingPage;


text:
Q: read data from chart, ms as x value i have some trouble with adding pinots to a chart and read them back to an array.
with tis code iam adding a new piont to my chart, y_value is a normal double var
time_stamp is a string with the current daytime (15:56:45:799) with millisecounds
string time_stamp = DateTime.Now.ToLongTimeString() + ":" + DateTime.Now.Millisecond.ToString();

chart_logger.Series[0].Points.AddXY(time_stamp, y_value);

after plotting the chart i want to save alle datapionts in an txt file, so i want the read all points form the chart
i tried it with
DataPoint[] asd = chart_logger.Series[0].Points.ToArray();

it read all the y values from the chart but i the x values are always zero
does someone have any idea
thanks for the help
Ralf

A: You need to use `ToOADate()' and 'FromOADate(double d)'.
chart_logger.Series[0].XValueType = ChartValueType.DateTime;
chart_logger.ChartAreas[0].AxisX.LabelStyle.Format = "MM/dd/yyyy HH:mm:ss.fff";
chart_logger.Series[0].Points.AddXY(DateTime.Now.ToOADate(), y_value);

DataPoint[] asd = chart_logger.Series[0].Points.ToArray();
var x = DateTime.FromOADate(asd[0].XValue);

Or
chart_logger.Series[0].YValuesPerPoint = 2;
var time = DateTime.Now;
string time_stamp = time.ToLongTimeString() + ":" + time.Now.Millisecond.ToString();
chart_logger.Series[0].Points.AddXY(time_stamp, y_value, time.ToOADate());

DataPoint[] asd = chart_logger.Series[0].Points.ToArray();
var x = DateTime.FromOADate(asd[0].YValues[1]);


text:
Q: Regex Url Check I am stuck with a simple regex problem.
What I want to do is to check a URL to see if it contains the word ajax and if it does then match on the URL.
For instance
given URL localhost/ajax/image/get
should match and return localhost/ajax/image/get
However localhost/image/get
should not match.
I've basic knowledge of regex but havn't been able to get anything working for it.
Any suggestions? I'm sure this is quite a simple case.
I am using this for a mod rewrite Rule
The mod rewrite rule is
RewriteRule ^.?\bajax\b.$ ajax.php?url=$1 [PT,L]
URL requested http://localhost:93/public/ajax/image/
It redirects to the ajax.php file but the url values are not preserved.
I have another rule which is a general one as follows
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
URL requested http://localhost:93/public/imgage/get/
When this redirects to index.php it has /public/image/get/ in the url GET value

A: Simple regex. You have multiple tags so I am not quite sure what your platform is. If it is java :
Pattern regex = Pattern.compile("^.*?\\bajax\\b.*$");

In general this should be the regex :
   /^.*?\bajax\b.*$/

Explanation :
"^" +       // Assert position at the beginning of the string
"." +       // Match any single character that is not a line break character
   "*?" +      // Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
"\\b" +      // Assert position at a word boundary
"ajax" +    // Match the characters "ajax" literally
"\\b" +      // Assert position at a word boundary
"." +       // Match any single character that is not a line break character
   "*" +       // Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
"$"         // Assert position at the end of the string (or before the line break at the end of the string, if any)

Finally I would suggest this for further reading.

A: I solved the issue, the regex i was looking for is
^(.ajax.)$
I had been trying ^(ajax)$ but this doesn't make sense.
Thanks for help

A: What about
[a-z/]*ajax[a-z/]*

it could use some refinement, so let me know if it needs to be improved.

A: It should be as simple as:
Pattern.matches(regex, str)

so
Pattern.matches("ajax", str)
where str is the url string being passed in.


text:
Q: Run a function inside a nested class, from a different nested class where both are nested in the same class If I have a piece of code looking like this, how would I be able to run printInner2() from the printInner1() function? Calling self.anything only shows things inside of the inner1 class, is there a way to "step up" to the next class level? Preferably keeping everything self contained so I don't have to init the class then call it internally.
class outer:

   class inner1:

       def printInner1(self):
           print("Inner 1")

   class inner2:

       def printInner2(self):
           print("Inner 2")

A: If what you're trying to do is have printInner1 and printInner2 as class methods, meaning they belong to the class itself and not to an instance of the class, you should remove the argument self.
class outer:
   class inner1:
       def printInner1():
           print("Inner 1")

   class inner2:
       def printInner2():
           outer.inner1.printInner1()
           print("Inner 2")

outer.inner2.printInner2()

If you need it to work with instances of a class you can do:
class Outer:
    class Inner1:
        def __init__(self, parent):
            self.parent = parent

        def printInner1(self):
            print("Inner 1")

    class Inner2:
        def __init__(self, parent):
            self.parent = parent

        def printInner2(self):
            self.parent.inner1.printInner1()
            print("Inner 2")

    def __init__(self):
        self.inner1 = Outer.Inner1(self)
        self.inner2 = Outer.Inner2(self)

Outer().inner2.printInner2()

Although, there is probably a better way to go about it.
From the question it is really hard to deduct what is it that you're trying to do. And for most use cases this is bad practice and it's probably best to refactor the code.


text:
Q: How Do I Move This Button Along With The Drop Down I am designing a page where a city should be selected first. Now I am able to get the button and the drop down item in it but it stays on to the top of the page. I want to be able to move it to the center or probably to the left-middle of the page. Here is my code:
<!DOCTYPE html>

<button onclick="myFunction()" class="dropbtn">Select City</button>

Mumbai


text:
Q: Video Call through SIP in Android I am beginner in Android and working on an application which could make video call over IP using SIP. I searched about it a lot on Google and also on StackOverflow and all I got is that I would need some Native Library, about which I don't have so much knowledge.
I looked after Linphone and Csipsimple and IMSdroid but didn't get anything (means I don't need the working application, I just want to know how they work).
Using inbuild SIP stack in Android, I am able to make Audio Calls but don't know how to do this with Video.
Is there any simple way to do this?
So, If there is any suggestion for me, plz tell me..
Thanks in Advance. I am looking for some positive responses. :)

A: Taken from my answer here: Android video calls using android's sip
I believe the generic Android SIP stack supports video...
Taken from:
https://developer.android.com/reference/android/net/sip/package-summary.html
If you want to create generic SIP connections (such as for video calls or other), you can create a SIP connection from the SipManager, using open(). If you only want to create audio SIP calls, though, you should use the SipAudioCall class, as described above.
and, if you want or don't mind using external libraries/SIP stacks, check out this:
http://www.youtube.com/watch?v=g1NHEsXFEns
which uses Jain-SIP should help!
EDIT: As of late, this project seems to be the leader in the native Android SIP space:
https://code.google.com/p/csipsimple/ .. open source and they offer everything you need to make voice and video calls.


text:
Q: Analysis e-neighborhoods Show that if $a,b \in \mathbb{R}$, and $a \not= b$, then there exist e-neighborhoods $U$ of $a$ and $V$ of $b$ such that $U \cap V = \varnothing$
I am thinking that I may need to use the triangle inequality but I am not sure really how to get started. Is this the appropriate thing to do?
Thanks!

A: Assume, without loss of generality that $a<b$. Let $m := \frac{1}{2}(b-a)$ be half the distance from $a$ to $b$. The neighbourhoods could be $U_a := \{ x \in \mathbb{R} : a-m < x < a+m\}$ and $U_b := \{ x \in \mathbb{R} : b-m < x < b+m\}$. It's clear that $U_a \cap U_b = \emptyset$. Better still, you could define
$$U_a := \{ x \in \mathbb{R} : a-m/2 < x < a+m/2 \} \, , $$
$$U_b := \{ x \in \mathbb{R} : b-m/2 < x < b+m/2 \} \, , $$
so that $\overline{U_a} \cap \overline{U_b} = \emptyset.$


text:
Q: Получение объекта по координатам Не могу понять, что необходимо сделать, чтобы вывести GameObject по координатам.
Есть код к примеру:
cam = MainCamera.main;
planes = GeometryUtility.CalculateFrustumPlanes(cam);
for (int i = 0; i < planes.Length; ++i) {
    Plane p = planes[i];
}

То есть выводит объекты, которые видит камера, как видим, тут используется Plane и у него можно получить:
p.normal (Vector3)
p.distance (float).
Но как мне потом зная p.normal координаты, вывести GameObject, который находится по данным координатам?

A: Попробуйте использовать методы OnBecameInvisible() и OnBecameVisible() они определяются в наследнике MonoBehaviour так же, как и методы Start или Awake и вызываются, когда объект начинает/перестаёт рендриться хотя бы одной камерой.
Соответственно вы можете использовать их для того, чтобы объект регистрировал себя в каком-нибудь списке, либо удалялся оттуда при вызовах соответствующих методов.

A: Вот то, о чем писал @M. Green, повесьте первый скрипт на камеру, а второй - на потенциально видимые объекты:

public class VisibleObjectsList : MonoBehaviour {
    public List<PotentiallyVisibleObject> list = new List<PotentiallyVisibleObject>();
}

public class PotentiallyVisibleObject : MonoBehaviour{
    private VisibleObjectsList list;

    void Start () {
        list = FindObjectOfType<VisibleObjectsList>();
    }

    void OnBecameInvisible(){
        list.list.Remove(this);
    }

    void OnBecameVisible(){
        list.list.Add(this);
    }
}

A: Решил вопрос:
На камеру кинул BoxColliderсделал нужный размер и повесил OnTriggerEnter.
Теперь когда камера попадает на объект, он выводится в OnTriggerEnter, а по OnTriggerExit - убираю с видимости.
Еще можно будет попробовать сделать, чтобы коллайдер менялся в зависимости от дистанции камеры или угла и т.д.


text:
Q: Downloading a plist as NSDictionary returns (null) I have checked many questions on here about downloading a plist file from my server and converting it to a usable NSDictionary. For whatever reason, when I NSLog the NSDictionary created from the plist file, I get this in the console:
Timestamp: (null)

I know that it is a real file: http://www.faithlifefellowship.us/iOS/sermons.plist
Code:
NSDictionary* plist = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:@"http://www.faithlifefellowship.us/iOS/sermons.plist"]];

NSLog(@"%@",plist);

What is the problem?
Could it have anything to do with the fact that the plist file is minified?
UPDATE:
Getting the file with the following code:
NSString* pl = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.faithlifefellowship.us/iOS/sermons.plist"] encoding:NSUTF8StringEncoding error:nil];

NSLog(@"%@",pl);

returns:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>1</key><array><integer>1</integer><string>I've Been Redeemed</string><string>Ive Been Redeemed</string><array><string></string></array><array><string>03/20/09</string><string>04/02/09</string><string>04/10/09</string><string>04/24/09</string><string>05/13/09</string><string>05/23/09</string><string>06/06/09</string><string>06/13/09</string><string>06/20/09</string></array><string>http://faithlifefellowship.us/Sermons/Banners/Banner-IBR.png</string><integer>9</integer><array><string>Many Christians allow things in their lives, not realizing that they have been redeemed from them and because of ignorance of God's Word, do not walk in total freedom. This series will set you free in every area of your life!</string><string>It is important to be able to differentiate between a curse in our lives and suffering tribulation for the Lord's sake.</string><string>The same exact blessing that was on Abraham's life is now on our lives because of Jesus Christ. Don't let ignorance or unbelief keep you from all that God has for you!</string><string>Well, I guess God wants me to be sick to teach me a lesson, ever heard someone say that? Well that does not work EVER in the light of God's Word. Gal 3:13 Christ HAS redeemed us...</string><string>As we age the world says that we get weaker mentally, but God's Word does not agree with this. Part of what we have been redeemed from is an unsound and unstable mind.</string><string>Get up early, work late, still nothing ever seems to go your way why? Becasue of the curse. The Good News is that we have been redeemed from loss and failure in our lives!</string>

Blah blah blah and on and on...it's all there

A: There are unescaped ampersands (i.e. 'Pt 1 & 2') in this file, which is restricted. You should either replace them with & on your server, or download contents of the file to NSString and then replace & with &:
NSString *error;
NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.faithlifefellowship.us/iOS/sermons.plist"]
                                         encoding:NSUTF8StringEncoding
                                            error:&error];

str = [str stringByReplacingOccurrencesOfString:@" & " withString:@" & "];
NSData *plistData = [str dataUsingEncoding:NSUTF8StringEncoding];

NSPropertyListFormat format;
NSDictionary *plist = [NSPropertyListSerialization propertyListFromData:plistData
                                                       mutabilityOption:NSPropertyListImmutable
                                                                 format:&format
                                                       errorDescription:&error];

Plus, there's a big problem with tags matching. You can validate your plist with http://www.xmlvalidation.com


text:
Q: Is there a version of the BSD print system's `pac` command in the SVR4 print system I was reading an old UNIX manual and one of the chapters was on UNIX printing systems. I am used to the BSD system(lpr/lpd) system, and found the pac command kind of cool. If you do not know what pac does, it gathers info for print jobs, and will calculate a printing price for the print jobs. The pricing model is customizable, and can be changed. Output would look something like:
Login                 pages/feet                   runs        price
user1                 10.00                        1           $10.00
user2                 100.00                       3           $300.00
user3                 1.00                         2           $2.00

later, the book went on to describe the SVR4 print system, which usesthe lp command to send a file to the print queue, and the lpsched daemon to print. But I have not seen any sort of pac command for the SVR4 system. Is there one? How do I use it?


text:
Q: twitter-like auto refresh feature using MVC 2 How can i create the twitter auto-refresh effect in an MVC 2 Application ?
thanks

A: You could use the setInterval javascript function which allows you to execute some code at regular intervals. Then you could send an AJAX request to the server to see if there are updates and refresh some portion of the page. Here's an example of how you could poll a server action for updates:
window.setInterval(function() {
    // this will execute every 5 seconds
    // send an AJAX request
    $.get('/someaction', { }, function(result) {
        // use the result returned from the server
        // to update the DOM
    });
}, 5000);


text:
Q: Google Analytics: What would happens in two domain but not using _setDomainName? I have two different domain site under same UA id without setDomainName. But for some reason, I cannot modify my code.What would happen if I didn't add _setDomainName?

A: By not setting a _setDomainName method, it takes on it's default value which is "auto", which will attempt to resolve the domain name based on the document.domain DOM property.
More information here - tracking code domains and directories.


text:
Q: Galilean transformations and Frenet Frame How I can prove that the curvature and torsion of a curve are invariant under the Galilean transformations? In my physics book a hint is the isometries of Galilean transformations, but it's still difficult. I don't have any idea.

A: A Galiliean transformation consists of a composite of any of the following transformations on spacetime:

*

*Translation in time

*Translation in space (time-independent)

*Translation in space (time-dependent)

*Rotation in space

These three transformations act on curves $\mathbf{x}(s)$ (where $s$ is the arc-length parameter) in the following ways:

*

*$\mathbf{x}(s)\to \mathbf x'(s) =\mathbf{x}(s-\sigma)$

*$\mathbf{x}(s)\to \mathbf x'(s)=\mathbf{x}(s) + \mathbf x_0$

*$\mathbf{x}(s)\to \mathbf x'(s)=\mathbf{x}(s) + s \mathbf v$

*$\mathbf{x}(s)\to \mathbf x'(s) =R\,\mathbf x(s)$

where $\sigma$ is a real number, $\mathbf x_0, \mathbf v$ are some constant vectors, and $R$ is a rotation (an orthogonal linear transformation that satisfies $R^t R = I$).  The curvature of an arc-length parameterized curve $\mathbf x(s)$ is defined as
$\kappa = \Big|\frac{d^2 \mathbf x}{dt^2}\Big|$
Let's see what happens to this quantity under each of these types of transformations.  Let $\kappa'$ denote the curvature of the transformed curve $\mathbf x'$, then we have

*

*$\kappa'(s) = \Big|\frac{d^2\mathbf x'}{ds^2}(s)\Big| = \Big|\frac{d^2\mathbf x}{ds^2}(s-\sigma)\Big| = \kappa(s-\sigma)$

*$\kappa'(s) = \Big|\frac{d^2\mathbf x'}{ds^2}(s)\Big| = \Big|\frac{d^2\mathbf x}{ds^2}(s)\Big| = \kappa(s)$

*$\kappa'(s) = \Big|\frac{d^2\mathbf x'}{ds^2}(s)\Big| = \Big|\frac{d^2\mathbf x}{ds^2}(s)\Big| = \kappa(s)$

*$\kappa'(s) = \Big|\frac{d^2\mathbf x'}{ds^2}(s)\Big| = \left(R\frac{d^2\mathbf x}{ds^2}(s)\right)\cdot\left(R\frac{d^2\mathbf x}{ds^2}(s)\right) = \left(\frac{d^2\mathbf x}{ds^2}(s)\right)\cdot\left(R^tR\frac{d^2\mathbf x}{ds^2}(s)\right) = \Big|\frac{d^2\mathbf x}{ds^2}(s)\Big| = \kappa(s)$
We see that under translation in time, the curvature has the same value along the new curve, but just at different times, and for the other three transformations, the curvature has the same value along the two curves for all times.
Composing all of these transformations, we find that the most general Galilean transformation has the form
$\mathbf x(s)\to\mathbf x'(s) =R\mathbf x(s-\sigma) +s\mathbf v + \mathbf x_0$
so in general, the curvature transforms as
$\kappa'(s) = \kappa(s-\sigma)$
The proofs for torsion $\tau$ are perhaps a little bit harder, but I'll leave them to you :)
Please let me know of any errors, questions or comments!
Cheers!

A: For curves in space, it's very easy (too easy--- there's nothing to do) because a Galilean transformation is just a translation on any one time, it just shifts the space coordinates by a constant. For curves in space-time it is false. for example, if you are moving very very fast with acceleration g, your space-time path has nearly zero curvature, but if your coordinates go along with you, you become stationary with acceleration g, and then the radius of curvature is 1/g, not zero.


text:
Q: Variance of Multi-Dimensional Ornstein Uhlenbeck process I am trying to compute the asymptotic variance of OU process
$$
d X_t = - H X_t dt + S dW_t
$$
where $X_t$ takes value in $R^d$. $H$ and $S$ are $d\times d$ matrices that does not have $HS = SH$ in general. How to compute its variance at $t$?
Things are classical for one dimensional case as
$$
Var (X_t) = \sigma^2 / \mu (1-e^{-\mu t})
$$

A: the large-$t$ limit $\rho$ of the variance of $X_t$ is given by
$$\rho=\int_0^\infty \exp(-tH)SS^{\dagger}\exp(-tH^{\dagger})dt$$
where the superscript $\dagger$ indicates the transpose (or the conjugate transpose if the matrix is complex); this result holds also if $S$ is $d\times d'$ with $d'\leq d$; see, for example, page 11 of these notes, which also show how to evaluate the integral by Schur decomposition of $H$.


text:
Q: Save file to sdcard as3 Air for Android I am making an android application in Air for android using actionscript 3. I need to download  a file from the server and save it to mobile sdcard. Following is my code, the file gets loaded from the server but how do I save it on sdcard?
import flash.filesystem.*;
var urlString:String = "http://www.mywebsite.com/xyz/myswftodownload.swf";
var urlReq:URLRequest = new URLRequest(urlString);
var urlStream:URLStream = new URLStream();
var fileData:ByteArray = new ByteArray();
urlStream.addEventListener(ProgressEvent.PROGRESS, onProgress);
urlStream.addEventListener(Event.COMPLETE, loaded);
urlStream.load(urlReq);

function loaded(event:Event):void
{
    urlStream.readBytes(fileData, 0, urlStream.bytesAvailable);
    trace("Loaded");
    urlStream.removeEventListener(ProgressEvent.PROGRESS, onProgress);
    urlStream.removeEventListener(Event.COMPLETE, loaded);
    //NOW HOW TO SAVE THE LOADED FILE ON SDCARD??
}

function onProgress(evt:ProgressEvent):void {
var nPercent:Number = Math.round((evt.bytesLoaded / evt.bytesTotal) * 100);
//loadingAnim.bar.scaleX = nPercent / 100;
status.text = nPercent.toString() + "%";
}

A: You can do something like this
//NOW HOW TO SAVE THE LOADED FILE ON SDCARD
var file:File = File.userDirectory.resolvePath("myswftodownload.swf");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeBytes(fileData, 0, fileData.length);
fileStream.close();

File.userDirectory usually points to the sdcard (external storage). But beware of the fact that external storage doesn't have to be available at all time (for example when device connected as mass storage by usb).
In your case i would consider using internal storage instead and use File.applicationDirectory or File.applicationStorageDirectory for saving your swf files. External storage is better for saving files like images, music, documents..


text:
Q: How to open android app in PC browser with http protocol? First, I don't know how to call this in android development. I am trying to search on the internet but found nothing.
Scenario:

*

*I develop an android app that could do database functions e.g. create, update, delete some data. Say simple list of animal names. I could do everything database functions but only on android device (I mean my app).

My question:

*

*Could I do all the database functions on PC browser that connected to my android app with a url link?

For example -- http://192.168.1.1:7575/
Link above will open a user interface that connected to my app and I could do database functions on it. If I change the data then it will change the data on android app as well.
Btw, I'm not native english speaker. Thanks.
[EDIT]
See this image below: The right side is an android app that running on android device. The left side is web version that connected to the android device with a url. If I close the app on android, the web version also unavailable. It's only one app, an android app. I don't know how to achieve this ability.
link here

A: In Android Studio 4.1+ you can use the Database Inspector feature.
This feature lets you to see live update of the database, or manipulate the data.
You can read more about it here:
https://developer.android.com/studio/inspect/database