text:
Q: Unable to connect to VSTS LocalDB instance We run integration tests in a Visual Studio Online build tasks, executing them against a LocalDB instance that runs on the hosted VSTS build agent.
We have a task to start LocalDB by executing these commands:
sqllocaldb create MSSQLLocalDB
sqllocaldb start MSSQLLocalDB
sqllocaldb info MSSQLLocalDB

This seems OK when it runs:
LocalDB instance "MSSQLLocalDB" started.
Name:               MSSQLLocalDB
Version:            13.1.4001.0
Owner:              factoryvm-az442\VssAdministrator
Auto-create:        Yes
State:              Running

The connection string from the integration test project look like this:
Server=(localdb)\\MSSQLLocalDB;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true

This has been working for over a year now, but over the past few days we are seeing this when trying to run the tests:
Login failed for user 'factoryvm-az442\VssAdministrator'

Since Trusted_Connection is used, I'm not sure why it can't login. I did also try removing it. I also tried parsing the instance named pipe name from the output of sqllocaldb info MSSQLLocalDB and using that in the connection string, e.g. Server=np:\\.\pipe\LOCALDB#1579B709\tsql\query;Database=MyDatabase, but then I get:
A connection was successfully established with the server, but then an error occurred during the login process.
(provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.)

Any idea how we can get this running again?
Note: Please note this is not the same as #44724118, as I do not have an invalid connection string and am not using IntegratedSecurity

A: I had also opened a GitHub issue, and someone from Microsoft replied that they updated the VSTS agent image - this seems to have resolved the problem.


text:
Q: Override method name in resource route     Route::resource('/api/ranking/firmware', 'Ranking\FirmwareController',
                    ['only' => ['index'], 'names' => ['index' => 'api.ranking.firmware.firmware']]);

It works when I set name 'index', but I want to access same method with 'firmware' name inside FirmwareController.

A: Resource controller has only rest interfaces, which included index, create, store, show, edit, update, delete. It's because of ideology of RESTful services. However, you can make a regular controller.
Route::controller('/api/ranking/firmware', 'Ranking\FirmwareController', [
    'firmware' => 'api.ranking.firmware.firmware',
]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error while compling vlc for android ,was it about libtool version? I have downloaded vlc source code .
after running script below
sh compile.sh

I got an error
mkdir -p -- /root/workspace/android/vlc/contrib/arm-linux-androideabi/share/aclocal && cd png && autoreconf -fiv -I/root/workspace/android/vlc/contrib/arm-linux-androideabi/share/aclocal
autoreconf: Entering directory `.'
autoreconf: configure.ac: not using Gettext
autoreconf: running: aclocal -I /root/workspace/android/vlc/contrib/arm-linux-androideabi/share/aclocal --force -I scripts
configure.ac:66: error: Libtool version 2.4.2 or higher is required
scripts/libtool.m4:46: LT_PREREQ is expanded from...
configure.ac:66: the top level
autom4te: /usr/bin/m4 failed with exit status: 63
aclocal: /usr/local/bin/autom4te failed with exit status: 63
autoreconf: aclocal failed with exit status: 63
make: *** [.png] Error 63

I thought it was about libtool version ,but the problem remains after i installed libtool 2.4.2
can somebody kindly tell me what's the problem going on .
Best regards!
Eric Shen

A: Though my ubuntu had the libtool2.4.2 installed, I too encountered this problem. This workaround solved the issue.
Find LT_PREREQ([2.4.2]) in one of the configure.ac files and replace it with LT_PREREQ([2.4])


text:
Q: Could Miller-Rabin primality test give false negative? Could Miller-Rabin primality test give false negative, for example when test prime number and gives it as composite?
I know that it could give false positive (giving composite number as prime), but  I am not sure about the reverse.

A: No, it will not indicate composite when given a prime.
The Miller-Rabin test, like many primality tests, uses properties that are always true for primes, but are rarely true for composites.  Hence, barring implementation defects, it will always return true (PROBABLY PRIME) when given a prime.  Most composites will return false (DEFINITELY COMPOSITE).  Some composites, which we call pseudoprimes to the particular test, will also return true.


text:
Q: How to display custom objects (with toString) in a JComboBox I am rather new to Java, so please keep that in mind...
I have a swing GUI in which contains a JComboBox.
I want the user to select one option of an ArrayList<Person>.
Please note that I could also use an array.
I have used JComboBox before, but only with Strings.
The Person class has a toString() method that I want to use to get the text that should represent the object in the JComboBox.
When a JButton is pushed later, the selected Person object (the same one) should be added to another ArrayList for further operations.
I want the button to do something like this:
Person selectedPerson = (Person) myComboBox.getselectedItem();

However, I somehow need to get those Person objects into that thing somehow.
I tried to use:
myComboBox.setModel(new DefaultComboBoxModel<>(aListOfStuff);

I even tried making my own model:
public class DropDownModel extends DefaultComboBoxModel<Person> implementsMutableComboBoxModel<Person>

but the setModel method wants none of that.

I have seen other kind of similar questions on Stackoverflow, but none of them answer my question. I've also noticed someone mention a renderer class or something like that.
Again:
I want an ArrayList to have its Person objects selectable in a JComboBox so that I can access the selected one with Person tempPerson = (Person) myComboBox.getSelectedObject();.
Do I have to make my own model class?
I pulled off displaying them in a JList. Using a custom model:
public class ListBoxModel extends AbstractListModel<Person> implements Iterable<Person>

Do I need something simular to that?
Is this possible at all?
Some examples:
myComboBox.setModel(new DefaultComboBoxModel<>(s.getPersonListAsArray()));
cbRemoveClass.setModel(new DefaultComboBoxModel<>(t.getClasses().toArray(new String[t.getClasses().size()])));
someOtherComboBox.setModel(new DropDownModel(dlModel.getList())); // trying to use my custom model

A:
Again: I want an ArrayList to have its Person objects selectable in a JComboBox

That is not how it works. The ArrayList means nothing to the combo box. The data needs to be stored in the ComboBoxModel.
So you need to add the data from the ArrayList to the model.
You write a simple loop to iterate through the ArrayList and then you use a combo box convenience method to add an item to the model:
for (each item in the ArrayList)
    comboBox.addItem( theItem );

A: I know I'm late to this, but this is the answer you were looking for:
JComboBox<ProtocolInterface> protocolCombo = new javax.swing.JComboBox<>();
HashSet<ProtocolInterface> protocols=this.myDevice.getSupportedProtocols();
protocolCombo.setModel(new javax.swing.DefaultComboBoxModel<ProtocolInterface>(protocols.toArray(new ProtocolInterface[protocols.size()])));

Just make sure that your object (in this case ProtocolInterface) has a "toString" method that displays the text you want like this:
@Override
public String toString() {
    return name;
}


text:
Q: Android - Elevation not working I'm migrating an Android App to use Material Design. To verify if I did everything correct i create an empty activity to test some Material Design itens (FAB, raised button, elevation on views, cards, lists, etc...).
The buttons appear to OK, but the elevation on views aren't. I searched the internet for an answer but didn't find it. I'm not using padding, transparent background, etc. Here's my code:
values-v21/styles.xml:
<resources>

    <style name="AppThemeNoActionBar" parent="AppTheme">
        <item name="android:navigationBarColor">@color/colorPrimary</item>
    </style>

    <style name="AppTheme" parent="MyMaterialTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="Button" parent="Base.Widget.AppCompat.Button.Colored">
        <item name="android:backgroundTint">@color/colorAccent</item>
    </style>

    <color name="colorPrimary">#E88768</color>
    <color name="colorPrimaryDark">#CC785C</color>
    <color name="colorAccent">#E88768</color>
    <color name="textColorPrimary">#000000</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#E88768</color>
</resources>

layout-v21/start_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/white"
                xmlns:app="http://schemas.android.com/apk/res-auto">
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_alignParentStart="true"
        android:elevation="12dp"
        android:translationZ="12dp"
        android:id="@+id/scrollView">

    </HorizontalScrollView>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_below="@+id/scrollView">

    </LinearLayout>

</RelativeLayout>

Can anyone help me?

A: Try setting a background color / drawable to your HorizontalScrollView:
android:background="@android:color/white"

This seems to be necessary for the shadow to be drawn.

A: If that elevation didn't work, you can use a trick like putting the contents in the CardView and then setting:

card_view:cardElevation="2dp"

Or:
card_view:cardCornerRadius="4dp"

For corners.

This is the best way, However you might see the elevations on Android Studio's Preview, but actually, all of them are not working when you are compiled the app or it is running on emulator or a real device.So, in these situations, better to use that CardView.
For exmaple:
<android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        card_view:cardCornerRadius="4dp"
        card_view:cardElevation="2dp">

        <HorizontalScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_alignParentStart="true"
            android:translationZ="12dp">

        </HorizontalScrollView>
    </android.support.v7.widget.CardView>


text:
Q: Keeping LED constantly on with BeagleBone black and python I have a small circuit plugged into a Beaglebone Black,
What I would like is to keep a white LED constantly on.
If I run the following code the LED turns on briefly ad then turns off again.
import Adafruit_BBIO.GPIO as GPIO
import time

GPIO.setup("P8_14", GPIO.OUT)
GPIO.output("P8_14", GPIO.HIGH)

I have tried the following:
import Adafruit_BBIO.GPIO as GPIO
import time

GPIO.setup("P8_14", GPIO.OUT)
while True:
    GPIO.output("P8_14", GPIO.HIGH)

Which will keep it constantly on but I have a feeling its actually blinking to fast for me to see. And if for example I have a bunch of code in the while loop then it blinks again (assuming the time.sleep(1) represents code that takes a second to run):
GPIO.setup("P8_14", GPIO.OUT)
while True:
    GPIO.output("P8_14", GPIO.HIGH)
    time.sleep(1)

Is there anyway to say to a pin to be on constantly with Python ?
Thanks for your help,

A: P8_14 -- this is digital Input/Output pin.
To setup a digital pin as an output, set the output value to HIGH, and then cleanup after you're done:
GPIO.setup("P8_10", GPIO.OUT)
GPIO.output("P8_10", GPIO.HIGH)
GPIO.cleanup()

For blink leds or turn it on use USR0, USR1, USR2 and USR3.
For blinking onboard leds try this example:
for i in range(4):
    GPIO.setup("USR%d" % i, GPIO.OUT)

while True:
    for i in range(4): # Turn Leds ON
        GPIO.output("USR%d" % i, GPIO.HIGH)
        time.sleep(1)
    for i in range(4): # Turn Leds Off
        GPIO.output("USR%d" % i, GPIO.LOW)
        time.sleep(1)


text:
Q: UnicodeDecodeError when installing mutagen pip So I wanted to install the pip 'mutagen' on my PC.
I using python 3.6.
When I tried to install the pip on my PC, I got this error:
    Exception:
Traceback (most recent call last):
  File "C:\Users\אלי\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str
    return s.decode(sys.__stdout__.encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 38: invalid continuation byte

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\אלי\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "C:\Users\אלי\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "C:\Users\אלי\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "C:\Users\אלי\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pip\req\req_install.py", line 878, in install
    spinner=spinner,
  File "C:\Users\אלי\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess
    line = console_to_str(proc.stdout.readline())
  File "C:\Users\אלי\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str
    return s.decode('utf_8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 38: invalid continuation byte

I using windows 10 and my default language is Hebrew.
I tried to install mutagen on other computers and I succeed.
Do anyone knows how to solve this issue?


text:
Q: What's the point on using % units in responsive design? I'm redesigning my site because looks awful on different resolutions (apart devices),  most guides and tutorials rely on % and em than fixed values. I'm still learning this so I'm reading everything around.
Thought this would solve the question with different display sizes but again: we have to craft some more CSS for fix some specific issues.
If I need to add media-queries for extra display sizes, why use % then? Do use % really reduce coding? Is ok need to add some extra css for some sizes or am I doing something wrong?
Thanks for any advice!

A: The purpose of using em sizes is to allow the base your design off of the user's choice of font size. I may use a larger font size because I have a huge monitor and poor eye sight, while someone else might prefer a smaller font. By using em units, your design will accommodate both of our font preferences and resize accordingly instead of forcing the font size to a given standard (eg. "12 point font").
In a similar manner, percent (%) units allow your design to respond to different browser sizes. Used in conjunction with em units, this will allow text-based elements to respond to arbitrary font size choices, and layout elements to respond to arbitrary browser sizes.
It is perfectly acceptable to design a single responsive design for all media types. Media queries are intended when you want different display styles on different devices, not to "support" different display sizes. An example would be to use serif fonts on print media and sans-serif fonts on display media, since usabilities studies have shown that these font faces are preferred for these sorts of media.
Furthermore, it allows you to do custom styling for some situations like mobile devices, where you may want to consider that the user has a limited amount of bandwidth and maybe cut down on extra images. Or if you want to display your content in a completely different layout for the microscopic screen afforded by certain phones.

A: % allows your site to be responsive to the user's method of viewing. Let's say you have a div that's at 100%. It'll fill the entire section, regardless if it's on a phone or desktop.
It should be okay to add extra CSS for sizes as well. As far as I know, you can have some elements display in % and some with a fixed px value, although they might conflict depending on how the page is setup or what it is being viewed with.

A: For example.
Your website header have the width of 950px; But in a mobile device, it may fit at 450px;
So, you use media-query to reposition some elements and handle some size issues and set the header width to 450px;
But, if you use % values, you can set your header div to have 100% of width base in its parent. So you can only change the body or some container div width, the all childs going to adapt.

A: Diana,
I am glad I came across this question. I literally just uploaded my first responsive design which is 90% based off of percentages when it comes to font-size and widths.
Check out the below:
http://www.noxinnovations.com/portfolio/responsive/
Obviously, it doesn't look amazing, and the image looks way out of place... But do me a favor and resize your browser window, by slowly making it smaller and smaller. I did that by setting a percentage width!
Trust me, I tried doing this responsive design test with pixels, and it didn't turn out too well. The percentage width ensures that regardless of the resolution and or pixel dimensions (per se) the design will always cater to the size of the screen. Also, I did not have to use one CSS3 Media Query, but I would highly suggest using CSS3 Media Queries only when you need them.
In my opinion, I should probably have a Media Query for a larger screen.
I hope this helps you as much as it has helped me!
Thank you,
Aaron


text:
Q: Mousewheel - switch between vertical & horizontal scroll until div ended I'm creating a prototype for a vertical and horizontal scroll system.
I would to have an normal vertical scroll of my page until a carousel. When the carousel is at the middle of my page to have an horizontal scroll until the last slide. And after to take back the vertical scroll.
Something like that : https://www.sneakinpeace.com/ but with some content after.
But I have a problem :

*

*I can not to have the ended of the carousel to continue vertical scroll and remove .stop-overflow class

Here's my prototype : https://jsfiddle.net/nx9sraug/1/
To know the end of the carousel I tried to have the width of .main_wrapper compared to the width of .main, without success
if ( $('.main').scrollLeft() == ($('.main .main__wrapper').width() - $('.main').width())) {
    alert('end!');
}

What's wrong please ? Can I have some help ?
Here's the full code :
jQuery(window).scroll(function() {
    init_position();
});

var windowHeight = jQuery(window).height();
var sliderHeight = jQuery('.main__wrapper').outerHeight(true);
var distance = (windowHeight - sliderHeight) / 2;

function init_position() {
    var windowScroll = $(window).scrollTop();
    var sliderPosition = $('.main').offset().top - $(window).scrollTop();

    if (sliderPosition <= distance) {
        console.log('milieu');
        $('html').addClass('stop-overflow');
        if ( $('.main').scrollLeft() == ($('.main .main__wrapper').width() - $('.main').width())) {
            alert('end!');
        }
        init_mousewheel();
    } else {
        $('html').removeClass('stop-overflow');
    }
}

function init_mousewheel() {
    $(document).mousewheel(function(e, delta) {
        $('#main')[0].scrollLeft -= (delta);
    }, { passive: false });
}


text:
Q: Scala cannot resolve constructor I'm leveraging the interoperability between Scala and Java and have the below code that uses Scala, to instantiate a class in the same project that was written in Java. The CommandExecutor parameter is inherited from a parent class.
class IdmIdentityServiceImpl extends ServiceImpl with IdmIdentityService {
    override def createNativeUserQuery: NativeUserQuery = {
        new NativeUserQueryImpl(commandExecutor)
      }
}

I get an error, in instantiating NativeUserQueryImpl that says cannot resolve constructor
NativeUserQueryImpl was written in Java, but I've been reading about the interoperability between Java and Scala and feel like it should work.
This is the NativeUserQueryImpl class, which takes in that CommandExecutor type in one of it's constructors. The class comes from the flowable-engine library.
public class NativeUserQueryImpl extends AbstractNativeQuery<NativeUserQuery, User> implements NativeUserQuery {

  private static final long serialVersionUID = 1L;

  public NativeUserQueryImpl(CommandContext commandContext) {
    super(commandContext);
  }

  public NativeUserQueryImpl(CommandExecutor commandExecutor) {
    super(commandExecutor);
  }

  // results ////////////////////////////////////////////////////////////////

  public List<User> executeList(CommandContext commandContext, Map<String, Object> parameterMap, int firstResult, int maxResults) {
    return commandContext.getUserEntityManager().findUsersByNativeQuery(parameterMap, firstResult, maxResults);
  }

  public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) {
    return commandContext.getUserEntityManager().findUserCountByNativeQuery(parameterMap);
  }

}

EDIT:
Full error
Error:(31, 5) overloaded method constructor NativeUserQueryImpl with alternatives:
  (x$1: org.flowable.idm.engine.impl.interceptor.CommandExecutor)org.flowable.idm.engine.impl.NativeUserQueryImpl <and>
  (x$1: org.flowable.idm.engine.impl.interceptor.CommandContext)org.flowable.idm.engine.impl.NativeUserQueryImpl
 cannot be applied to (org.flowable.engine.impl.interceptor.CommandExecutor)
    new NativeUserQueryImpl(commandExecutor)

A: From the full error posted in the original question, it appears that the CommandExecutor that is inherited from the parent class ServiceImpl has two different versions in the library
org.flowable.idm.engine.impl.interceptor.CommandExecutor and
org.flowable.engine.impl.interceptor.CommandExecutor where the subtle difference is that one is from an idm package and one is not.
Changing ServiceImpl from the second package to the first, updates the CommandExecutor parameter that's being passed in, and fixes the issue.


text:
Q: WPF - Enable 2nd combobox on 1st combobox selection I have two ComboBoxes, I want to enable the second ComboBox upon selection of First ComboBox. I have tried adding IsEnabled property but doesn't seem to work. The code I have tried is below.
<dxe:ComboBoxEdit Name="siteComboBox" HorizontalAlignment="Left" Margin="97,104,0,0"
     VerticalAlignment="Top" Width="150" ItemsSource="{Binding Site}"
     SelectedItem="{Binding SelectedSite}"/>
<dxe:ComboBoxEdit Name="planTypeComboBox" HorizontalAlignment="Left" Margin="97,159,0,0"
     VerticalAlignment="Top" Width="150"
     ItemsSource="{Binding PlanType}" SelectedItem="{Binding SelectedPlanType}"
     IsEnabled="{Binding ElementName=siteComboBox}"/>

Can anyone point out what I am doing wrong? or Is there any other way to do it?

A: You can use DataTriggers. When the selected item is null the second ComboBox will be disabled
<dxe:ComboBoxEdit Name="siteComboBox" HorizontalAlignment="Left" Margin="97,104,0,0"
     VerticalAlignment="Top" Width="150" ItemsSource="{Binding Site}"
     SelectedItem="{Binding SelectedSite}"/>
<dxe:ComboBoxEdit Name="planTypeComboBox" HorizontalAlignment="Left" Margin="97,159,0,0"
     VerticalAlignment="Top" Width="150"
     ItemsSource="{Binding PlanType}" SelectedItem="{Binding SelectedPlanType}">
     <dxe:ComboBoxEdit.Style>
         <Style TargetType="{x:Type dxe:ComboBoxEdit}">
             <Setter Property="IsEnabled" Value="True"/>
             <Style.Triggers>
                 <DataTrigger Binding="{Binding ElementName=siteComboBox, Path=SelectedItem}" Value="{x:Null}">
                     <Setter Property="IsEnabled" Value="False"/>
                 </DataTrigger>
             </Style.Triggers>
         </Style>
     </dxe:ComboBoxEdit.Style>
</dxe:ComboBoxEdit>

Edit : If you are using implicit theme, the defined style must inherited from the theme style:
<dxe:ComboBoxEdit Name="siteComboBox" HorizontalAlignment="Left" Margin="97,104,0,0"
     VerticalAlignment="Top" Width="150" ItemsSource="{Binding Site}"
     SelectedItem="{Binding SelectedSite}"/>
<dxe:ComboBoxEdit Name="planTypeComboBox" HorizontalAlignment="Left" Margin="97,159,0,0"
     VerticalAlignment="Top" Width="150"
     ItemsSource="{Binding PlanType}" SelectedItem="{Binding SelectedPlanType}">
     <dxe:ComboBoxEdit.Style>
         <Style TargetType="{x:Type dxe:ComboBoxEdit}" BasedOn="{StaticResource {x:Type dxe:ComboBoxEdit}}">
             <Setter Property="IsEnabled" Value="True"/>
             <Style.Triggers>
                 <DataTrigger Binding="{Binding ElementName=siteComboBox, Path=SelectedItem}" Value="{x:Null}">
                     <Setter Property="IsEnabled" Value="False"/>
                 </DataTrigger>
             </Style.Triggers>
         </Style>
     </dxe:ComboBoxEdit.Style>
</dxe:ComboBoxEdit>

A: A ComboBox does not have an IsChecked property. So that binding isn't going to work.
You could set up another property like IsSiteSelected that returns true when SelectedSite is not null and bind to that instead.

A: For the second combo box set IsEnabled when SelectedIndex of first combo box is not -1
Or define a SelectionChanged event for first combo box and enable/disable second combo box in backend


text:
Q: Define a global variable in SPSS Modeler I want to create a variable that contains @GLOBAL_MEAN(myField) and use it in several nodes. How can I do that in SPSS Modeler 16.0 ?
When I add a derive node and create a new variable with the value @GLOBAL_MEAN(myField)I get the following error:
AEQMJ0332E: The global value '@GLOBAL_MEAN(myField)' is undefined

Thanks

A: I found the solution ! First you have to create (from outputs tab) a Set Globals node. Then you choose the concerned field and you can check any function you want (mean, max, min,..). Then link the node where you want to use that global value with the Set Globals node. Finaly you use the function @GLOBAL_MEAN(myField) in that node. The error wont appear anymore.


text:
Q: asynchronous serial port communication in windows in c I am getting an error when I try to run a c file which does some basic writes to a serial port. I am trying to run it asynchronously because the writes sometimes take a long time to transfer. My original version had it running synchronously with WriteFile() commands which worked fine. I am new to using OVERLAPPED and would appreciate and input concerning it.
The error I am getting is:
Debug Assertion Failed!
<path to dbgheap.c>
Line: 1317
Expression: _CrtIsValidHeapPointer(pUserData)

when the second write function is called.
In main:
    {
        //initialized port (with overlapped), DBC, and timeouts

        result = write_port(outPortHandle, 128);
        result = write_port(outPortHandle, 131);
    }

static void CALLBACK write_compl(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped) {
        //write completed. check for errors? if so throw an exception maybe?
        printf("write completed--and made it to callback function\n");
    }

int write_port(HANDLE hComm,BYTE* lpBuf) {

   OVERLAPPED osWrite = {0};

   // Create this write operation's OVERLAPPED structure's hEvent.
   osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
   if (osWrite.hEvent == NULL)
      // error creating overlapped event handle
      return 0;

   // Issue write.
   if (!WriteFileEx(hComm, &lpBuf, 1, &osWrite, &write_compl )) {
      if (GetLastError() != ERROR_IO_PENDING) {
         // WriteFile failed, but isn't delayed. Report error and abort.
          printf("last error: %ld",GetLastError());
          return 0; //failed, return false;
      }
      else {
         // Write is pending.
         WaitForSingleObjectEx(osWrite.hEvent, 50, TRUE);   //50 ms timeout

        return -1; //pending
      }
   }
   else {
        return 1; //finished
   }
}

That was not the full code, sorry. I was using an array of BYTEs as well, not constants. But system("pause")'s were causing my debug assertion failed errors, and after carefully looking through my code, when the WriteFileEx() was successful, it was never setting an alert/timeout on the event in the overlapped structure, so the callback function would never get called. I fixed these problems though.
I just need help with the handling/accessing a single BYTE in a structure which is allocated when a ReadFileEx() function is called (for storing the BYTE that is read so it can be handled). I need to know how to access that BYTE storage using an offset and make the overlapped structure null. Would making the overlapped structure null be as simple as setting the handle in it to INVALID_HANDLE_VALUE?

A: I think you have a couple of issues:

You are passing an integer as a pointer (your compiler should warn against this or preferably refuse to compile the code):

result = write_port(outPortHandle, 128);

Compare this to the definition of write_port:

int write_port(HANDLE hComm,BYTE* lpBuf) {

The above statements doesn't match. Later on you then pass a pointer to the lpBuf pointer to the WriteFileEx function by taking the address of the BYTE* -> "&lpBuf". This will not result in what you think it will do.

Even if you fix this, you will still have potential lifetime issues whenever the write is successfully queued but won't complete within the 50 ms timeout.
When using overlapped I/O, you need to make sure that the read/write buffer and the overlapped structure remain valid until the I/O is completed, cancelled or the associated device is closed. In your code above you use a pointer to an OVERLAPPED struct that lives on the stack in your call to WriteFileEx. If WriteFileEx does not complete within 50 ms, the pending I/O will have a reference to a non-existing OVERLAPPED struct and you will (hopefully) have an access violation (or worse, silently corrupted stack data somewhere in your app).
The canonical way of handling these lifetime issues (if performance is not a big issue), is to use a custom struct that includes an OVERLAPPED struct and some storage for the data to be read/written. Allocate the struct when posting the write and deallocate the struct from the I/O completion routine. Pass the address of the included OVERLAPPED struct to WriteFileEx, and use e.g. offsetof to get the address to the custom struct from the OVERLAPPED address in the completion routine.
Also note that WriteFileEx does not actually use the hEvent member, IIRC.

EDIT: Added code sample, please note:

*

*I haven't actually tried to compile the code, there might be typos or other problems with the code.

*It's not the most efficient way of sending data (allocating/deallocating a memory block for each byte that is sent). It should be easy to improve, though.

    #include <stddef.h>
    #include <assert.h>
    #include <windows.h>

    // ...
    typedef struct _MYOVERLAPPED
    {
        OVERLAPPED ol;
        BYTE buffer;
    } MYOVERLAPPED, *LPMYOVERLAPPED;
    // ...

    static void CALLBACK write_compl(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
    {
        if (NULL == lpOverlapped)
        {
            assert(!"Should never happen");
            return;
        }

        LPBYTE pOlAsBytes = (LPBYTE)lpOverlapped;
        LPBYTE pMyOlAsBytes = pOlAsBytes - offsetof(MYOVERLAPPED, ol);
        LPMYOVERLAPPED pMyOl = (LPMYOVERLAPPED)pOlAsBytes;

        if ((ERROR_SUCCESS == dwErrorCode) &&
            (sizeof(BYTE) == dwNumberOfBytesTransfered))
        {
            printf("written %uc\n", pMyOl->buffer);
        }
        else
        {
            // handle error
        }

        free(pMyOl);
    }

    int write_port(HANDLE hComm, BYTE byte) {

       LPMYOVERLAPPED pMyOl = (LPMYOVERLAPPED)malloc(sizeof(MYOVERLAPPED));

       ZeroMemory(pMyOl, sizeof(MYOVERLAPPED));
       pMyOl->buffer = byte;

       // Issue write.
       if (!WriteFileEx(hComm, &pMyOl->buffer, sizeof(BYTE), pMyOl, &write_compl )) {
          if (GetLastError() != ERROR_IO_PENDING) {
             // WriteFile failed, but isn't delayed. Report error and abort.
              free(pMyOl);
              printf("last error: %ld",GetLastError());
              return 0; //failed, return false;
          }
          else {
            return -1; //pending
          }
       }
       else {
            free(pMyOl);
            return 1; //finished
       }
    }

A:
    result = write_port(outPortHandle, 128);
    result = write_port(outPortHandle, 131);

The lpBuf argument have to be pointers to buffers, not constants.
e.g.
char buffer;
buffer = 128;
result = write_port(outPortHandle, &buffer);
buffer = 131;
result = write_port(outPortHandle, &buffer);

What you really want to do is also pass a buffer length.
e.g.
    char buffer[]  = { 128, 131 };
    result = write_port(outPortHandle, &buffer, sizeof(buffer));

int write_port(HANDLE hComm,BYTE* lpBuf, size_t length) {

   ...

   // Issue write.
   if (!WriteFileEx(hComm, &lpBuf, length, &osWrite, &write_compl )) {
   ...


text:
Q: Como insertar un SP en masivo para varias base de datos desde un SP Gracias por tomarse el tiempo en ver mi consulta. ¿Cómo insertar un procedimiento almacenado en varias Base de Datos MSSQL', todo ejecutado con un sp.

A: Nota importante: Todo el código debería ser manejado desde un control de versiones como git, subversion o CVS y después usar Jenkins, Octopus o Azure Studio para implementar el código a distintos destinos. Sin embargo, esto requiere de un trabajo más amplio para su implementación.
Una de las maneras más claras de hacerlo sin un control se versiones, es usando los servidores registrados en SSMS. Lo primero que debemos hacer, es mostrar la pestaña de servidores registrados desde el menu Ver.

Después creamos un grupo que serán todos los destinos en los que se ejecutará el script.

Dentro de ese grupo, creamos un servidor registrado.

Es importante hacer notar, que debemos de crear un servidor registrado por cada base de datos. Y en cada servidor registrado debemos ir a las propiedades de conexión para indicar la base de datos a la que se conectará.

Una vez que tengas todos los servidores registrados dentro del grupo, puedes darle clic derecho al grupo y seleccionar Nueva Consulta. Eso hará que cualquier código que ejecutes desde ahí se ejecute en todas las bases de datos que configuraste.


text:
Q: What is the difference between Past Simple and Past Continuous for actions that are spread over time? There are actions that are spread over time, to snore or to play tennis for example. For me it is not always clear should I use Past Simple or Past Continuous for such actions. For me it is absolutely clear that I should use Past Continuous when the action is happening around some explicit or implicit point of time.

We were walking home when I met Dan

or

We were playing tennis at 10 a.m.

But this is not so clear when I don't have even implicit point of time. I've seen examples where Past Simple was used like

-What did you do yesterday morning? -I played tennis.

and I've also seen examples where Past Continuous was used like

You were snoring last night.

What would change in the meaning if I changed the sentences above to be like

-What were you doing yesterday morning? -I was playing tennis.

and

You snored last night.

I've also found example where both tenses were used for the same sentence. This table is from https://dictionary.cambridge.org/grammar/british-grammar/past-continuous-or-past-simple.

Doctors were treating patients in temporary beds and they were trying to do their best in a difficult situation.
Past continuous: writer chooses to show the events as ongoing at that time in the past.

Doctors treated patients in temporary beds and they tried to do their best in a difficult situation.
Past simple: writer chooses to show the events as finished.

To be honest, explanations in the right column are not completly clear for me and all my attempts to reduce all this to some well-defined system have failed. I can't decide what tense to choose in sentences like the ones I wrote above. I wonder how the thought process of native speakers is built when they choose tense in situations like this.


text:
Q: Change font size for text Is there an easy way to change font size for some none-header text with Semantic-UI, without make changes to the theme or use plain css?
I see for some elements, like button, one could use large, massive and so one. Perhaps something like this is possible for "normal text" also, but I cannot in the documentation see how, but I might be blind?

A: Semantic UI does not have that out of the box. You can write a CSS class that does it for you.
.large.text {
   font-size: 2rem;
}

This would make
Hi there
 have a size that is twice the size of the baseline text size.

A: You can also add your own CSS to component's .overrides file for the theme you are using and it will be available in your app.
For example, if you are using 'default' theme, you can add the following to button.overrides :
.large.text {
    font-size: 12px;
}

site.variables contains the default font size of the page, it can be changed there as well if it's to be changed everywhere

A: It is possible to be done in Fomantic-UI from version 2.7.2.
Fomantic-UI is a fork of Semantic-UI with ongoing development.
example of large text

docs: https://fomantic-ui.com/elements/text.html


text:
Q: Dense and complete totally ordered sets The totally ordered set $\mathbb{R}$ has the following properties.

*

*[Density]. Given any two $x,y \in \mathbb{R}$, we can find $\eta \in \mathbb{R}$ such that $x < \eta < y$.

*[Dedekind Completeness]. Every non-empty subset that admits an upper bound also admits a supremum.
Adjoining a greatest and/or least element to $\mathbb{R}$ preserves the above properties. This gives us a total of four non-isomorphic totally ordered sets satisfying properties 1 and 2, namely $$(-\infty,\infty),\quad[-\infty,\infty),\quad (-\infty,\infty],\quad [-\infty,\infty].$$
This is probably a silly question, but is the above list exhaustive (up to isomorphism)?

A: No.
A simple example that doesn't quite work is the total order on $\mathbb{R}\times\mathbb{R}$ defined such that $(a,b) < (c,d)$ if $a<c$ or if $a=c$ and $b<d$.  (In other words, uncountably many copies of $\mathbb{R}$, lined up end-to-end.)  This is dense and clearly not order-isomorphic to the real line (extended or not), because it contains uncountably many disjoint intervals that are order-isomorphic to the real line (unlike the real line itself, which can contain only countably many of these).  However, it is not Dedekind-complete per your definition, because $\{0\}\times\mathbb{R}$ is bounded above (say, by $(1,0)$), but has no least upper bound.  This can be repaired by considering $\mathbb{R}\times (\mathbb{R} + \{-\infty,\infty\})$ instead, in which case the supremum of $\{0\}\times \mathbb{R}$ is just $(0,\infty)$; and you are guaranteed greatest lower bounds as well.

A: Additional information for the interested reader:
Joel David Hamkins writes here that

The real line $\langle \mathbb{R},<\rangle$ is (up to isomorphism) the unique nonempty, separable, complete, dense, endless total order.


text:
Q: Changing data point shape of second y-axis with ggplot In my example I created a second y-axis in ggplot.
Instead of changing the colour for the data points of the second y-axis I want to change the shape.
But, of course, I get the error Scale for 'shape' is already present. Adding another scale for 'shape', which will replace the existing scale.
In the end I want to have a circle for "Large" and a filled circle for "Small" for "Visits" of the second y-axis.
This is my code:
Treatment <- c(rep(c("T/T"), times = 6),rep(c("R/R"), times = 6))
Size <- c(rep(c("Large", "Large", "Large", "Small", "Small", "Small"), times = 2))
Areatime <- c(240, 220, 120, 60, 55, 75, 90, 45, 70, 115, 40, 30)
Visits <- c(30, 45, 45, 65, 55, 55, 25, 35, 45, 75, 65, 55)
Counts <- data.frame(Treatment, Size, Areatime, Visits)

Counts$Treatment <- factor(Counts$Treatment, levels=c("T/T","R/R"))
Counts$inter <- interaction(Counts$Treatment, Counts$Size)
str(Counts)

ggplot(Count, aes(x = Treatment, y = Areatime)) +
  geom_jitter(aes(y = Areatime, shape = Size, width = 0.3)) +
  scale_shape_manual(values = c(0, 15), name = "Areatime", breaks = c("Large", "Small"),
    labels = c("Large", "Small")) +
  geom_jitter(aes(y = Counts*3, colour = Size, width = 0.3)) +
  scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]"))+
  scale_colour_manual(values =c(1, 2), name="Visits", breaks=c("Large", "Small"),
                     labels=c("Large", "Small")) +
  theme(axis.text.x=element_blank(),
                 panel.grid.major = element_blank(),
                 panel.grid.minor = element_blank(),
                 axis.ticks.x = element_blank(),
                 axis.line.x = element_blank(),
                 axis.line.y = element_line("black")) +
  facet_grid(.~Treatment, scales="free", switch = "x") +
  labs(y = "Average Areatime [sec]")

Plot of Example

A: I played a bit around and it is not an elegant hack, but maybe it is good enough. You can use shape = 21 this is a fillable shape. Then you need to match the fill colour with the background color so it looks like it is not filled. There where some typo's in your example code. I hope I fixed them correctly.
Treatment <- c(rep(c("T/T"), times = 6),rep(c("R/R"), times = 6))
Size <- c(rep(c("Large", "Large", "Large", "Small", "Small", "Small"), times = 2))
Areatime <- c(240, 220, 120, 60, 55, 75, 90, 45, 70, 115, 40, 30) Visits <- c(30, 45, 45, 65, 55, 55, 25, 35, 45, 75, 65, 55)

Counts <- data.frame(Treatment, Size, Areatime, Visits)

Counts$Treatment <- factor(Counts$Treatment, levels=c("T/T","R/R"))
Counts$inter <- interaction(Counts$Treatment, Counts$Size) str(Counts)

ggplot(data = Counts,
       aes(x = Treatment,
           y = Areatime)) +   geom_jitter(aes(y = Areatime,
                  colour = Size,
                  shape = Size),
              size = 3,
              width = 0.3) +   scale_shape_manual(values = c(0, 15),
                     name = "Areatime",
                     breaks = c("Large", "Small"),
                     labels = c("Large", "Small")) +   scale_colour_manual(values = c(1, 2)) +   geom_jitter(aes(y = Visits,
                  fill = Size),
              shape = 21, # this shape we can fill, but will give a border
              size = 3,
              width = 0.3) +   scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]"))+   scale_fill_manual(values = c("grey95", "red"),
                    name = "Visits",
                    breaks = c("Large", "Small"),
                    labels = c("Large", "Small")) +   guides(colour = guide_legend(title = "Areatime")) +   theme(axis.text.x=element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks.x = element_blank(),
        axis.line.x = element_blank(),
        axis.line.y = element_line("black")) +   facet_grid(. ~Treatment,
             scales="free",
             switch = "x") +   labs(y = "Average Areatime [sec]")

This while produce:

A: Great, thanks! I just changed the colour for both to black instead of red and made the background the same gray colour and added the *3 in the second geom_jitter after "Visits" again (you just forgot because of my typo). So, the solution is:
ggplot(data = Counts, aes(x = Treatment, y = Areatime)) +
  geom_jitter(aes(y = Areatime, colour = Size, shape = Size), size = 3, width = 0.3) +
  scale_shape_manual(values = c(0, 15), name = "Areatime",
                     breaks = c("Large", "Small"), labels = c("Large", "Small")) +
  scale_colour_manual(values = c(1, 1)) +
  geom_jitter(aes(y = Visits*3, fill = Size), shape = 21, size = 3, width = 0.3) +
  scale_y_continuous(sec.axis = sec_axis(~./3, name = "Relative Visits [%]")) +
  scale_fill_manual(values = c("gray95", "black"),name = "Visits",
                    breaks = c("Large", "Small"), labels = c("Large", "Small")) +
  guides(colour = guide_legend(title = "Areatime")) +
  theme(axis.text.x=element_blank(),
                panel.background = element_rect(fill = "gray95"),
                panel.grid.major = element_blank(),
                panel.grid.minor = element_blank(),
                axis.ticks.x = element_blank(),
                axis.line.x = element_blank(),
                axis.line.y = element_line("black")) +
  facet_grid(. ~Treatment, scales="free", switch = "x") +
  labs(y = "Average Areatime [sec]")

Solution


text:
Q: What's the best method to be overloaded in ViewPage for inserting some script to all ViewPage? I want to insert some script that is required for my JavaScript library in all view pages. I know that Asp.net MVC is built on Asp.net Framework. Therefore, I can override many methods in "System.Web.UI.Page" class that is a parent of "System.Web.Mvc.ViewPage" class.
Nevertheless, I can do it by override Render method but it makes all view pages be invalid for XHTML 1.0 strict. Correct JavaScript must be placed in header tag of HTML document.
public class ViewPage<TModel> : ViewPage where TModel : class
{
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        base.Render(writer);
        writer.Write("");
    }
}

Thanks,
PS. I know I can create some code in each master page for doing that. However, it is a quite complicate for other developers to start using my JavaScript source code.

A: Don't do it in code; do it in markup. Add the script tag to your Site.Master, in the correct, valid place.

A: I just see head of both View Page & View Master Page always run at server. Please look at the following templates.
Default Template of ViewPage
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

Default Template of ViewMasterPage
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>

        <asp:ContentPlaceHolder ID="MainContent" runat="server">

        </asp:ContentPlaceHolder>

Therefore, it is very easy to solve this question by adding some control to header control.
public class ViewPage : mvc.ViewPage
{
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        if (Header == null)
            throw new Exception("Header object is null. Please set header runat=\"server\".");

        Header.Controls.Add(new LiteralControl(CommonHelper.JavaScript(MvcUtils.GetApplicationUrl(Request) ,string.Empty)));

        base.Render(writer);
    }
}


text:
Q: Gstreamer understanding Okey guys I thought that after few days with gstreamer I understand it I wrote some pipelines with would logically work but I have headache when it comes to saving a stream to file.
gst-launch-1.0 rtspsrc location=rstp://ip/url ! decodebin ! textoverlay text="Work you damn thing " ! x264enc ! h264parse ! mp4mux ! filesink location=some_video.mp4

Okey this is my logic:
 1. rtspsrc - has one pad and it's src it outputs x/rtps
 2. decodebin - is a bin (bunch of elements) it has ghost pads and one of those
    sink pads accept x/rtps then on source pad it generates raw video
 4. x264enc - accepts raw video on sink pad and encodes it to a h264 raw
    video
 5. h264parse - accepts raw h264 on sink and it parse it to h264 video
 6. mp4mux - muxing it
 7. filesink - it sinks it to a file

Everything is fine but after I finish recording it and when I try to play it I got this error:

This file contain no playable stream

If there are some experianced users of gstreamer out there I would like to ask them where is the leak in my logic and what is cause of this error ?

A: You will have to send an EOS event to the pipeline, then wait for the EOS message on the bus of the pipeline, and only then shut down the pipeline (changing state from PLAYING to READY or NULL).
If you use gst-launch-1.0, use the -e parameter. When you then hit ctrl+c it will do exactly that before shutting down everything.
This is needed as in the end mp4mux needs to finalize the file and write information about the complete stream in the file. Otherwise the file is not a valid MP4 file.


text:
Q: Calling ActionScript 2.0 events from another project I have an ActionScript 2.0 file that contains a small library.
This library parses an XML file.
I have assigned an onComplete function on the onLoad function of the XML.
For example:
------------ mysmalllib.as --------------
r_xml = new XML();
r_xml.onLoad = onComplete;

function onComplete(success:Boolean) {
           // some stuff
           OtherFunction();
        }

------------ mainProgram.fla --------------
import mylib.mysmalllib;

var flashCall = new mylib.mysmalllib;

function toBeCalled() {
        //
}
------------------------------------------------

The thing that I want is, whenever the OtherFunction is called (that exists in mysmalllib), another function in my main program to be notified (toBeCalled). I suppose it has something to do with dispatch but I'm not any good in AS.
Thx

A: I did a quick google search and found this:
http://flash-creations.com/notes/asclass_eventdispatcher.php
It seems to cover what you need to know about EventDispatcher in AS2


text:
Q: AWS Lambda return both a base64 encoded data and a text string in body response I am using an AWS Lambda implementation with Node.js to generate a PDF file. I have the following callback that returns the pdf in an encoded base64 result. This works great for me:
return callback(null, {
    statusCode: 200,
    body: new Buffer(data).toString('base64'),
    isBase64Encoded: true,
    headers: {
      'Content-Type': 'text',
    },
  })

However, I would like to add further information with my response - not just the PDF bae64 encoded data, but some string type results that I can use further down my active application connected to this Lambda function. I'd like to return the base64 data and string data, something like this:
return callback(null, {
    statusCode: 200,
    body: JSON.stringify(
        {
            message: 'hello world',
            report: new Buffer(data).toString('base64')
        }
    ),
    isBase64Encoded: true,
    headers: {
      'Content-Type': 'text',
    },
  })

But this is failing for me. How would I refactor the above to return both string data and base64 data? I'm also having to force the isBase64Encoded setting to true, which may clash with my new requirement to return both base64 and normal string data.

A: The Content-Type of your response is not text - since you are returning JSON, a application/json value would make more sense and might alleviate some of the issues you are having. It would be helpful if the post could be updated with some more relevant details of the errors you are encountering.
One other possible work-around would be to add the message (and any other string values) as HTTP headers on the base64 encoded response you already have working. Then your client can decode the HTTP response whose body contains the base64 encoded PDF and HTTP headers x-custom-message (or something similar) set to hello world.


text:
Q: SSH best practice with a privileged port I am using cPanel on Centos 7.7 and I am a bit confused about this note in the documentation:

We recommend that you use a privileged port of 1 - 1023 that another
  service does not currently use. Only the root user can bind to ports 1
  - 1023. Anyone can use the unprivileged ports of 1024 and greater.

I am not certain what this statement implies - SSH defaults to port 22. But the recommendation is to change the port to something else.
Port 22 is already privileged, but what's the difference if I change it to 483 vs. 2022 in regards to the above note?  Regardless of what port I change it to, anyone can still SSH to that port.

A:
I am not certain what this statement implies - SSH defaults to port
  22. But the recommendation is to change the port to something else.

I don't read it like that - they just say that you are free to change
port that SSH daemon is listening on.

Port 22 is already privileged

Yes, it is.

but what's the difference if I change it to 483 vs. 2022

Almost none, except that all SSH clients that I know - OpenSSH, Putty,
dbclient will try to use port 22 by default so you will have to
provide a port number manually when connecting to a host using a
non-standard port but as you can save port number in a config it's a
one-time job.  And from a practical standpoint, some people prefer
setting SSH daemon to listen on port 80 or 443 to pretend HTTP or
HTTPS respectively so that SSH connections will not be blocked by
overzealous firewalls in hotels, airports etc.

in regards to the above note? Regardless of what
  port I change it to, anyone can still SSH to that port.

I think that by Anyone can use the unprivileged ports of 1024 and
greater. they meant that local non-root users can use non-privileged ports
for their services.  It's not about connecting to the services
listening on a given port from outside, it's about directing local
services to use that port. As to why do they recommend using a
privileged port for SSH service - the reason is that:

The TCP/IP port numbers below 1024 are special in that normal users
  are not allowed to run servers on them. This is a security feaure, in
  that if you connect to a service on one of these ports you are fairly
  sure that you have the real thing, and not a fake which some hacker
  has put up for you.

(from
http://info.cern.ch/hypertext/WWW/Daemon/User/PrivilegedPorts.html)
To expand on it further - as discussed in these comments on
ServerFault:

It is precisely the reason you shouldn't run privileged daemons on
  ports above 1023. Any user (local or remote) can DDoS it until it
  crashes, then a local user (i.e. PHP, Apache, MySQL, anything that has
  a remote execution vulnerability) can start its own daemon on the same
  port and then wait for you to connect.


text:
Q: Android button click method(s)? I'm fairly new to android programming but I have a questions about clicking on buttons
I've tried several tutorials but not sure if I get something
when I need a button to do something for me, I can do it in to ways:
a.add the line -  android:onClick="methodName"
b. or just add an onClink listener
what is the difference between these to ways? or maybe they are not doing the same thing at all and I'm just confused?
thanks.

A: They do the same thing.
In case A you have to just implement onClick method.
In case B you have to first set OnClickListener and then implement onClick method.

A: One is set in the xml file, the other is set at runtime.  That's the primary difference.
The other difference is setting method name in xml makes it literally look for a method name, so you can plug it into different activities, that implement the method differently, and as long as the method uses that name, it will execute.


text:
Q: Would low frequency signal (10kHz) have reflection on conducting wires as well? I am connecting a signal source of 10kHz sine wave with a driver which is a voltage follower made by an OpAmp. The follower has one input and two identical outputs. One output is connected with a device(LOAD) to drive the device(LOAD); the other is connected with an oscilloscope for measuring.
The OpAmp used is ADA4610

simulate this circuit – Schematic created using CircuitLab
The first picture:  Voltage follower is not connected with the device(LOAD) and its output signal is pure.

The second picture: Voltage follower is connected with the device(LOAD). It can be observed that there are harmonic noises showing up.

Updated observation:

*

*When I change the load to 1kOhm resistor, the output of OpAmp does not show any distortion.

*When actual load is used (around 50Ohm), distortion shows up.

*My suspect is that large output current could lead to distortion. However, I did not find related information in the datasheet.

My question is:

*

*Are the harmonics caused by reflection?

*Would very low frequency signals have reflection as well?

*How to export pure sine waves without distortion in this case?

A: No, a reflection is a linear phenomenon and cannot produce harmonics.
The harmonics are generated by nonlinearities in your buffer amplifiers (voltage followers). -72 dB relative to the fundamental is actually pretty good. What kind of opamps are you using? You may need to upgrade to a precision high-bandwidth unit in order to do any better.


text:
Q: Is the answer correct? I had to simplify it:
$$
\cos^2(\pi+x)+\cos^2\left(\frac{\pi}{2}+x\right)=-\cos^2(x)-\sin^2(x)=-(\cos^2(x)+\sin^2(x))=-1.
$$
My answer turned out to be wrong. Could someone point out where is the mistake?

A: Note that
$$
\cos(\pi+x) = \cos \pi \cos x - \sin \pi \sin x = -\cos x
$$
and
$$
\cos\left(\frac{\pi}{2}+x\right) = \cos \left( \frac{\pi}{2} \right) \cos x - \sin \left( \frac{\pi}{2}\right) \sin x = -\sin x.
$$
So
$$
\cos^2(\pi+x)+\cos^2\left(\frac{\pi}{2}+x\right)
= \cos^2 x + \sin^2 x =1.
$$

A: $cos(x) $ is negative in $2nd $ and $3rd$ quadrant , but $cos^2(x)$ is positive everywhere, so the answer should be $1$ as $$cos^2(\pi +x)=(cos(\pi+x))^2=(-cos(x))^2=cos^2(x)$$similarly$$cos^2({\pi\over 2}+x)=(cos({\pi\over 2}+x))^2=(-sin(x))^2=sin^2(x)$$and $$cos^2(x)+sin^2(x)=1$$

A: Note that:
$\cos^2(\pi+x)+\cos^2[(\pi/2)+x]=(\cos\pi \cos x -\sin\pi \sin x)^2+[\cos(\pi/2)\cos x -\sin(\pi/2)\sin x ]^2=(-\cos x)^2+(-\sin x)^2=1$

A: Although $\cos (\pi +x)=-\cos (x) $ and $\cos (\frac {\pi}2+ x)=-\sin (x)$ are absolutely true, $(-\cos (x))^2=-\cos^2 (x) $ and $(-\sin (x))^2=-\sin^2 (x) $ are absolutely false.


text:
Q: How should I return errors in asp .net core API I'am working on my private project using .Net Core and Angular and i have a little pickle with how should I return errors.
My backend has layers(controllers, services, repositories and entity).
I've created general response object I want to return. In my service method I set different errors like "NotFound" or "Internal server error" as a StatusCode.
I don't want to do switch case on StatusCode and return different error based on that in controller because I don't think it's a good solution.
Returning ApiResponse object will cause that I always will have 200 code and to know if there's any error I need to check the status code of the returned object in the Angular. I don't know if that's a good solution.
And I want to keep these layers. I want controller to just handle the request, service to have all the logic and repository to do CRUD actions.
So how should I return errors from my service layer to controller?
That's one version of my controller method.
    [Authorize]
    [ApiValidationFilter]
    [HttpPost("updateFacebookUrl/")]
    public async Task<ApiResponse> UpdateFacebookURL([FromBody] UpdateURLVm updateURLVm)
    {
      return await _userInfoService.UpdateFacebookURL(updateURLVm);
    }

And that's second version of my controller method.
    [Authorize]
    [ApiValidationFilter]
    [HttpPost("updateInstagramUrl/")]
    public async Task<IActionResult> UpdateInstagramURL([FromBody] UpdateURLVm updateURLVm)
    {
      var result = await _userInfoService.UpdateInstagramURL(updateURLVm);

      if (result.StatusCode != (int)HttpStatusCode.OK)
      {
        return BadRequest(result);
      }

      return Ok(result);
    }

That's my service method.
    public ApiResponse UpdateInstagramURL(UpdateURLVm updateURLVm)
    {
      try
      {
        var user = _unitOfWork.userRepository.FindByCondition(x => x.Id == updateURLVm.UserId).FirstOrDefault();

        if (user == null)
          return new ApiResponse((int)HttpStatusCode.NotFound, "User not found");

        user.Instagram = updateURLVm.URL;

        _unitOfWork.userRepository.Update(user);
        _unitOfWork.Complete();

        return new ApiResponse((int)HttpStatusCode.OK);
      }
      catch (Exception ex)
      {
        return new ApiResponse((int)HttpStatusCode.InternalServerError, "Something went wrong");
      }
    }

Return object.
 public class ApiResponse
  {
    public int StatusCode { get; private set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
    public string Message { get; private set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
    public object Result { get; private set; }

    public ApiResponse(int statusCode, string message)
        : this(statusCode)
    {
      this.Message = message;
    }

    public ApiResponse(object result) :
      this(200)
    {
      Result = result;
    }

    public ApiResponse(int statusCode)
    {
      this.StatusCode = statusCode;
    }
  }

A: I'd throw exception in my core service or repository and let middleware handle it.
ApiError is my custom class and some things might not be the same as this was written with .NET Core 2.2 I imagine you are using 3.x. And a quick note (if I may) those api endpoint urls are not very RESTful..
   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseExceptionHandler(appBuilder =>
        {
            appBuilder.Run(async context => {
                var ex = context.Features.Get<IExceptionHandlerPathFeature>();
                if (ex?.Error is NullReferenceException)
                    context.Response.StatusCode = 404;
                else if (ex?.Error is InvalidOperationException)
                    context.Response.StatusCode = 400;
                else
                    context.Response.StatusCode = 500;

                context.Response.ContentType = "application/json";

                ApiError error = new ApiError()
                {
                    Code = context.Response.StatusCode,
                    Message = env.IsDevelopment() ? ex?.Error.Message : "An unexpected error happened. Try again later."
                };

                await context.Response.WriteAsync(JsonConvert.SerializeObject(error)).ConfigureAwait(false);
            });
        });
   }


text:
Q: Lazy Loading questions with EF5 and Code First It seems that lazy loading does not work the same with code-first as it does with db-first:
Consider:
public class Project
{
    [Key]
    public long ProjectId { get; set; }

    [Required]
    [MaxLength(60)]
    public virtual string Name { get; set; }
}

And:
public class TestCase
{
    [Key]
    public long TestCaseId { get; set; }

    [Required]
    [ForeignKey("ProjectId")]
    public virtual Project Project { get; set; }
    public virtual long ProjectId { get; set; }
}

In this DbContext:
public class TestDbContext : DbContext
{
    public TestDbContext() : base("TestIckle")
    {
    }

    public DbSet<Project> Projects { get; set; }
    public DbSet<TestCase> TestCases { get; set; }
}

When I try to to this in my code it does not work:
    Console.WriteLine(_db.Configuration.LazyLoadingEnabled); //prints true
TestDbContext _db = new TestDbContext();
var testcase = _db.TestCases.Create();
testcase.Project = _db.Projects.Find(7);

//the following line outputs 0 with Code-First
//the following line outputs 7 with DB-First
Console.WriteLine(testcase.ProjectId);

Is a code-first model less capable than a db-first one? Seems odd that I would have assign the nav property and the pkey for it, which makes me think I have something configured wrong.
Should the following ever work?
var x = _db.TestCases.Create();
x.ProjectId = 7;
Console.WriteLine(x.Project.Name); //this never seems to work

Would be nice, seing as x knows which context it is attached too, I would have thought it could have handled this situation.
Thanks.

A: In those last two examples, Entity Framework is not loading up those entities because you have not committed those relationships to the database. It won't automatically populate the FK ID when you've assigned the navigation property, nor will it populate the navigation property when all you've done is set the ID.
Entity Framework is smart enough, though, to know that when you assign to either of those properties (i.e. the ID or the navigation property) that it will populate the correct values in the future for both properties. But before you do any actual commit it will not know to automatically populate that value. Nor should they, if you think about it: What would happen if there's a drop down on a page that maps to one of those properties? Every single time a user clicks on it there would have to be a database call to correctly keep the mapping. That could translate to a much slower, much more breakable application.


text:
Q: Chrome Extension - "could not load javascript '' for content script" Can anyone see why the below manifest (truncated for brevity) is producing:

could not load javascript '' for content script

{
    ...
    "content_scripts": [{
        "matches": ["<all_urls>"],
        "js": [
            "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js",
            "assets/js/content-script-curr-tab.js"
        ]
    }],
    ...
    "content_security_policy": "object-src 'self'; script-src 'self' https://apis.google.com https://cdnjs.cloudflare.com"
    ...
}

If I remove the reference to the Cloudflare script, it loads, yet I've clearly whitelisted the Cloudflare CDN in the content security policy.


text:
Q: limitations of running WSO2 Carbon 4.x and WSO2 Carbon based products in webapp mode? WSO2 Carbon is not officially supported in webapp mode (see the selected answer here).  However, I have no choice - If I want to run carbon, it must be run in webapp mode.
There are some detailed instructions here for setting up carbon 4.x in webapp mode.
I am concerned is that standalone mode is strongly recommended by WSO2.
My Questions are:  What are the limitations:

*

*when running Carbon 4.x in webapp mode?

*when running other Carbon based products (e.g. ESB, AS, etc) in webapp mode?

If possible, please provide a detailed list of the limitations.

A: Limitations:

*

*When you take the ESB, as you might have seen it exposes ports 8280/8243 (HTTP/HTTPS) in addition to 9763/9443 which is exposed through the servlet transport. In the case of ESB you need (and want) to use port 8280/8243 when you're interacting with the ESB because those are the two non-blocking high performant transports. When you deploy ESB on top of another web container, you're limited by the servlet transports provided by the container. So we can't get the desired performance out of the ESB for proxying and other scenarios.

*Complexities involving using web container functionalities. Carbon has its own clustering/caching/security etc... infrastructure. When you deploy Carbon as a webapp then we should look at supporting all those functions provided by the container for different containers. Which is complex, not consistent and in some cases sub-optimal

IMHO those were the two most important factors why it's discouraged to deploy Carbon on top of other containers. Going with a standalone deployment approach it has contributed immensely to not include web container specific "hacks" into the platform to get things done and have a much cleaner consistent platform.

A: One issues with deploying Carbon in web-app mode is that this deployment model is not supported by WSO2.  I will add more issues to this answer as I encounter them...

A: AFAIK, webapp is not supported... Please refer this thread :Running WSO2 Carbon as Web Application in Tomcat
Regards,
Mohan


text:
Q: How to read and use a column in a local CSV file with javascript? I have a CSV file and I need to display in the terminal only the second column. I'm using javascript and nodejs. My CSV file is in a local folder. My CSV data look like this:
name,emails,name1,email1,name2,email2,name3,email3,name4,email4,name5,email5

It's like an array with two columns and six rows, first one with name and second one with emails. I only want to return the list of emails without the heading in the terminal. Later I'll have to use this email list to compare it with an other array.
I think it is possible with papaparse but I don't understand how to use it.
I also know that fs module can be use to read the entire file.
If it's possible to convert the data in an array with or without keys/values like this it will also be perfect:
[ name:'name1', email:'email1', name:'name2', email:'email2', name:'name3', email:'email3', name:'name4', email:'email4', name:'name5', email:'email5' ]

Knowing that I also have to do it with an other CSV file that contain 9 columns and 960 rows.

A: This code should parse a CSV file in the format you mention, e.g.
test.csv

name,emails
name1,email1
name2,email2
name3,email3
name4,email4
name5,email5

app.js
const Papa = require('papaparse');
const fs = require("fs");

let csvData = fs.readFileSync("test.csv", "utf-8");
csvData = csvData.trim().replace(/([^,]+),\s*([^,]+),\s*/gi, '$1,$2\n');
console.log("Adjusted csv:", csvData);

let { meta, data } = Papa.parse(csvData, { header: true });

console.log("Parsed data:", data);
console.log("Metadata:", meta);

The parsed data would look like so:
[
  { name: 'name1', emails: 'email1' },
  { name: 'name2', emails: 'email2' },
  { name: 'name3', emails: 'email3' },
  { name: 'name4', emails: 'email4' },
  { name: 'name5', emails: 'email5' }
]


text:
Q: What Notation is this? When $p$ is prime, show that $v: Z^*_p \rightarrow U_2$
I know that the $Z_p$ is the elements $\{0,1,2,\cdots,p-1\}$ But what about the star on top of the $p$? Is that the group operation? Because it's supposed to be part of a ring. I'm just not too sure.

A: For a ring $R$, $R^*$ is defined as $\{r \in R: r \text{ is a unit}\}$. If $R$ is a field, then $R^* = R \setminus \{0\}$.
//Edit: … and $r \in R$ is a unit if there exists an $s \in R$ with $r \cdot s = s \cdot r = 1$.

A: Putting a star, It means the set of invertible elements in $Z_p$ and if you are considering the multiplicative group $Z_p$ then $[0]$ is the only element that is not invertible.
Thats why the number of elements in $Z_p^*$ is $p-1$
However, When considering $Z_n^*$ in general, you may have more elements that are not invertible, not just $[0]$
Example: $[2]$ in $Z_4$ is not invertible
If you want to test whether an element is invertible in $Z_n$ you just see if the greatest common divisor of that element and $n$ is 1
if the gcd is 1 then the element is invertible.
If not then it's not invertible


text:
Q: Mobile site off center when jQuery button is triggered I have a centering issue that seems to be caused by my animated scroll function. When the button is triggered, the entire site becomes off-centered, with padding on the right side. This only happens with mobile devices / touch screens. If you avoid the button, no issues arise.
Thanks in advance for your time and help, I'm very stumped!
Website
Screenshot
HTML

JS
(function($){

// defines various easing effects
$.easing['jswing'] = $.easing['swing'];
$.extend( $.easing,
{
        def: 'easeOutQuad',
        swing: function (x, t, b, c, d) {
                return $.easing[$.easing.def](x, t, b, c, d);
        },

        easeOutQuad: function (x, t, b, c, d) {
                return -c *(t/=d)*(t-2) + b;
        },
});

$.fn.animatescroll = function(options) {

    // fetches options
    var opts = $.extend({},$.fn.animatescroll.defaults,options);

    // make sure the callback is a function
    if (typeof opts.onScrollStart == 'function') {
        // brings the scope to the callback
        opts.onScrollStart.call(this);
    }

    if(opts.element == "html,body") {
        // Get the distance of particular id or class from top
        var offset = this.offset().top;

        // Scroll the page to the desired position
        $(opts.element).stop().animate({ scrollTop: offset - opts.padding}, opts.scrollSpeed, opts.easing);
    }
    else {
        // Scroll the element to the desired position
        $(opts.element).stop().animate({ scrollTop: this.offset().top - this.parent().offset().top + this.parent().scrollTop() - opts.padding}, opts.scrollSpeed, opts.easing);
    }

    setTimeout(function() {

        // make sure the callback is a function
        if (typeof opts.onScrollEnd == 'function') {
            // brings the scope to the callback
            opts.onScrollEnd.call(this);
        }
    }, opts.scrollSpeed);
};

// default options
$.fn.animatescroll.defaults = {
    easing:"swing",
    scrollSpeed:800,
    padding:0,
    element:"html,body"
};

}(jQuery));

A: I had the exact same problem!
My Fix:
body{
    width:100%;
    overflow:hidden;
 }


text:
Q: Display coordinates on a Google Map in Rails app Stage:
In a Rails 3.2 application, suppose I have this model:
Point(id:integer, latitude:decimal, longitude:decimal, zoom:integer)

Using scaffold generator, it generates a form with 3 text fields like this:
<%= f.text_field :latitude %>
<%= f.text_field :longitude %>
<%= f.text_field :zoom %>

I really don't want to have this.
I prefer to have a Google Maps map and use it for set coordinates to the form and edit them.
I have seen that there are many solutions using Javascript, but if it is possible to avoid to use directly JS, it could be a good choice.
Question:

*

*Is the a gem that help to make this?

*What is good implementation of this?

Thank you very much

A: You won't be able to do this without JavaScript.
What you need to do is:

*

*Add the google maps map to the page

*Add a click listener on the map

*

*when the user clicks on the map (optionally place a marker and) get the lat/lng coordinates of the event, and use JS (maybe with the help of jQuery) to set your :latitude and :longitude form fields, as well as the current zoom level


text:
Q: Magento 1 stop backup process I started a backup from the back-end, and my website switch to maintenance mode.But it is taking very long time to backup, is it possible to stop?

A: Try this
ps -aux | grep 'php bin/magento'
use second column number or [PID] into this command kill -9 [PID]
Tell me if its works or not

A: Please remove maintenance.flag file from var directory. your site will back


text:
Q: Python:How to change the granularity of axes in matplotlib plot? I am wondering how to can change the number of bins in a line plot in matplotlin python pandas?
like if my x axis range is [0,1000] and I want it be decided to 200 ticks. Can anybody help?

A: Use the set_ticks function
from matplotlib import pyplot as plt

fig, ax = plt.subplots()
ax.set_xticks([0,200,400,800,1000])


text:
Q: How to extract a SQL database design into Visio in a manageable format? I have a database diagram that I would like to extract from SQL and manipulate it to create a user-friendly and easier-on-the-eye ERD.  The database contains over 200 tables and I would like to map the tables out to show other how it works to others.
I don't want to reverse engineer as Visio reformats the ERD and no longer looks like the model I have in database designs.
I'm aware that you can right-click and copy-to-clipboard however this captures the model as an image which means I can't manipulate it.
Is there an alternative piece of software out there that I'm not aware of?

A: I'd check out Embarcadero tools Try Data Architect.

A: You can use the "free" MySQL workbench if you are using MySQL https://www.mysql.com/products/workbench/ to reverse engineer the model from an SQL file then re-organize the model into multiple pages.


text:
Q: Уменьшение размера файла при создании клона репозитория Работаю над файлом в проекте, после завершения делаю комит в репозиторий. Далее мне нужно например сделать еще одну копию репозитория. Делаю клон. И сравниваю файлы. У первого размер 44,9 КБ, а в копии репозитория 44,0 кб. Текстовое содержимое одинаковое. Почему различается размер файлов при идентичном содержимом?

A: Возможно в первом случае у Вас окончания строк CRLF, а во втором LF. Git пытаеться оптимизировать и если в настройкая явно не указанно, конвертирует CRLF в LF. core.autocrlf


text:
Q: How do I clone/extend a FormData object? I have a set of POST endpoints where I need to send a collection of static parameters plus a few dynamic parameters specific to the request.
For every request, I am doing the following:
var staticParams = {...}, // some arbitrarily large object
    localParams = {...},
    formData = new FormData();

Object.keys(staticParams).forEach(function(key) {
  formData.append(key, staticParams[key]);
});

Object.keys(localData).forEach(function(key) {
  formData.append(key, localParams[key]);
});

It's not a huge tax, but it seems silly to repeat the first enumeration for every request. How can I clone and extend my FormData object so that I don't have to build the whole thing every time?

FWIW, I know how to clone Objects; I believe FormData is unique in that the key/value pairs are not simply keys on the Object, so I am unclear on the correct way to clone it.

A: You could use the following function to be able to extend your objects.
if(Object.prototype.extend === undefined) {
    Object.prototype.extend = function(obj) {
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                this[i] = obj[i];
            }
        }
    };
}

Which adds the properties of the object 'obj' to the object the function is called on.
In your case, you could use it as follows:
formData.extend(staticParams);
formData.extend(localParams);


text:
Q: Как сослаться на вычисляемый столбец? Есть задача:
Какая разница в стоимости между самым дорогим и самым дешевым заказом из США.
решить нужно через онлайн тренажер вот здесь:
https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
SELECT Customers.Country, SUM(Quantity*Price) as Sum, OrderDetails.OrderID
FROM Customers join Orders ON Customers.CustomerID = Orders.CustomerID
join OrderDetails ON Orders.OrderID = OrderDetails.OrderID
join Products ON OrderDetails.ProductID = Products.ProductID
where Customers.Country IN ('USA')
GROUP BY OrderDetails.OrderID

Написал код, который считает стоимость заказов из штатов. Есть ли способ обратиться к вычисляемому столбцу Sum? Потому, что если в SELECT прописывать
MaX(Sum)-Min(Sum) as diff
появляется ошибка no such column:

A: Получилось решить через подзапросы:
WITH Summa_z AS
    (SELECT  OrderDetails.OrderID, Quantity*Price as Summa FROM Products
        INNER JOIN OrderDetails ON OrderDetails.ProductID = Products.ProductID GROUP BY OrderDetails.OrderID ORDER BY Quantity*Price DESC),
     USA AS
    (SELECT  Orders.CustomerID, Country, OrderID  FROM Customers
        INNER JOIN Orders ON Orders.CustomerID = Customers.CustomerID WHERE Country IN ('USA'))

SELECT Max(Summa)-Min(Summa) as Result FROM Summa_z join USA ON USA.OrderID = Summa_z.OrderID


text:
Q: Want to sort of create a distributed file system? Where I work there is about 400 employees split between several campuses at the two main campuses we have servers set up and shared folders on the servers. I want to setup a system so  we have one shared folder that users see but then have copies of all the files on both servers and access the files based on which campus the user is at to stop people having wait while files transfer, and then only if a file is changed force them to have to access the latest copy of the file, and then transfer all files changed overnight so it is not slowing down the network during the day.
Can anyone tell me is there a system that already does this? Or what keywords I should be using when trying to search for a system that does this?
I have been looking at creating a system to do this using MS SQL Server 2012 FileTables and putting triggers on the tables to check which table had the latest copy of the file and creating a store procedure to compress and transfer changed files overnight.

A: What about Distributed File System?

A: There are multiple distributed filesystems for this.
AFS (Andrew FileSystem) might be interesting:
http://www.openafs.org/
Some other solutions are:
for Linux

*

*FedFS, the Federated File System which uses only NFS at this moment

*DFS for Samba

fow Windows

*

*DFS = Distributed File System, search Wikipedia for it (I'm not allowed to post >2 links here, because I'm a new user)

Personally I don't have much experience with these solutions. However, I suggest you should investigate AFS first, it is a well-maintained cross-platform system.

A: Assuming you're using Windows throughout your company, BranchCache may be of interest.  NB: this requires that your users are on at least Windows 7.
http://technet.microsoft.com/en-us/library/hh831696.aspx
This allows you to host files on a central server, with cached copies being held either on local servers at each branch, or on local machines (i.e. if you have branches without server rooms / don't want to invest extra in the cache server).  If the option's available I'd recommend having a cache server at each office as this will improve the reliability of file availability (i.e. not affected by a user rebooting or turning off their workstation).
I don't think there's any precache OOTB (though not 100% sure), but this could be enabled easily through scripting (i.e. have a script at each branch which requests any new files, thus causing them to become cached).


text:
Q: tkinter window without the surrounding I was wondering if there is a way to remove the borders (titlebar with buttons and the edges on each side) of a tkinter window. Does someone know how to do that?
Couldn't find any solution for this in the web.

A: Try to set borderwidth and highlightthickness to 0


text:
Q: Auto Mount of a Network Drive I've edited my fstab file to provide all the details of my network drive. It works fine, however, after my laptop (re)start, I still need to run manually sudo mount -a.
Here is fstab line:
///192.168.1.1/my_network_folder /home/my_user/net_drive cifs credentials=/home/my_user/.smbcredentials,vers=3.0,iocharset=utf8,gid=1000,uid=1000,file_mode=0777,dir_mode=0777 0 0
How can I automate it (kind of autoexec.bat from Windows), so I don't have to run mount manually each time?
Thanks,
Paul

A: It's likely that your network isn't up yet when your system tries to automount the share. Try adding: x-systemd.automount,x-systemd.requires=network-online.target to the fstab entry.
If that doesn't work you could try adding mount -a to your /etc/rc.local file as that gets executed rather late during bootup.


text:
Q: how to animate the uilabel view which has some text , in obj c in my app i am planing to add the animation for the textLabels, which should come from left side of the screen
i have used following code but its crashing
(void)animateLoop {

    UILabel *mylab;
    mylab.text=@"SAAAAdiiiii";
    mylab.frame = CGRectMake(-mylab.bounds.size.width, 100, mylab.bounds.size.width, mylab.bounds.size.height);
    [UIView beginAnimations:@"timesquare" context:nil];
    [UIView setAnimationDuration:5];
    [UIView setAnimationRepeatAutoreverses:(YES)];
    [UIView setAnimationRepeatCount:10];

    mylab.frame = CGRectMake(480, 100, mylab.bounds.size.width, mylab.bounds.size.height);

    [UIView commitAnimations];
 }

n i called this in the viewDidload
but it was crashing at this line    mylab.text=@"SAAAAdiiiii";   crashLog:invalidargument
can any one tell me how can i  animate the uilabel
thanx in advance

A: You need to alloced the UILabel . means first create the memory for you label ...
UILabel *mylab = [[UILabel alloc] initWithFrame:CGRectMake(x,y,width,height)];
mylab.text=@"SAAAAdiiiii";

Suggest you to have  UILabel *mylab; as iVar , because it has to be released.

A: You have to allocate and init your UILabel first..
instead of UILabel *mylab; try UILabel *mylab = [[UILabel alloc] init];
You also have to release it somewhere and you have to add the label to your view (something like [self.view addSubview:mylab];).


text:
Q: how to bind a server to different ports instead of a sing le one? i am writing a tcp server code to monitor tcp/ip traffic coming to my system.
Can anyone have the idea about how to bind to different tcp ports,instead of a single port.
or can anyone ve the idea about how to do it?
expecting ideas from alll good hearts

A: Take a look at libpcap, it's closer to what it sounds like you need.

A: For each port you are listening on you need to prepare the data structures required to bind to that port and listen on it. You cannot listen on ALL ports -- unless you work at driver level and intercept the packets before they are dispatched to the application listening on a port. So effectively, if you will, inside your app, you will start multiple servers -- one for each port -- but once you have acquired a client connection you can share the same code for all requests coming on all ports (you are listening to).

A: You'd need to create one socket per port you want to bind.  But how this will help you to "monitor tcp/ip traffic coming to your system" I am not sure.  Probably it won't.


text:
Q: Using CSS3 pie on a dynamic knockout js application I've built a single page application using Knockout.js, where html nodes get added, moved and destroyed regularly, I've been developing it in Chrome, Firefox and IE 9, but had been planning to add IE8 and IE7 CSS3 support using CSS3 PIE.
Now I've got to the stage where I'm adding PIE and I seem to have hit a problem.
I've applied the behaviour to two divs - one is in the initial HTML source and the other is dynamically added.
The initially rendered div has a box shadow and border-radius as desired.
The dynamically added div has no CSS3 styling but does have the border applied with the same CSS selector.
Does CSS3 PIE only run at runtime? Can I trigger it to re-run?
Many Thanks..

A: In the end I solved this by applying the behaviour to a class - "ie-behaviour" and then adding this class to the elements after they are rendered, not sure why but this seems to trigger CSS3 PIE to apply all of the required styles.


text:
Q: Check if point lies within m-dimensional rectangle I'm trying to come up with a generalised algorithm for detecting whether a point lies within or on the boundary of a m-dimensional hyperrectangle defined using intervals.
For a 2D-case it is straight-forward and one can if point lies within a polygon using techniques such as ray-casting. However, how would one check for an m-dimensional hyperrectangle? Is there a way of say equation such a hyperrectangle and checking whether point lies within or on the boundary?
I'm trying to implement this in C++, are there any known libraries that may help?
Thanks! Help much appreciated!

A: What's wrong with straightforward approach?
if ((Point.x[0]>= Rect.min[0]) && (Point.x[0] <= Rect.max[0]) &&
 ...
   (Point.x[m-1]>= Rect.min[m-1]) && (Point.x[m-1] <= Rect.max[m-1]))

in loop by dimensions, of course

A: If you have the hyperrectangle (HR) stored as a combination of intervals (i.e. center coordinate + extent or beginning + end) and rotations, you can transform the query point into the coordinate system of the HR (through appropriate rotation, translation and scaling). Then you only have to do 2*m bound checks.
Your suggested alternative of using a polyhedron is potentially a performance hog because an m-dimensional HR has 2^m corner points.
(This is of course assuming you are not restricting yourself to axis-aligned boxes, in which case the answer is of course trivial)


text:
Q: Rails - How to display SQL values in a OCIError? I'm using Ruby on Rails with Oracle, using the gem ruby-oci8. Sometimes things go wrong and we get a SQL error, be it because of a bad grouping or a PK violation. The thing is, it never shows the actual values that the query was trying to run.
Example error output (getting the sql from e.original_exception.sql, where e is the raised Exception, of course):
"INSERT INTO \"VERSIONS\" (\"CREATED_AT\", \"EVENT\", \"ID\", \"ITEM_ID\", \"ITEM_TYPE\", \"OBJECT\", \"WHODUNNIT\")
VALUES (:a1, :a2, :a3, :a4, :a5, :a6, :a7)"

The question is: How do I make it show the actual values instead of ":a1, :a2, etc..."?
ps: The full exception message for this specific error was:
#<ActiveRecord::RecordNotUnique: OCIError: ORA-00001: unique constraint ({redated_db_name}.VERSIONS_PK) violated: INSERT INTO "VERSIONS" ("CREATED_AT", "EVENT", "ID", "ITEM_ID", "ITEM_TYPE", "OBJECT", "WHODUNNIT") VALUES (:a1, :a2, :a3, :a4, :a5, :a6, :a7)>

EDIT: This might also apply to errors on other databases as well, like MySQL. Can someone please confirm this?


text:
Q: PHP: Can using strlen/mb_strlen incorrectly ever result in security issues? I use UTF-8 across all my websites and so when I count string lengths I use mb_strlen. It occurred to me though someone could easily create a page in another encoding like iso-8859-1 and submit it to my script that is expecting it in UTF-8.
Are there any scenarios where this could cause serious (i.e. security) issues with a website? I'm guessing the worst that can happen is you get some characters that won't display correctly but thought I'd check if anything more sinister can happen.


text:
Q: Automating DOSbox application I have a very old DOS application which I would like to automate. Like there are keypresses and such which if automated will help a lot as I might have to run the program over a hundred times manually.
My question seems to be very similar to this one but the solutions offered there are not very useful for me, plus it is over nine years old
Automating old DOS application using Python
Only big difference between this question and mine is that I have no option other than DOSbox for doing this. This application is set up on a lot of computers, and all the people using the application know how to use DOSBox. Migrating to Virtualbox would be a pain and very time-consuming.
I was thinking maybe if I could mechanize this somehow in python using xautomaton or uinput, but I haven't been able to figure out exactly how. The application will be running on Ubuntu primarily.
To give an idea of the application, I am attaching a screenshot:

The solution does not necessarily need to be in python. Any other language would work. Any help is appreciated.

A: I figured this out. Although this does not use python, to do this, I just captured the windowid of DOSbox and sent all the key presses there using xdotool. Here is an example:
wid=$(xdotool search --class DOSbox)
xdotool key --window $wid m t 5 Return Return i

Which will type "mt5", then press enter twice and then type "i"
The series of keypresses can be stored in a string or a file and called iteratively each time this has to be run. If there is a better method to do this, please feel free to answer.


text:
Q: Java EE 6 Eclipse JAX-RS deployment issue I am following a tutorial that shows how to setup JAX-RS. However, I am getting an error when I reach a certain part in the tutorial.
The tutorial is here: http://www.youtube.com/watch?v=on557289GzA&feature=related
At one stage it says to perform the following:

Click Properties
  -> Click Project Facets
  -> Click JAX-RS(REST Web Service)
  -> Click further configuration
  -> Click OK

I then click apply, in the tutorial this should then generate the relevant files, however in my implementation I get the following error:

cannot Deploy HelloWorld Deployment
  Error for module: HelloWorld:
  Exception while loading the app :
  java.lang.Exception:
  java.lang.IllegalStateException:
  ContainerBase.addChild: start:
  org.apache.catalina.LifecycleException:
  org.apache.catalina.LifecycleException:
  com.sun.jersey.api.container.ContainerException:
  The ResourceConfig instance does not
  contain any root resource
  classes.%%%EOL%%%

I am using a "GlassFish Server Open Source Edition 3 (Java EE 6)" and "Java 1.6.0.22".
Any help in solving this problem would be appreciated.

A: The issue may be with your web.xml file (mine was when I had a similar error), make sure that your servlet is setup looking like this:
<servlet>
    <display-name>JAX-RS REST Servlet</display-name>
    <servlet-name>JAX-RS REST Servlet</servlet-name>
    <servlet-class>
        com.sun.jersey.spi.container.servlet.ServletContainer
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

If this does not help, please comment with further information on what the issue is (are the jar files being imported correctly for JAX-RS, or if it is a configuration issue)

A: I was having the exact same problem and it was solved using this answer from a similar question from this question (The ResourceConfig instance does not contain any root resource classes)


text:
Q: Neccessary Condition involving Sylow-Subgroups for $p$-Solvability Let $G = AB$ and let $P \unlhd A$, where $P \in Syl_p(G)$. If $P$ permutes with all Sylow $q$-subgroups of $B$ with $q \ne p$, then $G$ is $p$-solvable.
Any suggestions on how to proof?


text:
Q: Может ли MySQL вызвать внешнюю программу по триггеру? Имеются ли какие нибудь способы по триггеру в MySQL вызвать например хранимую процедуру (выполнить в ней определенные действия с данными в таблицах) а затем вызвать внешнюю программу (скрипт, например PHP)?
Может какие то модули для MySQL могут такое?


text:
Q: Why is msdeploy failing when creating a wordpress site in azure using the resource group gallery template? Im trying to create a wordpress site in Azure using the gallery template for wordpress.
Im running this command:
New-AzureResourceGroup `
-ResourceGroupName "WPGroup1" `
-Location "North Europe" `
-GalleryTemplateIdentity WordPress.WordPress.0.4.2-preview `
-hostingPlanName "WPPlan1" `
-siteName "WPCustomer1" `
-siteLocation "North Europe" `
-sku Standard `
-databaseName "dbwpcustomer1" `
-databaseLocation "North Europe" `
-databaseSku Free `
-webDeploy_AuthenticationKey 'mSUuC&-27L2Dl|meu{rG@RT>K*}gA!`BF<nv=;BvKAu^;O4tcp0aqUJRzwspo>n'`
-webDeploy_SecureAuthenticationKey '|5!@q{G&L xvlszlC4.9CN6bJ.IA|Qj,S_+>iqKiz|&PlIB61a00-t`,/z*?L=#z'`
-webDeploy_LoggedInKey 'Pv;jk/&-Bp@lsaVw|y5h<b$8i04^)HW2D5}~|G#!#3fZ}V4MS=rE}hJZrk7@keW4'`
-webDeploy_NonceKey '{~0|AVTb6oAv9<~FQcp%vu#2cbc|TWD$`Q%b|Olv4YU$wf##*mXofJ]M^]Y.V{L0'`
-webDeploy_AuthenticationSalt '*_LJ_Z%6-t|W+]Z(k6 Mjg3CvD.S@cRoV3#+6(tK?R#K`7,?bEhh2Q->3,V+[N:!'`
-webDeploy_SecureAuthenticationSalt 'EFC?lh|_thz(`J}ma^.2c6zjrXgV>Dh~0PBw>3:&Kybt_mzZ>{#OD^DHqiCc3&8h'`
-webDeploy_LoggedInSalt 'wc,{@J<q8-YL_1@ MB=:~Nu2^vzeJ]&AB()LC71-av^6M1%^sm;}L-z|yMTVU;fj'`
-webDeploy_NonceSalt '$q;W[]F@Gj08E3{Io5Y0L|n1XmmEBHVt39s**v`-mxqC?.%l+=8]c&|7x}AZdO/2'

The resource group gets created with a site and a database but the deployment of wordpress fails. I get this error message:
New-AzureResourceGroup : 9:12:22 AM - Resource Microsoft.Web/sites/Extensions
'WPCustomer1/MSDeploy' failed with message 'The resource operation completed with terminal
provisioning state 'failed'.'
At line:1 char:1
+ New-AzureResourceGroup `
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-AzureResourceGroup], Exception
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.NewAzureResourceGroupCommand
I have tried to download the .json file and the package, put it in my own storage group and changed the path in the .json file but I get the same error.
Anyone know why this isn't working?

A: I found a solution,
The problem has to do with the keys, when I tried with only numbers & letters it works!


text:
Q: Extract from Ajax response I have an ajax call that returns JSON data (Data Attached).
After converting the data into String, this is how it looks like:
{
   "shipments":[
      {
         "companyName":"TriStar Inc.",
         "shipmentDate":null,
         "transMode":"NDAY",
         "paid":true,
         "delDate":null,
         "custRefInfo":{
            "customerName":"DAISY N.",
            "customerZip":"90544"
         },
         "orderStatus":true
      },
      {
         "companyName":"Carbo Box",
         "shipmentDate":null,
         "transMode":"COUR",
         "paid":true,
         "delDate":null,
         "custRefInfo":{
            "customerName":"TOM K",
            "customerZip":"07410"
         },
         "orderStatus":true
      }
   ]
}

Now when I print the JSON response in Firefox, it looks like:
[Object { companyName="TriStar Inc.", shipmentDate=null, transMode="NDAY", more...}, Object { companyName="Carbo Box", shipmentDate=null, transMode="COUR", more... } ]

My question is, how do I extract companyName and customerName field out of this response. The following isnt working:
 load: function(response){
        for(var i in response){
             console.log(response.shipments[i].companyName);
  }

A: if you get a string that is json, you need to parse it first.
var obj = JSON.parse(jsonString);
now you have a proper object literal, and you can access it normally
var shipments = obj.shipments;
shipments is now a javascript array...
for(var i = 0; i < shipments.length; i++){
    console.log(shipments[i].companyName);
}

note you should not use the for(var i in x) construct on arrays.

A: response.shipments[i].companyName