text:
Q: How to access the BindingContext of custom control in Xamarin.Forms I have a CollectionView with ItemsSource set to ObservableCollection of type Employee.
The ItemTemplate of the CollectionView is a CustomControl that has 1 BindableProperty of Type Employee
MainPage.xaml:
  <CollectionView ItemsSource="{Binding Employees}"
                  SelectedItem="{Binding SelectedEmployee}">
    <CollectionView.ItemTemplate>
      <DataTemplate>
        <controls:CustomControl Employee="{Binding .}" />
      </DataTemplate>
    </CollectionView.ItemTemplate>
  </CollectionView>

The CustomControl has an image (checked image to indicate selection).
CustomControl.xaml:
  <Frame HasShadow="True"
         BackgroundColor="Blue">
    <StackLayout Orientation="Horizontal">
      <Label Text="{Binding Name}" />
      <Image Source="check.png" />
    </StackLayout>
  </Frame>

CustomControl.xaml.cs:
public partial class CustomControl : ContentView
    {
        public CustomControl()
        {
            InitializeComponent();
        }

        public static BindableProperty EmployeeProperty = BindableProperty.Create(
                    propertyName: nameof(Employee),
                    returnType: typeof(Employee),
                    declaringType: typeof(CustomControl),
                    defaultValue: default(Employee),
                    defaultBindingMode: BindingMode.OneWay);

        public Employee Employee
        {
            get
            {
                return (Employee)GetValue(EmployeeProperty);
            }
            set
            {
                SetValue(EmployeeProperty, value);
            }
        }
    }

Model (Employee):
public class Employee: INotifyPropertyChanged
    {
        private int name;
        public int Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
                OnPropertyChanged(nameof(Name));
            }
        }

        private int isSelected;
        public int IsSelected
        {
            get
            {
                return isSelected;
            }
            set
            {
                isSelected = value;
                OnPropertyChanged(nameof(IsSelected));
            }
        }

        #region PropertyChanged
        public void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }

I am trying to create simple animation (FadeIn/FadeOut) for the checked image in the CustomControl so when an item is selected the image will fade in, and when unselected it will fade out. I could use IsVisible and set it to true/false but that's ugly.
My idea was to listen to PropertyChanged event of the Employee (which supposed to be the context of my CustomControl), and when the property IsSelected is modified, I will start the animation to show/hide the image. something like this
public CustomControl()
        {
            InitializeComponent();
            (this.BindingContext as Employee).PropertyChanged += CustomControl_PropertyChanged;
        }

        private void CustomControl_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(Employee.IsSelected))
            {
                //do animation to show/hide image
            }
        }

But couldn't access the Context of my CustomControl!
When I declare the binding in MainPage.xaml I am passing a single Emplyee objet as BindingContext (that dot, right?):
<controls:CustomControl Employee="{Binding .}" />

but after the CustomControl is initializd, the BindingContext is still null!
public CustomControl()
        {
            InitializeComponent();
            var context = this.BindingContext; //this is null
        }

How can I observe the changes on the IsSelected property of the Employee object from my CustomControl?

A: In your custom control override the OnBindingContextChanged method, inside of that method you should be able to access the binding context that is set for your view.
Ex:
    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();
        var context = this.BindingContext as Employee
    }


text:
Q: Only adding some cells in one column it's my first post and just started out with programming, but I am looking forward to the journey!
My Problem:
For a project, I read out an Excel file with Pandas. Now I want to add only some cells together in the same column.
Concrete:
I have the population from Age 0-99 and only want to add People above 65+.
Excel Sheet is like:
Age | Men | Females

Thank you very much for suggestions!

A: Please try the following slicing method:
df[df['Age']>65]

A: if you want to to get the rows in which the value of age variable is > 65. Then use this code
data['Age']=(data['Age'].loc[data['Age']>65])

the values which are below 65 are filled with NaN or remain empty
You can check the min value in this column by writing
data.describe(include='all')

The min value of age will be 65
Now, if you want to remove the rows which have missing values (in which the age is less than 65)
write,
data.dropna(axis=0,how='any')

it will remove all the rows with missing values.
Now you have the data in which the age variable of all the rows is greater than 65.
Thank you!!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Falcon sqlite3 connection I am trying to create my first REST api. I heard that the Falcon is good and easy for beginners. I read the official docs and there is nothing about how to connect to the database.
I have seen the flask docs as well and there is well written everything.
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
    g.sqlite_db = connect_db()
return g.sqlite_db

Is there any way to connect SQlite with falcon?

A: You can use any orm to ease the process of database connection and data handling.
A simple SQLite connection using sqlalchemy is :
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('sqlite:///dbname.db', echo=True)
session = sessionmaker()
session.configure(bind=engine)

This will create a db connection and the same can be used to perform database operations.


text:
Q: mouseover to display appropriated div for link I need to have each div link  make the appropriate div text to appear at the bottom of the page. I have it partially set up but I wanted to know if there was a better way to steam line this code.

GIS / Mapping

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas id justo

The Divs are not nested because I want the text to always appear at the bottom of the page no matter which link you hover over.

A: The $(function(){ ... } doesn't need to be repeated for each function, and you can use functions such as fadeToggle() to reduce the amount of code:
$(function () {
    $("div[id^='item']").hover(function(){
        var selector = '#Tile' + $(this).attr('id').replace('item', '');
        $(selector).fadeToggle('fast');
    });
});

This assumes your IDs are always in the format: item(N) maps to Title(N).
The second line selects all elements where the ID begins with item and the line that follows selects the ID after item and uses it to select the appropriate
.

A: If I understand it correctly. you want to show the
 content next to  div.  you can try.
$(function () {
    $('[id^=item]').hover(function(){
        $(this).parent().next().fadeToggle();
    });
});


text:
Q: WCF Method with parameter not generating right WSDL I have a simple service definition:
[ServiceContract]
public interface IInterface12
{

    [OperationContract]
    void SendInterface12(string appId);
}

which I have implemented in the service as:
public void SendInterface12(string appId)
{

The thing is that the string parameter appId is not showing up. The complete WSDL is here:
      <?xml version="1.0" encoding="UTF-8"?>

-<wsdl:definitions xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://tempuri.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsa10="http://www.w3.org/2005/08/addressing" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://tempuri.org/" name="Interface12Service">

-<wsdl:types>

-<xsd:schema targetNamespace="http://tempuri.org/Imports">

<xsd:import namespace="http://tempuri.org/" schemaLocation="http://localhost/TestInterface12/Interface12Service.svc?xsd=xsd0"/>

<xsd:import namespace="http://schemas.microsoft.com/2003/10/Serialization/" schemaLocation="http://localhost/TestInterface12/Interface12Service.svc?xsd=xsd1"/>

</xsd:schema>

</wsdl:types>

-<wsdl:message name="IInterface12_SendInterface12_InputMessage">

<wsdl:part name="parameters" element="tns:SendInterface12"/>

</wsdl:message>

-<wsdl:message name="IInterface12_SendInterface12_OutputMessage">

<wsdl:part name="parameters" element="tns:SendInterface12Response"/>

</wsdl:message>

-<wsdl:portType name="IInterface12">

-<wsdl:operation name="SendInterface12">

<wsdl:input message="tns:IInterface12_SendInterface12_InputMessage" wsaw:Action="http://tempuri.org/IInterface12/SendInterface12"/>

<wsdl:output message="tns:IInterface12_SendInterface12_OutputMessage" wsaw:Action="http://tempuri.org/IInterface12/SendInterface12Response"/>

</wsdl:operation>

</wsdl:portType>

-<wsdl:binding name="BasicHttpBinding_IInterface12" type="tns:IInterface12">

<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>

-<wsdl:operation name="SendInterface12">

<soap:operation style="document" soapAction="http://tempuri.org/IInterface12/SendInterface12"/>

-<wsdl:input>

<soap:body use="literal"/>

</wsdl:input>

-<wsdl:output>

<soap:body use="literal"/>

</wsdl:output>

</wsdl:operation>

</wsdl:binding>

-<wsdl:service name="Interface12Service">

-<wsdl:port name="BasicHttpBinding_IInterface12" binding="tns:BasicHttpBinding_IInterface12">

<soap:address location="http://localhost/TestInterface12/Interface12Service.svc"/>

</wsdl:port>

</wsdl:service>

</wsdl:definitions>

What am I missing? I have to have a service operation that takes a parameter but when I generate the proxy, there is no parameter for the string appId parameter. It says it takes 0 parameters.

A: Most probably the WSDL references an XSD file where your parameter is defined. Search for "import" or "include" to see the location of that XSD. If this is your wsdl location: http://myserver.com/X.svc?WSDL=WSDL0 then the XSD is in http://myserver.com/x.svc?XSD=XSD0 (or XSD1, XSD2...). Possibly your WSDL references another WSDL (WSDL1) which is the one that references the XSD (or a few of them).


text:
Q: AES enc/dec gives on different platforms different outputs for the first 16 bytes I have a really strange behaviour about encryption and decryption with AES CBC. I use a python script to encrypt a block of data and would like to decrypt it on a microcontroller (TI C2000) and somehow it works, but the first 16 bytes of a 128 byte block are always different on the C2000 and the Python Script and I really don't know how this is possible. Especially it is strange, since the input data in the encryption routine is exactly as expected, since my first tought was, that it must be incorrect input data, but that is not the case.
The block I encrypt/decrypt looks like this:
key[16] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
                   0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}

iv[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                     0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}

data_unencrypted[128] = {0x00,0x00,0x1b,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x76,0x58,0x08,
0x00,0x10,0x00,0xf0,0xff,0x00,0x00,0x46,0x55,0x08,0x00,0x7f,0x58,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x63,
0x08,0x00,0x30,0xa1,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}

data_encrypted_python[128] = {0x2f,0xf2,0x20,0x85,0x2d,0xcd,0xb7,0x5e,0xfe,0x2b,0x90,0xe7,0x66,
0x3e,0xbb,0x3e,0xfa,0x15,0xf1,0xca,0x3e,0xc4,0x92,0x33,0x1a,0xc1,0xea,0x36,0x33,0xc5,0xeb,0xd4,0x33,0x5f,
0xcd,0x06,0x74,0xd4,0x85,0x79,0xed,0xf8,0xdc,0x5e,0x45,0x3d,0x74,0x29,0x63,0x69,0x77,0xc9,0x8b,0xdd,0x09,
0x8b,0xb4,0x2c,0xd7,0xf9,0xe9,0x94,0x1b,0x5d,0x20,0xa4,0x01,0xa7,0x91,0x67,0x24,0xa3,0x78,0xf7,0x72,0x6e,
0xbd,0xd3,0x37,0x27,0x13,0xcd,0x44,0x40,0x35,0x49,0x2d,0xf7,0xdd,0x58,0x35,0xe9,0x1b,0x1d,0x1f,0x97,0xe0,
0xe4,0xc4,0x89,0x0c,0x88,0x46,0x61,0x47,0xbc,0x87,0x3a,0xf5,0x50,0x9b,0xb0,0x4b,0xd9,0x8e,0x05,0x31,0x7c,
0x2a,0xd3,0xb5,0x3b,0xdd,0xa1,0x67,0xc3,0x60,0x39}

--> decrypt in python gives the same as the unencrypted, original data from above.
data_decrypted_c2000[128] = {0x1c,0xc4,0x2b,0xb7,0xd2,0x8d,0x18,0x31,0xe8,0x96,0x30,0x70,0xb5,
                     0x6a,0xad,0xd3,0xf0,0xff,0x00,0x00,0x46,0x55,0x08,0x00,0x7f,0x58,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x63,
                     0x08,0x00,0x30,0xa1,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
                     0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
                     0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
                     0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
                     0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}

--> Note, that only the first 16 bytes are false.
How is this possible? Is it even possible without input data corruption?

A: Yes, it is possible, since CBC uses the previous ciphertext as "vector" for the current block it is trying to decrypt. If a vector is incorrect then the resulting plaintext is also incorrect. However, since the next block only depends on the ciphertext that plaintext error doesn't propagate during decryption.
What is likely happening is that the C2000 uses the wrong - seemingly random - IV value. Like all other vectors this is XOR'ed with the result of the block cipher decrypt resulting in an also randomized plaintext block. If the next plaintext block would have any (small) error then the ciphertext block could have been corrupted, but that's obviously not the case here.

EDIT: After a careful look, I find that the C2000 actually produces the result you would expect given the currently specified IV. That means that the Python IV handling is incorrect, even though it is consistent in both the encryption & decryption functionality.


text:
Q: Passing element to jQuery function I need to change the text of a html span element in a timer.
The timer works well, but I have no sucess changing the span content.
The problem is at:
$(element).text(hour);

What am I missing here?
Here is my code:
HTML:
00:00

Here is my JS:
function loaded(selector, callback){
        $(function () {
            callback($(selector));
        });
        $(document).on('DOMNodeInserted', selector, function () {
            callback($(this));
        });
   };

   function setupTimer(element, duration, interval) {
        var start = Date.now(),
            diff,
            minutes,
            seconds;
        clearInterval(window.mytimer);
        function timer() {
            diff = duration - (((Date.now() - start) / 1000) | 0);
            minutes = (diff / 60) | 0;
            seconds = (diff % 60) | 0;
            if (minutes < 0) {
              minutes = 0;
            }
            if (seconds < 0) {
              seconds = 0;
            }
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;
            hour=minutes + ":" + seconds;
            $(element).text(hour);
            if (window.mytimer != null & diff < 0) {
              clearInterval(window.mytimer);
            }
        };
        timer();
        window.mytimer = setInterval(timer, interval * 1000);
    };

   loaded('#mytimer', function(el){
          setupTimer(el,100,1);
   });

A: First, this is an additional answer to the one of Kaddath, he is correct, as I mentioned in the comments above, remove your loaded method (or at least a part of it).
Why?

*

*DOMNodeInserted is deprecated and has a negative impact on
performance.

*Whenever you change the content (HTML/Text) of this element you trigger a new inserted event, that is the reason why your timer does not work.

If you really need to "wait", as you described in your comment beow, you could use mutationobserver which "replaces" the DOMNodeInserted logic. I put together a small example
$().ready(function() {

  function setupTimer(element, duration, interval) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    clearInterval(window.mytimer);
    function timer() {
        diff = duration - (((Date.now() - start) / 1000) | 0);
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;
        if (minutes < 0) {
          minutes = 0;
        }
        if (seconds < 0) {
          seconds = 0;
        }
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        hour=minutes + ":" + seconds;
        element.text(hour);
        if (window.mytimer != null & diff < 0) {
          clearInterval(window.mytimer);
        }
    };
    timer();
    window.mytimer = setInterval(timer, interval * 1000);
  };

  // simply run your method here (in case DOM element exists)
  // setupTimer($('#mytimer'),100,1);

  // in case your element is not there you can
  // observe the document for changes like this...
  var observer = new MutationObserver(function( mutations ) {
      mutations.forEach(function( mutation ) {
        var newNodes = mutation.addedNodes; // DOM NodeList
        if( newNodes !== null ) { // If there are new nodes added
            var $nodes = $( newNodes ); // jQuery set
            $nodes.each(function() {
                var $node = $( this );
                // looking for your element
                if( $node.attr('id') === 'mytimer') {
                    // do your action
                    setupTimer($('#mytimer'),100,1);
                    // in case you do not need it any longer
                    observer.disconnect();
                }
            });
        }
      });
    });

    // Configuration of the observer:
    // might be possible to reduce this in your case
    var config = {
        attributes: true,
        childList: true,
        characterData: true
    };

    // the target has to be an existing DOM node
    // adapt this to your needs...
    var target = document.body;

    // Pass in the target node, as well as the observer options
    observer.observe(target, config);

});

A: Remove the part with the DOM inserted, it causes the interval to be re-created again and again, because when you do ``text()`, you insert an element.
function loaded(selector, callback){
    $(function () {
        callback($(selector));
    });
    /*$(document).on('DOMNodeInserted', selector, function () {
        callback($(this));
    });*/
};

check this fiddle: https://jsfiddle.net/rzaeg38g/


text:
Q: AccessControlException on template loading in shared tomcat hosting environment My application is deployed in a shared Tomcat hosting environment where my appBase is outside of the container and the security policy is strictly maintained. I am now trying to introduce Freemarker templating, but am getting this:
Could not create a file template loader for current directory
java.security.AccessControlException: access denied (java.io.FilePermission C:\apache-tomcat\bin read)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:374)
        at java.security.AccessController.checkPermission(AccessController.java:546)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
        at java.lang.SecurityManager.checkRead(SecurityManager.java:871)
        at java.io.File.exists(File.java:731)
        at freemarker.cache.FileTemplateLoader$1.run(FileTemplateLoader.java:124)
        at java.security.AccessController.doPrivileged(Native Method)
        at freemarker.cache.FileTemplateLoader.<init>(FileTemplateLoader.java:122)
        at freemarker.cache.FileTemplateLoader.<init>(FileTemplateLoader.java:108)
        at freemarker.cache.FileTemplateLoader.<init>(FileTemplateLoader.java:94)
        at freemarker.cache.TemplateCache.createDefaultTemplateLoader(TemplateCache.java:120)
        at freemarker.cache.TemplateCache.<init>(TemplateCache.java:115)
        at freemarker.template.Configuration.<init>(Configuration.java:110)
        at freemarker.template.Configuration.<clinit>(Configuration.java:96)
        at org.springframework.ui.freemarker.FreeMarkerConfigurationFactory.newConfiguration(FreeMarkerConfigurationFactory.java:333)
        at org.springframework.ui.freemarker.FreeMarkerConfigurationFactory.createConfiguration(FreeMarkerConfigurationFactory.java:266)
        at org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean.afterPropertiesSet(FreeMarkerConfigurationFactoryBean.java:6
0)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$6.run(AbstractAutowireCapableBeanFactory.java:1504)

even though I believe the security policy recommendations for Freemarker have been followed.
Using Spring to inject the Configuration:
<bean id="freemarkerMailConfiguration"
        class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">

    <property name="templateLoaderPath" value="file:/C:/apache-tomcat-files/mailtemplates/"/>
</bean>

or manually creating it
    Configuration freemarkerMailConfiguration = new Configuration();
    File dir = new File("C:/apache-tomcat-files/mailtemplates");
    freemarkerMailConfiguration.setDirectoryForTemplateLoading(dir);

the exception seems to originate with the no-args constructor of Configuration, where presumably it tries to load from the default location before you can get to change it - using setDirectoryForTemplateLoading() is too late.
Can anyone tell me whether I can successfully set the directory when the default is out of bounds?
Many thanks,
Neil

A: That's just a Warning in the log (not an Error), don't worry about it. What goes on is that when you do new Configuration(), it tries to set up the default TemplateLoader that loads from the current directory, that's in you case happens to be C:\apache-tomcat\bin. When it fails, it logs this, then uses null as TemplateLoader. It doesn't mater, since you set the TemplateLoader yourself anyway, so you override its default value.
(BTW, with 2.3.21 if you use new Configuration(new Version(2, 3, 21)) then this warning is avoided, as it doesn't use that silly default for the TemplateLoader anymore.)


text:
Q: Работа с javax.comm в linux Привет. Кто-нибудь знает, как правильно установить javax.comm в ubuntu? Мне эта библиотека нужна для работы с COM-портами. В инете натыкался на старые туториалы. Ещё, я так понимаю, мне нужно установить RXTX. Может кто-нить знает актуальные туториалы по установке этого добра в линуксе? Линканите или расскажите плиз.
Спасибо.
A: Немного уточню предыдущего автора. :)

*

*Перейти по ссылке загрузки Java Communication API Download (видна на странице Java Communications).

*Зарегистрироваться.

*Скачать архив для платформы Linux.

*В архиве ознакомиться с инструкцией docs/html/platform/linux/PlatformSpecific.html и выполнить ее по шагам.

A: https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_SMI-Site/en_US/-/USD/ViewFilteredProducts-SingleVariationTypeFilter
выбираете прлатформу. Качаете. Распаковываете. Папка docs - вся документация


text:
Q: Install VS 2008 Team Developer on Windows 7 Has anyone successfully installed VS 2008 Team Developer edition on the Windows 7 beta yet?  Every time I try, i get an error about insufficient privileges in C:\Windows\Winsxs.
I was able to install the VS 2008 Team Database edition with no problems, and had thought that maybe installing the Dev edition after the DB edition might take care of the winsxs issue, but still no luck.
VS Error Message Image http://img152.imageshack.us/img152/7263/snipimagewd8.jpg
Edit: My install is on the 32 bit version of windows.  Looks like the 64 bit version works - has anyone tried it on 32 bit windows 7?
Edit: I tried turning off UAC, no luck.  Then, tried to install just the "team developer tools" portion (since I already had team DB installed) - and got the same error, only this time it includes an "ignore" button.  Clicked ignore, only to get another error with no ignore, this time for C:\Windows\Winsxs\Policies folder.  Only option at that point is to cancel out of the install.

A: Yes, I've successfully installed it ( Win7 64bit + Dev edition + SP1 + Team Explorer) and not encountered any issues so far.
I might try installing the smallest possible set of features and see if that works.  If it did I would then add features back in 1 by 1.

A: Might try disabling UAC completely if you haven't already.  Just search User Access Control in the control panel or something and it should show up.

A: So, i tried installing this on my other laptop, and it installed fine.
Only (software) difference between the 2 laptops was that one had been running for a few days longer, and had all of the windows update patches installed on it.  So, I checked the first laptop that the install failed on, and there were a bunch of Office 2007 updates to install - so installed those and tried the install again.  After the office patches were all in place, the VS 2008 Team Dev install worked.  This still baffles me as to why it gave me such grief for the first couple days.
I just might have to fire up a VM if i get some free time to test this all again to see if that was really what fixed it - seems strange that office patches should block my VS install.

A: Make sure you're not running setup in compatibility mode for Windows XP SP2. Because then it will complain that it needs at least Windows XP SP2 to be installed which it cannot find.
Also I couldn't install it from an ISO image mounted with MS Virtual CDROM. The error I got was "Couldn't load sitsetup.dll". Burning the image to a DVD and running setup from there fixed this problem.
I'm using Windows 7 Ultimate build 7000, 32bit, English.

A: I dont mean to sound patronizing, but have you ran the installer as an adminstrator?


text:
Q: Absolute positioned HTML5 video element with negative z-index breaks background-attachment in webkit browsers I'm using an HTML5 video element as a background layer which works fine, however, it's causing problems with other elements on the page that have a background image with the property background-attachment: fixed. The background images become unstuck, broken up, or disappear completely. If I change the z-index of the video wrapper div to something positive the problem disappears but that defeats the purpose of using it as a background layer. This problem is only occurring in webkit browsers (Chrome and Safari).
Here's the basic HTML:

...

        <video loop autoplay muted>
            <source src="video.mp4" type="video/mp4">
            <source src="video.webm" type="video/webm">
        </video>

...

...

And the CSS:
.fixed-background {
    background: url('image.jpg') center center;
    background-size: cover;
    background-attachment: fixed;
}
.video-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: -1;
}
.video-background video {
    min-width: 100%;
    min-height: 100%;
}

I've created a sample JSFiddle that illustrates the problem. Works fine in Firefox, but breaks in Chrome/Safari.

A: Just wrap HTML5 video in dom element with styling rules position: relative; and overflow:hidden; This will fix everything in all browsers!

A: Did you find a fix for this?
I have the same issue, however only in safari.
Edit
This post here fixed it for me.
Chrome position:fixed inside position:absolute breaking with iframe / video
Add this to all position: fixed; elements
-webkit-backface-visibility: hidden;
-webkit-transform: translateZ(0);

A: I ran across the same issue. Corey's fix did not resolve the bug for my background-attachment: fixed element.
However, I was able to get it working. Inside the element that declares background-attachment: fixed I add
I'm not entirely sure as to why this works, but I believe it's because the 1x1 pixel forces the browser to repaint the parent element as well.
PS: It doesn't have to be an img element, it can be any element.
Here is the JSFiddle
Edit:
This does NOT work on Chrome 35 Ubuntu


text:
Q: How can I change the publish date based on a custom field? How can I change the publish date based on a custom field?
Author uses a date picker to choose the date for journal entry. The date is used to make a list of all the users journal entries. I can order these posts in a list with a query and orderby. But, then Next and Previous don't match the list.
I have read here, codex, and Google how to attempt to fix this, none have worked so far.
Maybe the best way would be to set the publish date to the same as the custom field from the date picker?
Does anyone know how this can be done?

A: I don't know how your front end form saves its data, but presumably it is using wp_insert_post and wp_update_post. If so, there is a filter called wp_insert_post_data that can be used to alter the post data before the post is inserted or updated.
function reset_post_date_wpse_100021($data,$postarr) {
  var_dump($data,$postarr); die; //debug
  // your code
  return $data;
}
/**
 * runs before new posts have IDs !!!
 */
add_filter('wp_insert_post_data','reset_post_date_wpse_100021',99,2);

The second parameter is your $_POST data plus the old database data with the $_POST data overwriting the old data where they conflict.
If you look at the var_dump of that $postarr value you should see your datepicker data. You need to chop up your datepicker data and overwrite the date values in the $data array.
The issue I see is that WordPress (and MySQL) uses 0000-00-00 00:00:00-- Y-m-d H:i:s-- as the datetime format. That is what you need to provide, but you don't mention a time component at all. At the very least tack 00:00:01 onto your date.
That should be all you need.


text:
Q: Are there architecture smells? There are tons of resources on the web referring to and listing code smells.  However, I've never seen information on architectural smells.  Is this defined somewhere, and is there a list available?  Has any formal research been done into architecture defects, and their impact on project speed, defects, and the like?
Edit: I wasn't really looking for a list in the answers, but documentation (on the web or in a book) about architecture smells.

A: A database designed by an ORM! Or a database backend that is nonrelational that should be relational. Or a database where you design to use views that call views that call views, not only are they too slow (databases must be designed for performance from the start not later) but when you need to make a change, they are horrible to track through (Over abstraction as @AmirResaei said makes it easy to get lost in the code when you need to fix something that is at the bottom of all those layers.)

A: *

*Multitier Architecture
When you have Layers on Layers on Layers on Layers... you see my point here, in your application. I call it Over Layered Architecture

*Over abstraction in such way that you get lost in the code.

*Futuristic Architecture This happens when the solution is too futuristic. In reality no one can predict new requirements. Therefore most of the futuristic implementation is just waste of time and resource.

*Technology Enthusiastic  Architecture
The architect liked the new technology and he put in production. Without knowing if it was proven before.

*Over Kill Architecture A simple problem was solved by exponential factor of architecture skills and technology.

*Cloud Architecture
I call it cloud architecture since architecture has no connection to the really. It's just some nice Visio diagrams.

The total lack of the opposite is also true.
Here is link of Top Ten Software Architecture Mistakes.

A: Code smells and architectural smells are one and the same. Code begins to "smell" because of sub-optimal architecture.
In Martin Fowler's seminal book on the topic, Refactoring, he presents a series of Code Smells and identifies way to refactor them out of your system. Joshua Kerievsky's Refactoring to Patterns further emphasizes this idea by giving specific architectural patterns to fix various code smells (and how to refactor to them step by step).
Most refactoring is done to alleviate suboptimal code via enhanced architecture. One could argue that the only naturally born "Architectural Smell" (other than Big Ball of Mud), would be the BDUF (Big Design Up Front) Architecture. Where you try to accommodate everything you need before the first line of code is written. An agile software project where design is done as needed (even I daresay where code is treated as design), will have its architecture grow organically.

A: Everything is Configurable. When an architect tells you that his system is change-proof or highly-customizable because of extensive configurability, that's an architecture smell.
The problem is that you can really only provide configuration mechanisms for what you think right now is going to need to be configured, but once your application is in the wild, it will not be sufficient. Then, the configuration mechanisms expand and expand, and eventually you get the Inner Platform Effect.
And then you are in software hell.

A: (A lot of) Coupling -in whatever form- is what makes architectures smell. The more it's coupled, the more it smells.
That said : no coupling at all often smells performance issues.

A: Here's one concrete architecture/design smell that I encounter all the time: analysis and reporting directly from a transactional database.
This is certainly OK in some situations (i.e. light reports), but in many cases reporting and transactional processing requirements are in conflict. Yet, because it's the simple/inexpensive thing to do, reports are run directly off of the transactional DB.  This causes all sorts of headaches on both sides of the equation.
This is typically seen in Enterprise LOB apps, btw.  I understand that many SMBs just don't have the resources or know-how to create warehouses and datamarts (forget about cubes, or map-reduce setups), but many larger orgs that I've worked with have the same issues.
When designing a system, the architect really should be aware that reporting - especially analysis reports - and transactional requirements are best treated as separate issues and not just lumped together at the database level.

A: I'm not sure if this rightfully fits at the architecture level, but if I see a bunch of manager classes/modules in what is supposed to be an OO design then that is a guarantee that the only person who will understand the architecture/design is the architect/designer himself without lots of explanation/learning by others.

A: There are many architecture smells documented by the community. A commonly occurring set is the following.

*

*Cyclic Dependency: This smell arises when two or more architecture components depend on each other directly or indirectly.

*Unstable Dependency: This smell arises when a component depends on other components that are less stable than itself.

*God Component: This smell occurs when a component is excessively large either in the terms of LOC or number of classes.

*Feature Concentration: This smell occurs when a component realizes more than one architectural concern/feature.

*Scattered Functionality: This smell arises when multiple components are responsible for realizing the same high-level concern.

*Dense Structure: This smell arises when components have excessive and dense dependencies without any particular structure.

I recently prepared a taxonomy of smells. Currently, it documents 38 architecture smells and more than 260 total code smells.


text:
Q: difference between Service and IntentService To know the difference between IntentService and Service in Android, I created the below posted small test of an IntentService class. The IntentService class can be started using
startService(intent); which will result in a call to nStartCommand(Intent intent, int flags, int startId). Also to send values from the IntentService class to the MainActivity
for an example, we should send it via sendBroadcast(intent); and the MainActivity should register a broadcastReceiver for that action so it can receive the values sent via
sendBroadcast(intent);

so far I cant see any difference between Service and IntentService!! Since they are similar in the way of starting them and the way they broadcast data,can you please tell me in
which context they differ?
please tell me why i am receiving those errors and how to solve it
MainActivity
public class MainActivity extends AppCompatActivity {

    private final String TAG = this.getClass().getSimpleName();

    private Button mbtnSend = null;
    private int i = 0;

    private BroadcastReceiver mBCR_VALUE_SENT = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(MyIntentService.INTENT_ACTION)) {
                int intnetValue = intent.getIntExtra(MyIntentService.INTENT_KEY, -1);
                Log.i(TAG, SubTag.bullet("mBCR_VALUE_SENT", "intnetValue: " + intnetValue));
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        registerReceiver(this.mBCR_VALUE_SENT, new IntentFilter(MyIntentService.INTENT_ACTION));

        this.mbtnSend = (Button) findViewById(R.id.btn_send);
        this.mbtnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), MyIntentService.class);
                intent.putExtra("intent_key", ++i);
                startService(intent);
            }
        });
    }
}

MyIntentService:
public class MyIntentService extends IntentService {

private final String TAG = this.getClass().getSimpleName();
public final static String INTENT_ACTION = "ACTION_VALUE_SENT";
public final static String INTENT_KEY = "INTENT_KEY";

public MyIntentService() {
    super(null);
}

/**
 * Creates an IntentService.  Invoked by your subclass's constructor.
 *
 * @param name Used to name the worker thread, important only for debugging.
 */
public MyIntentService(String name) {
    super(name);
    setIntentRedelivery(true);
}

@Override
public void onCreate() {
    super.onCreate();
    Log.w(TAG, SubTag.msg("onCreate"));
}

@Override
protected void onHandleIntent(Intent intent) {
    Log.w(TAG, SubTag.msg("onHandleIntent"));

    int intent_value = intent.getIntExtra("intent_key", -1);
    Log.i(TAG, SubTag.bullet("", "intent_value: " + intent_value));

    Intent intent2 = new Intent();
    intent2.setAction(MyIntentService.INTENT_ACTION);
    intent2.putExtra(MyIntentService.INTENT_KEY, intent_value);
    sendBroadcast(intent2);

    SystemClock.sleep(3000);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.w(TAG, SubTag.msg("onStartCommand"));

    return super.onStartCommand(intent, flags, startId);
}

A: In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.
From the docs:
Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
IntentService Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
Refer this doc - http://developer.android.com/reference/android/app/IntentService.html

A: Service
This is the base class for all services. When you extend this class, it's important that you create a new thread in which to do all the service's work, because the service uses your application's main thread, by default, which could slow the performance of any activity your application is running.
IntentService
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.
Below are some key differences between Service and IntentService in Android.
1) When to use?
The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.
The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).
2) How to trigger?
The Service is triggered calling to method onStartService().
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.
for more clarity refer this
http://www.onsandroid.com/2011/12/difference-between-android.html


text:
Q: Is there any Newrelic plugin or agent to monitor Unicorn? Can we monitor Unicorn with New Relic? Whether it is down , and if possible any more details available.

A: There is a Unicorn plugin listed in plugin central. It is written by DianthuDia and here is the information for it:
Description
Report Unicorn idle worker ratio & memory usage to NewRelic.
Requirements
Ruby 2.0 or greater.
Installation

*

*Download the latest tagged version from https://github.com/DianthuDia/newrelic_unicorn_plugin/tags

*Extract to the location you want to run the unicorn agent from

*Copy config/template_newrelic_plugin.yml to config/newrelic_plugin.yml

*Edit config/newrelic_plugin.yml and replace "YOUR_LICENSE_KEY_HERE"

*run bundle install

*run bin/newrelic_unicorn_agent


text:
Q: SharePoint if statements for registering css In regular old HTMl we are allowed to do the following to use a css file depending on browser versions:
<link rel="stylesheet" href="path-to-styles/css/cssfilename.css">
<!--[if IE 7]>
<link rel="stylesheet" href="path-to-styles/css/cssfilename.css">
<![endif]-->

in a sharepoint user control we can add the files like so:
 <SharePoint:CssRegistration name="/_layouts/solutionfolder/filename.css" After="corev4.css" runat="server"/>

How can I determine which version of the style sheet to load based on browser version? Or do I register them all then later determine which to use

A: You can use ConditionalExpression property to specify your conditional browser version.
For ex.
<SharePoint:CSSRegistration name="/_layouts/solutionfolder/filename.css" After="corev4.css" ConditionalExpression="lt IE 7" runat="server" />


text:
Q: Is there a way to get the table data is fetched from? Is there a way to get the current table data is fetched from?
Maybe easier to give an example:
Select
       current server       -> Returns "PDBS" or whatever
     , current table(a)     -> Is there something similar that would return "customer"?
     , a.customer_no
     , b.order_no
  from customer a
  left join orders b
    on b.customer_no     = a.customer_no
 where
       customer_no       = 123456
     ;

Edit:
The reason I'm asking is that we have a number of tables (20ish) with descriptions for different things with language support. We have 3 test environments and production and I've written a script that identifies discrepancies in the environments.
I have hardcoded the table names and in doing so was curious if there was a way to extract the table names directly...


text:
Q: How do I copy a string to another string with inline assembly? This simple code should copy the string "c" in the string "d", changing only the first char to 'x':
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char c[5] = "abcd", d[5];

    __asm__(
        "leal %1, %%ebx\n"
        "leal %0, %%ecx\n"

        "movb $'x', (%%ecx)\n"
        "movb 1(%%ebx), %%al\n"
        "movb %%al, 1(%%ecx)\n"
        "movb 2(%%ebx), %%al\n"
        "movb %%al, 2(%%ecx)\n"
        "movb 3(%%ebx), %%al\n"
        "movb %%al, 3(%%ecx)\n"
        "movb $0, 4(%%ecx)\n"

        :"=m"(c)
        :"m"(d)
        :"%ebx", "%ecx", "%eax"
    );

    printf("%s\n", d);
    return 0;
}

But it gives a segmentation fault error. I believe my problem is with the constraints, but I can't figure how to fix this.
What is the right way, and how can I change this code to work?

A: Yes, the input/output operands are wrong. The format is this:
__asm__("<instructions>\n\t"
       : OutputOperands
       : InputOperands
       : Clobbers);

You have the inputs and outputs backwards. You have c as an output, when it should be an input (since you're reading from it). You have d as an input, when it should be an output (since you're writing c to it).
Thus, your inline assembly should be written as follows:
__asm__("leal %1, %%ebx\n\t"
        "leal %0, %%ecx\n\t"

        "movb $'x',     (%%ecx)\n\t"
        "movb 1(%%ebx), %%al\n\t"
        "movb %%al,     1(%%ecx)\n\t"
        "movb 2(%%ebx), %%al\n\t"
        "movb %%al,     2(%%ecx)\n\t"
        "movb 3(%%ebx), %%al\n\t"
        "movb %%al,     3(%%ecx)\n\t"
        "movb $0,       4(%%ecx)"
        : "=m" (d)
        :  "m" (c)
        : "%ebx", "%ecx", "%eax"
       );

But, you are also not making the most efficient use of the operands. You have several manual load operations (lea) that you've written in assembly. You don't need to write these; that's the whole point of the Gnu extended inline assembly syntax—the compiler will generate the necessary load and store instructions for you. Not only does that make the code simpler and easier to write and maintain, but it also makes it more efficient, because the compiler can better schedule/arrange the loads and stores within surrounding code, and skip the lea instructions entirely.
Making these modifications to use operands more efficiently, as well as using names for the operands to make the code easier to read, you would have:
__asm__("movb $'x',    (%[d])\n\t"
        "movb 1(%[c]), %%al\n\t"
        "movb %%al,    1(%[d])\n\t"
        "movb 2(%[c]), %%al\n\t"
        "movb %%al,    2(%[d])\n\t"
        "movb 3(%[c]), %%al\n\t"
        "movb %%al,    3(%[d])\n\t"
        "movb $0,      4(%[d])"
        :     "=m" (d) // dummy arg: tell the compiler we write all of d[]
        : [c] "r"  (c)
        , [d] "r"  (d)
        ,     "m" (c)  // unused dummy arg: tell the compiler we read all of c[]
        : "%eax"
       );

We're asking the compiler for the pointers to be in registers with the r constraint, so we can still choose the addressing mode (reg+displacement) ourselves, as in your original.  This causes the compiler to implicitly generate the two required lea instructions. Not only does this make the code simpler to write, but it also lets the compiler choose which registers it wants to use, which can make the code more efficient. (For example, it needs d in %rdi as an arg for printf.  Compiler-generated setup for asm statements is optimized along with normal code, so it doesn't have to repeat this work like it would if you wrote the lea explicitly in asm.  Leave as much as possible to the compiler, so it can optimize away when possible.)
Note that asking for a pointer with an r constraint doesn't imply that you dereference it.  Thus, we use "m" and "=m" dummy memory operands to tell the compiler what memory is read and written, so it will ensure that the contents match program-order even in a more complex case where your function is inlined into another function that modifies c[] and d[] before and after.  This works well because c[] and d[] are true C arrays, with static size.  It wouldn't work if they were just pointers that you got from function args.  In that case, "=m" (d) would tell the compiler that the asm writes a pointer value into a memory location, not the pointed-to contents.  "=m" (*d) would tell the compiler that the asm writes the first byte.  As the official docs point out, you could write something ugly using a GNU C statement-expression like:
{"m"( ({ const struct { char x[5]; } *p = (const void *)c ; *p; }) )}

Or, you could instead use a "memory" clobber to tell the compiler that all memory must be in sync.  With no output operands at all, the asm block would be implicitly __volatile__, which also prevents reordering.  But if you had one unused dummy output to let the compiler choose a scratch register (see below), and didn't manually use __volatile__, then the compiler would prove to itself that you never use the results and optimize out the entire block of inline assembly!  (It's better to tell the compiler in as much detail as possible how your asm interacts with C variables, rather than relying on __volatile__.)

Letting the compiler choose the addressing mode will work fine for us.  It avoids an extra compiler-generated lea instruction ahead of the asm block, and it simplifies the constraints because we actually use the memory operands instead of separately asking for pointers in registers.
(The compiler could still have avoided an lea in the other version if it put c[] or d[] at esp+0, so the pointer-register operand could be esp).
__asm__("movb $'x',     %[d]\n\t"
        "movb 1 + %[c], %%al\n\t"
        "movb %%al,     1 + %[d]\n\t"
        "movb 2 + %[c], %%al\n\t"
        "movb %%al,     2 + %[d]\n\t"
        "movb 3 + %[c], %%al\n\t"
        "movb %%al,     3 + %[d]\n\t"
        "movb $0,       4 + %[d]"
        : [d] "=&m" (d)  // not sure if early-clobber is needed,
        // e.g. if the compiler would otherwise be allowed to put an output memory operand at the same address as an input operand.
        //  It's an error with gcc 4.7 and earlier, but gcc that old also doesn't accept "m"(c) as an input memory operand
        : [c]  "m" (c)
        : "%eax"
       );

See also Looping over arrays with inline assembly for more discussion of picking addressing mode yourself vs. using "m" constraints to let the compiler pick.  (If you don't want to get into that level of optimization, you probably shouldn't be using inline asm in the first place.)
The compiler will turn 3 + %[c] into something like 3 + 6(%rsp), which the assembler will evaluate the same as 9(%rsp).  Fortunately, it's not a syntax error if the substitution ends up producing 3 + (%rdi).  (You do get a warning, though: Warning: missing operand; zero assumed).
It would also be correct to use an "o" constraint to request an "offsetable" memory operand, but all x86 addressing modes are offsetable (you can add a compile-time-constant displacement and they're still valid), so "m" should always work.  (It would be nice if "o" would add an explicit 0 to avoid the assembler warning, but it doesn't).

But we're not done with possible optimizations yet. We're still forcing the compiler to clobber the eax register when we don't actually need to use that one—any general-purpose register will do. So, we introduce another output, this time a write-only (but early-clobber) temporary stored in a register:
char temp;
__asm__("movb $'x',     %[d]\n\t"
        "movb 1 + %[c], %[temp]\n\t"
        "movb %[temp],  1 + %[d]\n\t"
        "movb 2 + %[c], %[temp]\n\t"
        "movb %[temp],  2 + %[d]\n\t"
        "movb 3 + %[c], %[temp]\n\t"
        "movb %[temp],  3 + %[d]\n\t"
        "movb $0,       4 + %[d]"
        : [d] "=&m" (d)
        , [temp] "=&r" (temp)
        : [c]  "m" (c)
        : // no clobbers
       );

The early-clobber is necessary to stop the compiler from choosing a register that is also used in the addressing-modes for c or d.  The asm syntax is designed to efficiently wrap a single instruction which reads all its inputs before writing any of its outputs.

Okay, we've made the interface between the inline assembly block and the surrounding compiler-generated code pretty much optimal—but let's look at the actual assembly language instructions we're using inside of it. These are far from optimal: we're writing one byte at a time when we could be writing four bytes at a time! (And, on a 64-bit build, we could be writing eight bytes at a time, but that wouldn't help us here.) So, let's just do:
unsigned int temp;
__asm__("movb $'x',     %[d]\n\t"
        "movl 1 + %[c], %[temp]\n\t"
        "movl %[temp],  1 + %[d]"
        : [d]    "=&m"  (d)
        , [temp] "=&r" (temp)
        : [c]    "m"   (c)
        :
       );

This writes the first byte (an 'x' character) into d, and then copies 4 bytes from c into d. That will include the terminating NUL character from c (automatically appended to string literals by a C or C++ compiler), so the string in d is already NUL-terminated without needing to append an additional byte.
Shorter and faster, except for the store-forwarding stall from reading the last 4 bytes of c[] right after the compiler-generated initialization code stored the first 4 bytes and then a separate byte store of the terminating 0.  You wouldn't have this problem if you used static const char c[] = "abcd";, (because then it would be in static storage instead of stored to the stack with mov-immediate every time the function runs), or if c[] was a function arg that probably wasn't just written.  Out-of-order execution can hide the store-forwarding stall latency, so it's probably worth it if c[] is usually not just-written.

Notice that we are not reading from the first character of c—we just offset it as part of the movl instruction.  We could tell the compiler about that to allow it to optimize by moving stores to c[0] across the asm statement.  We could even ask for a [cplus1]  "r"   (&c[1]) input operand, which would be good if we needed the address in a register.  (See the original version of this answer for that.)
Since it's exactly 4 bytes, we can cast to a 4-byte integer type, rather than defining a struct with a char[4] member or something.  Remember that a memory operand refers to a value in memory, so you have to dereference a pointer.  Arrays are a special case: "m" (c) references the 5-byte contents of c[], not the 4 or 8-byte pointer value.  But as soon as we start casting, we just have a pointer.  Even a function argument like int foo(const char c[static 5]) works like a char*, not a char [5].  Anyway, the *(const uint32_t*)&c[1] is 4 bytes in memory from c[1] to c[3].  GCC warns about strict-aliasing with that cast, so maybe a struct { char c[4]; } would be better.  (gcc8-snapshot 20170628 doesn't warn.  Maybe the code is fine, or maybe the warning is broken in that unstable gcc version.)
// tightest constraints possible: 4 byte input memory operand, 5 byte output operand
unsigned int temp;
__asm__("movb $'x',    %[d]\n\t"
        "movl %[cplus1], %[temp]\n\t"
        "movl %[temp], 1 + %[d]"
        : [d]    "=&m" (d)  // references the contents of the whole array, not the pointer-value or just d[0]
        , [temp] "=&r" (temp)
        : [cplus1]    "m"   (*(const uint32_t*)&c[1])
        :
       );

The code is looking pretty good now. Here's the code for the full function, as generated by GCC 6.3 on the Godbolt Compiler Explorer (with -O3 -m32 to generate 32-bit code like in the question):
    subl    $40, %esp
    movl    $1684234849, 18(%esp)       # store 'abcd' into c
    movb    $0, 22(%esp)                # NUL-terminate c
    # begin inline-asm block
    movb $'x',    23(%esp)              # write initial 'x' into d[0]
    movl 19(%esp), %eax                 # get 4 characters starting at c[1]
    movl %eax, 1 + 23(%esp)             # write those 4 characters into d, starting at d[1]
    # end inline-asm block
    leal    23(%esp), %eax              # load address of c[1] into EAX register
    pushl   %eax                        # push address of d[0] onto stack
    call    puts                        # call 'puts' to output string.  printf("%s\n", d) optimizes to this.
    xorl    %eax, %eax
    addl    $44, %esp
    ret

gcc decides to save a register by delaying the lea until after the asm block.  With -m64, it does lea before the asm, but it still uses a stack-pointer address instead of the register it just set up.  That lets the loads/stores run without waiting for the lea to execute, but it also wastes code-size.  Since lea is fast, it's not what I'd do if writing by hand.
The "r" constraint version uses two separate subl instructions to reserve stack space: subl $28, %esp before initializing c[], and subl $12, %esp right before the asm block.  This is just a missed optimization by the compiler, unlike the extra lea which is unavoidable.
Notice that this is much much worse than the asm you'd get from the much more sensible:
d[0] = 'x';
memcpy(&d[1], &c[1], 4);

In that case, c[] optimizes away entirely and you get almost the same code that char d[] = "xbcd"; would produce.  (See test_memcpy() in the Godbolt link above).  The inline-asm version is only useful as an example or template for wrapping other memory-to-memory instruction sequences.

So how do we test that we got all the constraints right, allowing the compiler to optimize as far as correctness allows but no further?  In this case, storing into c[] and d[] before and after the asm statement provides a good check.  Recent gcc versions really will combine those stores into a single store either before or after if the constraints allow it.  (clang won't, though.)
int optimize_test(void) {
    // static // const
    char c[5] = "abcd";
    char d[5];
    c[3] = 'O';  // **not** optimized away: part of the 32-bit input memory operand
    c[0] = '0';  // merged with the c[0]='1' after the asm, because the asm doesn't read this part of c[]
    d[3] = 'E';  // optimized away because the whole d[] is an output-only operand

    unsigned int temp;
    __asm__("movb $'x',    %[d]\n\t"
            "movl %[cplus1], %[temp]\n\t"
            "movl %[temp], 1 + %[d]"
            : [d]    "=&m" (d)  // references the contents of the whole array, not the pointer-value or just d[0]
            , [temp] "=&r" (temp)
            : [cplus1 "m"  (*(const uint32_t*)&c[1])
            :
           );

    c[0] = '1';  // these dead stores into c[] are not optimized away, for some reason.  (Even with memcpy instead of an asm statement.)
    c[3] = 'M';
    d[3] = 'D';

    printf("%s\n", d);
    return 0;
}

There are a couple of additional tweaks that you could do with the inline assembly. For example, our clobbers are telling the compiler that it cannot re-use one of the input registers for the temp register, but it actually could. But these are all pretty subtle. If you actually cared about getting the best possible code from the compiler, you'd write the above code in C like I just showed.
There are many reasons not to use inline assembly, including performance: you'll probably just defeat the compiler's ability to optimize.  If the compiler isn't doing a good job somewhere (for a specific compiler version for a specific target architecture), often you can coax it into making better assembly by just changing the C source, without resorting to inline asm. (Although it's often possible for an expert that really knows what they're doing to beat the compiler, this often requires writing the entire loop in asm and requires a significant investment in time. And if you don't know what you're doing, you can easily make it slower.)
If you're interested in learning assembly language, you should be using an assembler to write the code, not a C compiler. This is all just busy-work! It took me way too long to write this answer, and had to get help from other experts to ensure that I got all of the constraints and clobbers precisely correct so as to cause optimal code to be generated, and I know what I'm doing! This would have been a 2-minute task in assembly:
lea     eax, DWORD PTR [d]
lea     edx, DWORD PTR [c+1]
mov     BYTE PTR [eax], 'x'
mov     edx, DWORD PTR [edx]
mov     DWORD PTR [eax+1], edx

…and you can easily verify that it is correct!

Extra notes from @PeterCordes:  If we can assume that these strings are constants/literals, then this would actually be much better:
mov    DWORD PTR [d],  'xbcd'    ; 0x64636278
mov    BYTE PTR  [d+4], 0

where d can be any addressing mode, for example [esp+6].  If we just want to pass the string to a function, writing in pure asm lets us do things like this that the compiler wouldn't, giving excellent code size and performance:
push   0             ; includes 3 extra bytes of 0 padding, but gcc was leaving more than that already
push   'xbcd'        ; ESP is now pointing to the string data we just pushed
push   esp           ; pushes the old value.  (push stack-pointer costs 1 extra uop on Intel CPUs, and AMD Ryzen, but the LEA or MOV we avoid would also be a uop).
call   puts

Making the compiler store into c[] and then reloading that inside the asm statement is just silly.  You could achieve this by passing in the data as a 4-byte integer with an "ri" constraint.  Or maybe using if (__builtin_constant_p(data)) { } else { } to branch on whether the data was a compile-time constant or not.
If the contents of c[] aren't supposed to be a compile-time constant, and if we can assume an offset load from c[] won't cause a store-forwarding stall, the general idea of Cody's final version is good:
lea     rdi, [d]               ; or "mov edi, OFFSET d" if you don't need a 64-bit RIP-relative LEA for PIC code
mov     edx, DWORD PTR [c+1]   ; load before store to avoid any potential false dependency
mov     BYTE PTR [rdi],   'x'
mov     DWORD PTR [rdi+1], edx

The lea is only worth it if we need d's address in a register afterwards (which we do in this case for printf / puts).  Otherwise it's better to just use [d] and [d+1], even if the addressing mode needs a 32-bit displacement.  (It doesn't in this case, since c and d are both on the stack).

Or, if there's padding after d[], and targeting 64-bit, we could load 8 bytes from c (if you know that the load won't cross into another page—a cache-line split on the load or store might also make this not worth it for perf reasons):
lea     rdi, [d]
mov     rdx, QWORD PTR [c]
mov     QWORD PTR [rdi], rdx
mov     BYTE PTR [rdi],  'x'   ; overlapping store: rewrite the first byte

On some CPUs, e.g. Intel since Ivy Bridge, this will be good even if c[] was just written (avoids the store-forwarding stall):
mov     edx, DWORD PTR [c]
mov     dl, 'x'            ; modify the low byte.  reading edx later will cause a partial-reg stall on older Intel CPUs
mov     byte ptr[d+4],  0
mov     dword ptr[d],   edx

There are other ways to replace the first byte, e.g. AND and OR, which avoid problems on older Intel CPUs.
This has the advantage that reading multiple bytes at once from the start of d[] won't suffer a store-forwarding stall, since the first 4 bytes are written with a store aligned to the start of d[].
Combining both previous ideas:
mov     rdx, QWORD PTR [c]
mov     dl, 'x'
mov     QWORD PTR [d], rdx

As usual, the optimal choice strongly depends on context (surrounding code), and on target CPU microarchitecture (Nehalem vs. Skylake vs. Silvermont vs. Bulldozer vs. Ryzen ...)

A: First of all, your code for string copy did not result in an exception, when I built using gcc and executed on my Windows PC. However, the string copy was not happening because your code appears to assume that register ecx points to variable d, when it actually points to variable c. The following code copies string contents of variable c to d, then replaces the first character in array d, with x. Try Compiling with gcc.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char c[5] = "abcd", d[5];

    __asm__(
        "leal %1, %%ebx\n"
        "leal %0, %%ecx\n"

        "movb (%%ecx), %%al\n"
        "movb %%al, (%%ebx)\n"
        "movb 1(%%ecx), %%al\n"
        "movb %%al, 1(%%ebx)\n"
        "movb 2(%%ecx), %%al\n"
        "movb %%al, 2(%%ebx)\n"
        "movb 3(%%ecx), %%al\n"
        "movb %%al, 3(%%ebx)\n"
        "movb 4(%%ecx), %%al\n"
        "movb %%al, 4(%%ebx)\n"
        "movb $'x', (%%ebx)\n"

        :"=m"(c)
        :"m"(d)
        :"%ebx", "%ecx", "%eax"
    );

    printf("String d is: %s\n", d);
    printf("String c remains: %s\n", c);
    return 0;
}

When using MinGW gcc compiler on Windows PC, the following out put is produced:
> gcc testAsm.c
> .\a.exe
String d is: xbcd
String c remains: abcd


text:
Q: Download-Your-Info Unzip failed I am trying to unzip a Facebook download-your-info zip file, but here's what I got:

Is there a way I can force-unzip it?
I tried sudo unzip file.zip -d destination_folder in terminal (I use Linux), and it unzipped the file, but what came out, all the files have size 0 bytes:

I do have permission to the directory and the file.

(I'm really sorry if my question is asked badly. Let me know down in the comments :) )


text:
Q: Multiple state changes in event listener, how to NOT batch the DOM updates? I'm building a component to test the performance of different algorithms. The algorithms return the ms they took to run and this is want I want to display. The "fastAlgorithm" takes about half a second, and the "slowAlgorithm" takes around 5 seconds.
My problem is that the UI is not re-rendered with the result until both algorithms have finished. I would like to display the result for the fast algorithm as soon as it finishes, and the slow algorithm when that one finishes.
I've read about how React batches updates before re-rendering, but is there someway to change this behavior? Or is there a better way to organize my component/s to achieve what I want?
I'm using react 16.13.1
Here is my component:
import { useState } from 'react'
import { fastAlgorithm, slowAlgorithm } from '../utils/algorithms'

const PerformanceTest = () => {

  const [slowResult, setSlowResult] = useState(false)
  const [fastResult, setFastResult] = useState(false)

  const testPerformance = async () => {
    fastAlgorithm().then(result => {
      setFastResult(result)
    })
    slowAlgorithm().then(result => {
      setSlowResult(result)
    })
  }

  return (

      <button onClick={testPerformance}>Run test!</button>

{fastResult}

{slowResult}

  )
}

export default PerformanceTest

I read somewhere that ReactDOM.flushSync() would trigger the re-rendering on each state change, but it did not make any difference. This is what I tried:
const testPerformance = async () => {
  ReactDOM.flushSync(() =>
    fastAlgorithm().then(result => {
      setFastResult(result)
    })
  )
  ReactDOM.flushSync(() =>
    slowAlgorithm().then(result => {
      setSlowResult(result)
    })
  )
}

And also this:
const testPerformance = async () => {
  fastAlgorithm().then(result => {
    ReactDOM.flushSync(() =>
      setFastResult(result)
    )
  })
  slowAlgorithm().then(result => {
    ReactDOM.flushSync(() =>
      setSlowResult(result)
    )
  })
}

I also tried restructuring the algorithms so they didn't use Promises and tried this, with no luck:
 const testPerformance = () => {
   setFastResult(fastAlgorithm())
   setSlowResult(slowAlgorithm())
 }

Edit
As Sujoy Saha suggested in a comment below, I replaced my algorithms with simple ones using setTimeout(), and everything works as expected. "Fast" is displayed first and then two seconds later "Slow" is displayed.
However, if I do something like the code below it doesn't work. Both "Fast" and "Slow" shows up when the slower function finishes... Does anyone know exactly when/how the batch rendering in React happens, and how to avoid it?
export const slowAlgorithm  = () => {
  return new Promise((resolve, reject) => {
    const array = []
    for(let i = 0; i < 9000; i++) {
      for(let y = 0; y < 9000; y++) {
        array.push(y);
      }
    }
    resolve('slow')
  })
}

A: Your initial PerfomanceTest component is correct. The component will re-render for the each state change. I think issue is in your algorithm. Please let us know how did you returned promise there.
Follow below code snippet for your reference.
export const fastAlgorithm  = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('fast')
    }, 1000)
  })
}

export const slowAlgorithm  = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('slow')
    }, 3000)
  })
}

A: Are you running your algorithms synchronously on the main thread? If so, that's probably what's blocking React from re-rendering. You may need to move them to worker threads.
The below is loosely based on this answer, minus all the compatibility stuff (assuming you don't need IE support):

// `args` must contain all dependencies for the function.
const asyncify = (fn) => {
    return (...args) => {
        const workerStr =
            `const fn = ${fn.toString()}

            self.onmessage = ({ data: args }) => {
                self.postMessage(fn(...args))
            }`

        const blob = new Blob([workerStr], { type: 'application/javascript' })

        const worker = new Worker(URL.createObjectURL(blob))

        let abort = () => {}

        const promise = new Promise((resolve, reject) => {
            worker.onmessage = (result) => {
                resolve(result.data)
                worker.terminate()
            }

            worker.onerror = (err) => {
                reject(err)
                worker.terminate()
            }

            // In case we need it for cleanup later.
            // Provide either a default value to resolve to
            // or an Error object to throw
            abort = (value) => {
                if (value instanceof Error) reject(value)
                else resolve(value)
                worker.terminate()
            }
        })

        worker.postMessage(args)

        return Object.assign(promise, { abort })
    }
}

const multiplySlowly = (x, y) => {
    const start = Date.now()

    const arr = [...new Array(x)].fill([...new Array(y)])

    return {
        x,
        y,
        result: arr.flat().length,
        timeElapsed: Date.now() - start,
    }
}

const multiplySlowlyAsync = asyncify(multiplySlowly)

// rendering not blocked - just pretend this is React
const render = (x) => document.write(`<pre>${JSON.stringify(x, null, 4)}</pre>`)

multiplySlowlyAsync(999, 9999).then(render)

multiplySlowlyAsync(15, 25).then(render)

Note that fn is effectively being evaled in the context of the worker thread here, so you need to make sure the code is trusted. Presumably it is, given that you're already happy to run it on the main thread.
For completeness, here's a TypeScript version:
type AbortFn<T> = (value: T | Error) => void

export type AbortablePromise<T> = Promise<T> & {
    abort: AbortFn<T>
}

// `args` must contain all dependencies for the function.
export const asyncify = <T extends (...args: any[]) => any>(fn: T) => {
    return (...args: Parameters<T>) => {
        const workerStr =
            `const fn = ${fn.toString()}

            self.onmessage = ({ data: args }) => {
                self.postMessage(fn(...args))
            }`

        const blob = new Blob([workerStr], { type: 'application/javascript' })

        const worker = new Worker(URL.createObjectURL(blob))

        let abort = (() => {}) as AbortFn<ReturnType<T>>

        const promise = new Promise<ReturnType<T>>((resolve, reject) => {
            worker.onmessage = (result) => {
                resolve(result.data)
                worker.terminate()
            }

            worker.onerror = (err) => {
                reject(err)
                worker.terminate()
            }

            // In case we need it for cleanup later.
            // Provide either a default value to resolve to
            // or an Error object to throw
            abort = (value: ReturnType<T> | Error) => {
                if (value instanceof Error) reject(value)
                else resolve(value)

                worker.terminate()
            }
        })

        worker.postMessage(args)

        return Object.assign(promise, { abort }) as AbortablePromise<
            ReturnType<T>
        >
    }
}


text:
Q: How to retrieve data from firebase realtime database There seems to be some change with recent update of firebase database.My project worked fine with the version firebase_database: ^7.0.0 but with the newer release of firebase database I can't update my project code.
Here is the working version for v7
class _MainScreenState extends State<MainScreen> {
//
 DatabaseReference driversRef =
      FirebaseDatabase(databaseURL: firebaseUrl).reference().child("Drivers");

//
void searchNearestDriver() {
    print("xxx searchNearestDriver");
    if (availableDrivers.length == 0) {
      cancelRideRequest();
      clear();
      noDriverFound();
      return;
    }
    var driver = availableDrivers[0];
    driversRef
        .child(driver.key!)
        .child('car_details')
        .child("type")
        .once()
        .then((DataSnapshot snap) async { //error from here
      if (await snap.value != null) {
        String carType = snap.value.toString();
        if (carType == carRideType) {
          notifyDriver(driver);
          //print("NotifyDriver is running");
          //TODO This removes the driver from geofire aswell re code

          //availableDrivers.removeAt(0);
        } else {
          Fluttertoast.showToast(msg: carRideType + "Driver not available");
        }
      }
    });
  }

The same code on firebase_database: ^9.0.12 gives an error.
The error I receive is on `(DataSnapShot snap) async ){...}
and the error is

The argument type 'Future Function(DataSnapshot)' can't be assigned to the parameter type 'FutureOr

A: The once method returns a DatabaseEvent, not a DataSnapshot in the newer versions I guess, This is the update.
void searchNearestDriver() async {
    print("xxx searchNearestDriver");
    if (availableDrivers.length == 0) {
      cancelRideRequest();
      clear();
      noDriverFound();
      return;
    }
    var driver = availableDrivers[0];
    //driversRef.child(driver.key!).child('car_details').child("type");
    // .once();

    DatabaseEvent event = await driversRef
        .child(driver.key!)
        .child('car_details')
        .child("type")
        .once();

    //.then((DataSnapshot snap) async {
    if (event.snapshot.value != null) {
      String carType = event.snapshot.value.toString();
      if (carType == carRideType) {
        notifyDriver(driver);

        //availableDrivers.removeAt(0);
      } else {
        Fluttertoast.showToast(msg: carRideType + "Driver not available");
      }
    }
  } //);


text:
Q: Error en consulta Buen dia, estoy haciendo una consulta en PHP para poder sacar los datos dependiendo la fecha de los registros, el detalle es que la consulta no me funciona, no estoy muy seguro de que la sintaxis de la consulta en la parte del WHERE este correcta ya que uso un INNER JOIN para obtener informacion de dos tablas, me podrian indicar si es correcta la consulta y de no ser asi me podrian decir en que parte me estoy equivocando. Anexo codigo:
$consulta = "SELECT empleado.nomina, empleado.nombre, empleado.depto, comentarios.comentario, comentarios.fecha FROM empleado WHERE fecha < '$fecha' INNER JOIN comentarios on empleado.nomina=comentarios.nomina";

A: El INNER JOIN es parte de la clausula FROM, no debe ir en el WHERE. Hay varias maneras de estructurar una query para generar la interseccion de la tabla, en este momento puede que estes confundiendo dos de ellas:
Podemos hacerlo con un INNER JOIN:
SELECT empleado.nomina,
       empleado.nombre,
       empleado.depto,
       comentarios.comentario,
       comentarios.fecha
  FROM empleado    INNER JOIN
       comentarios ON empleado.nomina=comentarios.nomina
 WHERE fecha < '$fecha';

La otra manera es generando un producto cartesiano y filtrando los rows con la clausula WHERE:
SELECT empleado.nomina,
       empleado.nombre,
       empleado.depto,
       comentarios.comentario,
       comentarios.fecha
  FROM empleado   , -- la coma produce un producto cartesiano entre ambas tablas
       comentarios
 WHERE empleado.nomina=comentarios.nomina --los registros se filtran en el where
       fecha < '$fecha';

Ambos estilos son validos, pero recomiendo que si usas uno te quedes con ese para todo el proyecto ser consistente, ademas de formatear mejor tu query, SQL es indiferente a los espacios en blanco pero las personas no y a veces se complica leer querys de una sola linea.

A: Con esta consulta obtienes el resultado que esperas el INNER JOIN va dentro de FROM con el WHERE puedes hacer filtros (condiciones)
SELECT e.nomina,
    e.nombre,
    e.depto,
    c.comentario,
    c.fecha
        FROM empleado AS e
            INNER JOIN comentarios AS c ON e.nomina = c.nomina
        WHERE c.fecha < '$fecha'

Recomendación trata de utilizar alias en las consultas.


text:
Q: If p is a prime, p divides $a^2+b^2$ and p divides $a^2$, then p divides $b^2$ Can you help me prove this number theory claim:
If p is a prime, p divides $a^2+b^2$ and p divides $a^2$, then p divides $b^2$
Thanks

A: Badjohn is right:  If $kp=a^2+b^2$ and $mp=a^2$ for some integers $k$ and $m$, then $(k-m)p=b^2$.

A: $p|a^2+b^2-a^2=b^2$
Especially $p|b$


text:
Q: Can I add range of ports in netsh add urlacl? I use the following command to allow listening of specific HTTP ports:
netsh http add urlacl url=http://+:[port]/ user=DOMAIN\UserName

But if I need to open a range of ports, can I setup a single rule?

A: I didn't find any way to specify a range so I went with using built-in FOR command:
for /L %i in ([port_start],1,[port_end]) do netsh http add urlacl url=http://+:%i/ user=DOMAIN\UserName

You can get more info on the FOR command by using 'FOR /?' in command prompt.
/L happened to be the one that worked for me because it builds a set of numbers given start, stop and step values.


text:
Q: Insert records into MYSQL Database azure logic app I want to copy data from sftp to Mysql,i try to use azure logic app,the problem i Don't know how to insert the file content csv into mysql database ,should i convert the csv file into json?

A: Yes you need to convert CSV file to JSON as because Logic app runs on JSON after that you need to create the MY SQL connection in logic app for that you need to pass the on-prem gateway connection name
Here is the document to pass on-prem gateway and here is the document for inserting data in logic apps


text:
Q: Rails how to return date and time in the RFC 2822 standard I have created a method which return the time , I want to return the time in RFC 2822 format please suggest how can I achieve this ?

A: Simply:
require 'time'

t = Time.now
formatted_time = t.rfc2822  # "Wed, 05 Oct 2011 22:26:12 -0400"

More details.


text:
Q: Move cursor inside textarea to end I have a text area control on a form that is supposed to accept 5 digit US zip codes. I have assigned the control a keyUp event that checks the number of characters entered until it reaches 5 then forces a new line.
public function forceNewLine(event:KeyboardEvent):void
{
    var maxLineChars:int = 5;
    var currentLine:int = 1;
    var numChars:int;

    numChars = (txtList.text.length);
    currentLine = Math.round(txtList.text.length / 6);

    if (numChars == (maxLineChars * currentLine))
    {
        txtList.text = txtList.text + "\n";
        txtList.setCursorPosition()
        //This is not a function I have defined but I think I need too..
    }
}

<s:TextArea id="txtList" keyUp="forceNewLine(event)"/>

It works fine except that when the new line is inserted, the cursor moves to the beginning of the textarea. I want it to go to the end.

A: Try using the selectRange function of the spark textArea.
txtList.selectRange(txtList.text.length, txtList.text.length)


text:
Q: read property file from a dependent project with maven I have an issue when reading properties from a dependent project.
I have a core project, and my application has a dependency on it.
under classpath of core, it has file core.properties.
and my application need to read this property file, but it couldn't.  It requires the core.properties in my classpath of my application, instead of core.
Is there an solution for that? One solution in my mind is that when I build my application.war, can I explictly declare that I want the core dependency be exploded?
Thanks for help!

A: What do you mean by "read this property file"?
Since it will be on the classpath it should be accessible with getClass().getResourceAsStream().
If you really need it as a file, you can use the Dependency plugin's unpack-dependencies goal to unpack particular files as part of the build process.


text:
Q: Auto completando input com endereço Existe alguma API que quando ao digitar o nome de uma cidade por exemplo, aparecera a sugestão como o nome da cidade em baixo do formulário? Por favor, não mandem o Place Autocompleter do Google, preciso de um API que forneça a sugestão da cidade e estado, exemplo:

*

*Santos, SP

A: Já usou jquery?
site: jquery.com
Licença: https://jquery.org/license/
Um exemplo de AutoComplete.
    <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>

Autocomplete

A: Veja Link.
Exemplo:
var cidades = [
           { data: 'es_afonso_claudio', value: 'Afonso Cláudio - ES' },
           { data: 'es_alegre', value: 'Alegre - ES' },
           { data: 'es_alfredo_chaves', value: 'Alfredo Chaves - ES' },
           { data: 'es_alto_rio_novo', value: 'Alto Rio Novo - ES' },
        ]

$('#cidades').autocomplete({
            lookup: cidades,
            onSelect: function(suggestion){
                alert(suggestion.value  + ' : ' + suggestion.data);
            }
        });

No caso aqui #cidades é o ID do input text.

A: Olá, dê uma olhada no Twitter Typeahead.
É um componente de autocompletar que permite a inclusão de dados default que são enviados na página para acesso rápido.
Recomendo conhecer!


text:
Q: if you don't use scaffolding, is ruby on rails still good for rapid development? If you take out the scaffolding feature where it creates the model/controller, and CRUD pages for you, is ruby on rails still any faster to market than say, django?
It seems very similiar to be if you take away that step...(even though I believe django has similar auto-gen capabilities)
I am reading the starting guide on the rails site, and when it introduces the scaffolding feature, it says that many people prefer to hand code these types of areas.

A: I have never seen Rails scaffold-generated view code used in a production app. The chances that it's going to create the look that you want is nearly zero. I use the generators for models and controllers all the time, as they are very useful.
To your question of frameworks:
If you know Python better, use Django.
If you know Ruby better, use Rails.
If this is a hobby site, use whichever one interests you the most.

A: The default scaffolding is generally only useful as a starting point, and doesn't provide too much of a leg up on a real app. If you want something Rails-based that provides better scaffolding, check out Hobo or ActiveScaffold -- both provide scaffold-style functionality, but take it a lot further than Rails does by default.
As far as Rails vs. Django, they provide pretty similar functionality, though Django has built-in account management. Which one you use should be more a matter of language preference than anything else.

A: Scaffolding is just a demo and learning feature. It's not intended for use in real site development. It's certainly not Rails' primary strength.


text:
Q: iOS: how to animate the fill in uibezier path? I am working on a kids letter tracing app - see attached screen shot.
I was able to display the letter by using the bezierpath identified by the font glyphs and allow writing the touches inside the bezierpath.
Now, i want to add an help animation so that it shows how to write this letter from start to finish.
How to do that?
Consider we display "A" and i want to show animation shows how to write "A" for kids.
Any pointers / ideas.
thanks much.

A: I used this animation for my app. Created a circular progress bar that fills up dot clockwise
CABasicAnimation *pathAnim = [CABasicAnimation animationWithKeyPath: @"path"];
pathAnim.toValue = (id)newPath.CGPath;

// -- initialize CAAnimation group with duration of 0.2secs and beginTime will begin after another.
CAAnimationGroup *anims = [CAAnimationGroup animation];
anims.animations = [NSArray arrayWithObjects:pathAnim, nil];
anims.removedOnCompletion = NO;
anims.duration = 0.2f;
anims.beginTime = CACurrentMediaTime() + anims.duration*i;
anims.fillMode  = kCAFillModeForwards;
[anims setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];

[progressLayer addAnimation:anims forKey:nil];

A: I can't find a "built-in" way to animate the fill as you want. There is a built-in way to animate the stroke, however:
Use a UIView with a CAShapeLayer backing it. CAShapeLayer has a path property. You can then apply an animation to the layer's strokeStart and/or strokeEnd properties.
Hope it helps.

A: There is no straightforward way to do this. I imagine the following would be easiest to implement:

*

*Create a path per character that will trace how the stroke will be written. If you have limited number of characters like in the alphabet, it's possible to do this by hand. You can implement something like this to capture the path: http://code.tutsplus.com/tutorials/smooth-freehand-drawing-on-ios--mobile-13164

*Use your current path (in red in your photo) as a clipping mask so the fill does not overflow.

*Stroke the path you created in 1. with a very thick stroke to do the fill.

A: After loading your bezierpath add init the animation:
CAKeyframeAnimation *shapeKeyframeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"strokeEnd"];
shapeKeyframeAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
shapeKeyframeAnimation.keyTimes = @[@0.0f, @0.6f, @1.0f];
shapeKeyframeAnimation.values =  @[@0.0f, @1.0f, @1.0f];
shapeKeyframeAnimation.duration = 4.0f;
shapeKeyframeAnimation.repeatCount = CGFLOAT_MAX;

then add it to your shape layer:
[shapeLayer addAnimation:_loadingKeyframeAnimation forKey:@"stoke"];


text:
Q: Finding the number of items which are associated to a specified set of related items I have a table, Transactions, containing this data:
+------+---------+
|  id  |  item   |
+------+---------+
| 1    |    A    |
| 1    |    B    |
| 2    |    A    |
| 2    |    D    |
| 3    |    C    |
| 3    |    D    |
| 4    |    E    |
| 4    |    C    |
| 5    |    A    |
| 5    |    B    |
| 5    |    C    |
+------+---------+

How would I find the number of transactions that contain a specified set of items?
For example, the number of transactions that contain items A and B is two, because only transactions 1 and 5 contain both of those items.

A: Im not sure what will be your input, but to solve your question this will do
Sql Fiddle Demo
This will count transactions with both items A and B
SELECT count(*)
FROM (
      SELECT id, count(*)
      FROM Table1
      GROUP BY `id`
      HAVING COUNT( CASE WHEN  `item` = 'A' THEN 1 END) > 0
         AND COUNT( CASE WHEN  `item` = 'B' THEN 1 END) > 0
      ) T

OUTPUT
| count(*) |
|----------|
|        2 |

NOTE
The count(*) in the subquery is optional, was just add it for debug to have a visual feedaback of that subquery.

A: Probably something like this, though not tested:
SELECT A.id, count(A.item) AS cntA, count(B.item) AS cntB
FROM table AS A
LEFT JOIN table AS B
   ON (A.item = B.item) AND (A.id <> B.id)
GROUP BY A.id
HAVING cntA = cntB

Self join the table on different IDs having the same items, and compare the count of items. If the count is the same, then the two IDs have the same items.

A: A bit shorter, and probably a bit faster:
SELECT  id
    FROM  Transactions
    WHERE  item IN ('A', 'B')
    GROUP BY  id
    HAVING  COUNT(DISTINCT item) = 2


text:
Q: How can I reinitialize Perl's STDIN/STDOUT/STDERR? I have a Perl script which forks and daemonizes itself. It's run by cron, so in order to not leave a zombie around, I shut down STDIN,STDOUT, and STDERR:
open STDIN, '/dev/null'   or die "Can't read /dev/null: $!";
open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
if (!fork()) {
  do_some_fork_stuff();
  }

The question I have is: I'd like to restore at least STDOUT after this point (it would be nice to restore the other 2).  But what magic symbols do I need to use to re-open STDOUT as what STDOUT used to be?
I know that I could use "/dev/tty" if I was running from a tty (but I'm running from cron and depending on stdout elsewhere).  I've also read tricks where you can put STDOUT aside with open SAVEOUT,">&STDOUT", but just the act of making this copy doesn't solve the original problem of leaving a zombie around.
I'm looking to see if there's some magic like open STDOUT,"|-" (which I know isn't it) to open STDOUT the way it's supposed to be opened.

A: If it's still useful, two things come to mind:

*

*You can close STDOUT/STDERR/STDIN in just the child process (i.e. if (!fork()).  This will allow the parent to still use them, because they'll still be open there.

*I think you can use the simpler close(STDOUT) instead of opening it to /dev/null.
For example:
if (!fork()) {
    close(STDIN) or die "Can't close STDIN: $!\n";
    close(STDOUT) or die "Can't close STDOUT: $!\n";
    close(STDERR) or die "Can't close STDERR: $!\n";
    do_some_fork_stuff();
}

A: Once closed, there's no way to get it back.
Why do you need STDOUT again? To write messages to the console? Use /dev/console for that, or write to syslog with Sys::Syslog.
Honestly though, the other answer is correct. You must save the old stdout (cloned to a new fd) if you want to reopen it later. It does solve the "zombie" problem, since you can then redirect fd 0 (and 1 & 2) to /dev/null.

A: # copy of the file descriptors
open(CPERR, ">&STDERR");

# redirect stderr in to warning file
open(STDERR, ">>xyz.log") || die "Error stderr: $!";

# close the redirected filehandles
close(STDERR) || die "Can't close STDERR: $!";

# restore stdout and stderr
open(STDERR, ">&CPERR") || die "Can't restore stderr: $!";

#I hope this works for you.
#-Hariprasad AJ


text:
Q: Trying to detect a correlation across multiple data sets (same stat, different countries) I have two data points, "A" and "B."
A and B are stats the effect countries, so I have data of A and B for four countries, Canada, the UK, the US and Australia.
Due to changes in reporting, each country only has about 5 years worth of valid data.
I know this is an extremely small sample size to perform an independent test on the data points from a single country, but is there any way for me to test each set of data and draw a valid conclusion of correlation if I get the same results over again for each country?
If so which tests would these be?


text:
Q: Getting and uploading an output file from Python program in Ubuntu I have a Python file uploaded to an Ubuntu server that produces a .txt file. My questions are pretty straightforward but I cannot easily find an answer:

*

*How do I automate the job so that it runs every day at the same time?

*How do I get the outputted txt file and upload it into some shared repository, like GitHub, every day automatically?

Thank you in advance.


text:
Q: Contact recently upgraded to iPhone. How can I tell my iPhone to send them iMessages now? One of my contacts has recently switched to an iPhone. How can I tell my phone to send them iMessages now?

A: It ought to figure it out for itself, once their phone is set up correctly.
So long as their phone number is listed in their phone, in Settings > Messages > Send & Receive  as "You can be reached by iMessages at..." then it should just switch over.
You'll see their messages start to appear in blue rather than green.
You can test/check by finding them in Contacts. As you open their details, you should see FaceTime light up, which confirms they're on an iPhone.


text:
Q: How to synchronize thread pool? my homework is about implementing an application that through threads allows me to search for a file in different folders the threads will create a ring topology, where each thread has interaction with the successor and predecessor thread.. but first I would like to print the id of the current node, the next one, and the previous one on my jframe.
The user specific how many threads he want to use, and that's the number of independent windows will be create.
But my question is, how do I know that? I think if I do that inside the for cycle using 'i' and increment it, like i+1, to print the following isn't the correct way.
this is my constructor where I am giving the index of the for cycle
then I have my Run method to print it to a jframe
public tareaHilo(int id) {
    initComponents();
    this.idHilo = id;
}
public void run() {
            this.setVisible(true);
            numeroHilo.setText(Integer.toString(idHilo));
            nodoPrecedente.setText("previous one");
            nodoSubsecuente.setText("next one");
        }

// This is other class
private void botonCrearActionPerformed(java.awt.event.ActionEvent evt) {
    try {
        tareaHilo tarea;
        numHilos = Integer.parseInt(inputHilos.getText());
        ExecutorService ex = Executors.newFixedThreadPool(numHilos);
        for (i = 1; i <= numHilos; i++) {
            tarea = new tareaHilo(i);
            ex.execute(tarea);
        }
        this.setVisible(false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

A: Swing is single-threaded. Don't do this with an ExecutorService. Use the Swing Timer instead. Something like:
public tareaHilo(int id) {
    initComponents();
    this.idHilo = id;
}
int i;
public void actionPerformed(ActionEvent ae) {
            this.setVisible(true);
            numeroHilo.setText("" + i);
            i++;
            nodoPrecedente.setText("Hilo Anterior #");
            nodoSubsecuente.setText("Hilo Siguiente #");
        }

private void botonCrearActionPerformed(java.awt.event.ActionEvent evt) {
    try {
        tareaHilo tarea;
        numHilos = Integer.parseInt(inputHilos.getText());
        javax.swing.Timer t = new javax.swing.Timer();
        t.scheduleAtFixedRate(...)
        this.setVisible(false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I've let it for you to fill in the scheduledAtFixedRate parameters, as well as work out when/how to stop the timer action


text:
Q: Installing Ubuntu 16.04 alongside Windows 10, legacy BIOS non-UEFI I'm trying to dual boot Ubuntu with Windows 10 (Legacy BIOS), but whenever I try and install, I get this:

Is there a solution from here? Can I just press the option not to force UEFI, and carry on with installation?
I followed this guide exactly, but the "Force UEFI installation?" occurs at the "Preparing to install Ubuntu" stage.

A: I ran into a similar issue when attempting to dual boot Ubuntu 18.04 on a machine running Windows 10 with legacy BIOS. This process might help:
https://askubuntu.com/a/1069984/616171


text:
Q: Cannot boot Ubuntu 22.04 Suddenly Google chrome stopped working and when running again from terminal threw some Process Singleton error. It'd been days since I last restarted my laptop. So I restarted it only to find the following error message.
My laptop is Dell Inspiron 3443 with a SSD and HDD dual booted with windows 10 and Ubuntu both boot files in SSD and some HDD space allocated for both