text:
Q: Writing Logs To Different Folders At Each Day With Log4net I want to log different folder at each day with log4net.
What I found so far is  using data pattern with RollingFileAppender:
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
 <file value="Logs\logfile.log" />
<appendToFile value="true" />
 <rollingStyle value="Composite" />
 <datePattern value=".yyyyMMdd-HHmm" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
 <countDirection value="1"/>
 <layout type="log4net.Layout.PatternLayout">
 <conversionPattern value="%date [%thread] %-5level %logger- %message%newline" />
</layout>

But this just create same new file under Logs folder. What  I want is,
At each different day logger create new folder and write logs under that folder such as:

Logs\Day1\logfile.log, Logs\Day2\logfile.log, Logs\N\logfile.log, ...

Is it possible in Log4net?

A: You can log to directories by add \\:
 <datePattern value=".yyyyMMdd\\\\`logfile.log" />
 <file value="logs\\" />


text:
Q: How can I remove the first byte multiple rows of varbinary data? I reworked a VB script to log parts over a final operation at work, but it added an additional byte at the beginning I would like to remove.

A: SQL substring() (and likely some other string functions) work on binary types too.
Something like this could work:
update yourtable
set data = substring(data, 2, len(data))
where substring(data, 1, 1) = char(0).

I'm not sure about where conditon - you need to try yourself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting JPEG into Mat (8 bits and 3 channels) --- Buffer Overflow Exception I'm trying to use a filter function from OpenCV in Processing, but before I do, I have to convert my image into a mat that is 8 bits and 3 channels. But whenever I run it, I keep running into a "Buffer Overflow Exception," and I can't figure out why I get that error and how to get the conversion to work.
import gab.opencv.*;
import java.nio.*;
import org.opencv.imgproc.Imgproc;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Core;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;

OpenCV opencv;
Imgproc imgproc;

PImage src, out;
PImage before, snap;
Mat one, two;
double a = 35.0;
double b = 20.0;

void setup() {
   src = loadImage("cat.jpg");
   size( 429, 360);

  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  one = new Mat( width, height, CvType.CV_8UC3);
  two = new Mat( width, height, CvType.CV_8UC3);

  one = toMat(src);
  imgproc.pyrMeanShiftFiltering( one, two, a, b);
  out = toPImage(two);
}

void draw() {
  image(out, 0, 0, width, height);
}

Mat toMat(PImage image) {
  int w = image.width;
  int h = image.height;
  Mat mat = new Mat(h, w, CvType.CV_8UC3);
  byte[] data8 = new byte[w*h*3];
  int[] data32 = new int[w*h];
  arrayCopy(image.pixels, data32);
  ByteBuffer bBuf = ByteBuffer.allocate(w*h*3);
  IntBuffer iBuf = bBuf.asIntBuffer();
  iBuf.put(data32); // ERROR -- BufferOverflowException
  bBuf.get(data8);
  mat.put(0, 0, data8);
  return mat;
}

PImage toPImage(Mat mat) {
  int w = mat.width();
  int h = mat.height();
  PImage image = createImage(w, h, RGB);
  byte[] data8 = new byte[w*h*3];
  int[] data32 = new int[w*h];
  mat.get(0, 0, data8);
  ByteBuffer.wrap(data8).asIntBuffer().get(data32);
  arrayCopy(data32, image.pixels);
 }


text:
Q: Editable Jcombobox not populating data from database in my Java swing application, I want Jcombobox populate with some data from database as well as allow user to enter keyword they wish in order to search using combobox value. So i set the editable mode to true.But then i lost data coming from database. Is it possible to enable editable mode true and same time populate Jcomobobox with data from database?
      private void cmbPvtTrnsCompanySeacrhFocusGained(java.awt.event.FocusEvent evt) {
          try {
              ArrayList<String> transList = PvtTransDriverController.getPvtTransporterNames();
              ComboBoxModel comboBoxModel = new DefaultComboBoxModel(transList.toArray());
              cmbPvtTrnsCompanySeacrh.setModel(comboBoxModel);

        } catch (ClassNotFoundException ex) {
              Logger.getLogger(PvtTransDriver.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
              Logger.getLogger(PvtTransDriver.class.getName()).log(Level.SEVERE, null, ex);
        }
  }

Initialization code for cmbPvtTrnsCompanySeacrh
cmbPvtTrnsCompanySeacrh.setEditable(true);
        cmbPvtTrnsCompanySeacrh.addFocusListener(new java.awt.event.FocusAdapter() {
              public void focusGained(java.awt.event.FocusEvent evt) {
                    cmbPvtTrnsCompanySeacrhFocusGained(evt);
              }
        });

        javax.swing.GroupLayout jPanel23Layout = new javax.swing.GroupLayout(jPanel23);
        jPanel23.setLayout(jPanel23Layout);
        jPanel23Layout.setHorizontalGroup(
              jPanel23Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel23Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(cmbPvtTrnsCompanySeacrh, 0, 266, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
        );

A: You can write some code like below:
ArrayList<String> transList = PvtTransDriverController.getPvtTransporterNames();
ComboBoxModel comboBoxModel = new DefaultComboBoxModel(transList.toArray());
cmbPvtTrnsCompanySeacrh.setModel(comboBoxModel );


text:
Q: How to set background opacity of a textview placed on to of ImageView I would like to achieve the following result where there is a transparent background over the name.:

So far this is what i have done (ignore the black border surrounding the image):

i would like to have a transparent background (actually a colored background with its opacity adjusted).
Here is the XML code i have been using:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">

<ImageView
    android:id="@+id/iconItem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_gravity="center"
    android:src="@drawable/shout_ic"/>
<TextView
    android:id="@+id/textItem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_alignBottom="@+id/iconItem"
    android:paddingBottom="5dip"
    android:textSize="10sp"
    android:textColor="#FFF"/>
</RelativeLayout>

Can anyone points me to the right direction on how to achieve such things? Thx

A: You can set background color through xml as shown in other answers.
Also dynamically you can getBackgtound and set alpha.
textItem.getBackground().setAlpha(100); // int value between 0 and 255

A: In your TextView definition, add:
android:background="#8888"

888 being a mid grey (888888), with 8 being a mid alpha (88)
OR
android:background="#8000"

000 being a black (000000), with 8 being a mid alpha (88)

A: Add the background property to your text view like this:
<TextView
android:id="@+id/textItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_alignBottom="@+id/iconItem"
android:paddingBottom="5dip"
android:textSize="10sp"
android:textColor="#FFF"
android:background="#70000000"/>

A: Try adding
android:alpha="0.5"

to the TextView, it should make it semi transparent

A: Add android:background to the textView
<TextView
  android:id="@+id/textItem"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerHorizontal="true"
  android:layout_centerVertical="true"
  android:layout_alignBottom="@+id/iconItem"
  android:background="#80000000"
  android:paddingBottom="5dip"
  android:textSize="10sp"
  android:textColor="#FFF"/>

And you can change the Transparency according to the percentage
Check this understanding the Color codes in android

A: <FrameLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="5dp">

<ImageView
android:id="@+id/iconItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/shout_ic"/>
 <TextView
android:id="@+id/textItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_alignBottom="@+id/iconItem"
android:paddingBottom="5dip"
android:textSize="10sp"
android:textColor="#FFF"/>
</FrameLayout>


text:
Q: An unhandled exception of type 'System.NullReferenceException' VB.net Private client As IFirebaseClient

Public Class PersonalData
    Public Property helloBlock() As String = "off"
End Class

Private Sub helloToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles helloToolStripMenuItem.Click
    Try

        Dim PD As New PersonalData() With
                {
                .helloBlock = "off"
                }

        Dim save = client.Set("func/", PD) 'To save data to Firebase Database.

        MessageBox.Show("hello off", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
    Catch ex As Exception
        If ex.Message = "One or more errors occurred." Then
            MessageBox.Show("Cannot connect to firebase, check your network !", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
    End Try
End Sub

in this line Dim save = client.Set("func/", PD) 'To save data to Firebase Database.
error System.NullReferenceException
Object reference not set to an instance of an object.
can anyone here help me pls fix this.

A: It seems I forgot to initialize it in main_load:
Try
      client = New FireSharp.FirebaseClient(fcon)
  Catch ex As Exception
      MessageBox.Show(ex.Message)
End Try


text:
Q: Posting a message from a Yammer app - notifications? We are posting a message to Yammer from our app about a specific user> Is it possible for the user to receive a notification about this message and if so how do we enforce this?
I've tried including "@username" in the message body but to no avail...

A: When a user is @mentioned ("at mentioned") in a conversation that thread should appear in the user's inbox. It won't appear in the notifications because that is reserved for specific notifications.
When you @mention the user today is the @username part being correctly linked to their profile? If not you might want to check out my other post on this subject. Once the permalink is used you should see it replaced with the user's profile name, and this is what triggers the connection. It should then appear in the inbox of the @mentioned user, even if they don't follow the conversation in their inbox.


text:
Q: ios 6.0 setAttributedText crash - (IBAction)pinFieldChanged:(id)sender {
    UITextField *pinField = sender;
    float kerninig = 76.0;

    NSAttributedString *attributedString =
        [[NSAttributedString alloc]
        initWithString:pinField.text
        attributes:
        @{
            NSFontAttributeName : [UIFont fontWithName:@"Helvetica Neue" size:36],
            NSForegroundColorAttributeName : [UIColor colorWithRed:130.0/255.0 green:130.0/255.0 blue:130.0/255.0 alpha:1.0],
            NSKernAttributeName : @(kerninig)
        }];
    if ([pinField respondsToSelector:@selector(setAttributedText:)]) {
     [pinField setAttributedText:attributedString];
    }

}

My app is crashing under ios6.0 when i'm trying to set attributed text to text field, though this selector is available iOS 6.0 and later
Can you give me any idea why this could happen?
Thanks in advance!)

A: iOS5 may be expects a CTFont so use
 NSString* s = @"Yo ho ho and a bottle of rum!";
    NSMutableAttributedString* mas = [[NSMutableAttributedString alloc]  initWithString:s];
    __block CGFloat f = 18.0;
    CTFontRef basefont = CTFontCreateWithName((CFStringRef)@"Baskerville", f, NULL);

https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/iOS5bookExamples/ch23p689styledText1/p579p593styleText1/RootViewController.m
use below ios 6
 NSAttributedString *stringValue= [[NSAttributedString alloc] initWithString:@"cocoalibrary.blogspot.com" attributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];

A: NSAttributedString is not available below than IOS 6. See this link, you can found this line.

In iOS 6 and later you can use attributed strings to display formatted
  text in text views, text fields, and some other controls


text:
Q: how to create facebook milestone with picture using API? Is there any way to send facebook milestone with picture using API ? I have checked the following documentation and found nothing.
https://developers.facebook.com/docs/reference/api/page/#milestones

A: No, the API suuports only the parameters listed on that document, you can't upload milestones with images attached via the API


text:
Q: Orthogonal Complements property I have a question about how to prove a certain property of orthogonal complements of vector subspaces. Given $\mathrm E$, a vector space over a commutative field k, define: $$\phi\text{ : } \mathrm E \times \mathrm E^* \to k\text{ , where } \mathrm E^* \text{ is the dual space of E, and } \\ \phi(x,\omega) = \omega(x)$$
we can now define $\mathrm F^ \bot  = \{\omega \in \mathrm E^* \mid \phi(x,\omega)=0  , \forall x\in \mathrm F \}$, where $\mathrm F $ is a vector subspace of $\mathrm E $
The first couple of properties such as proving that $\phi$ is in fact a mixed tensor, that $\mathrm F^ \bot $ is also a subspace and $ \dim F + \dim F^\bot = \dim E$ are simple enough, but I've gotten to one that I don't know how to go about, which is: $$ {(F+G)}^\bot = F^\bot\cap G^\bot $$
Where, of course, $F$ and $G$ are vector subspaces.
Also for anyone wondering this is in the context of duality in projective spaces, because proving these properties is fundamental to the principle of duality, or at least the way I'm learning it. Thanks in advance.

A: Try this: $\omega \in F^\bot \cap G^\bot $ implies $\omega \in F^\bot $ and $\omega \in G^\bot$. That is, $\omega (x) = 0$ for every $x \in F$ and $\omega (y) = 0$ for every $y\in G$. Hence, $\omega (x+y) = 0$ for all $x+y \in F + G$. So $\omega \in (F+G)^\bot$.
So far we have proved one inclusion: $F^\bot \cap G^\bot \subset (F+G)^\bot$. For the other inclusion, namely $(F+G)^\bot \subset F^\bot \cap G^\bot$, just do the same: start with the definition of $\omega$ being in $(F+G)^\bot$ and see what happens. (If you get stuck, ask me again.)


text:
Q: Why are certain naming conventions so inconsistent in Linux? It seems like the general pool of logging, changelog, readme, and config files in Linux is very inconsistently named. It always makes me wonder, why didn't *nix devs decide on a common file name schema long ago? I feel that it's unnecessarily annoying having to remember exactly how a file is named in regards to, let's say, configs.
For example, here is the configuration naming convention: We find this, this.cnf, this.conf, this.config, or neither, dropping into the underscore this_config realms, or even occasionally the Windowsy this.cfg style. Considering the diversity above, what is the most accepted approach for naming configs? The same can be said/asked for logs, changelogs, readmes, etc.
Most of the scripts and binaries seem well laid out with consistent schema, so what made configs take the hard road? Did something happen back in the day that divided the dev crowd into naming convention camps, or was "tertiary" consistency like this just never worth pursuing due to the open nature and free spirit approach of Linux?

A:
Considering the diversity above, what is the most accepted approach for naming configs?

Whatever you want to call them. File extensions don't matter much beyond letting an admin know what the file probably is. A human is probably going to know that *.cfg and *.conf are both probably config files.
The *.cnf I've only ever seen with MySQL which is a one-off deviation that you'd have to ask the MySQL/MariaDB developers about.

Did something happen back in the day that divided the dev crowd into naming convention camps, or was "tertiary" consistency like this just never worth pursuing due to the open nature and free spirit approach of Linux?

It's probably not something most people would consider important. Most people go with *.conf nowadays (nginx, udev, apache, rsyslog/syslog-ng, etc), but it's possible *.cfg was preferred back when file paths could only have a few characters. It probably never changed for the same reason /etc/fstab was never renamed, most people who cared already know what the file in question does.

A:
Did something happen back in the day that divided the dev crowd into ... camps ...?

You may be looking at the chronology backwards.
"Back in the day" the "Unix dev crowd" was all at AT&T Bell Laboratories.
(If you provide enough power to the flux capacitor,
you may be able to go back to a time when the "Unix dev crowd"
was two people, and they may have shared an office, for all I know.)
But then the University of California (Berkeley)
(and other less well known universities) started modifying it,
and companies like IBM, Sun, and Oracle got into the act
(producing products like Xenix, AIX, and Solaris),
and that's not even counting all the companies (e.g., Sybase)
that just wrote application software for Unix.
(See What exactly is POSIX?
for more background/history on Unix/POSIX.)
These developers (1) didn't know what each other were doing,
because they were working for competing organizations,
(2) thought their way was better,
and didn't care about giving the user a uniform experience,
and/or (3) deliberately chose to be arbitrarily incompatible,
for purposes of fragmenting the market.
(It's been suggested that IBM strategically made the Unix market a jungle
in order to drive customers away from Unix
and back to their proprietary operating systems.)
This is just a fraction of the legacy of Linux.
So why hasn't this been "fixed"?
Well, as you said yourself, "If it ain't broke, don't fix it."
And backward compatibility within products (e.g., mySQL)
may be considered more valuable
than horizontal compatibility between products.


text:
Q: Importing Compiled Objective-C Framework Swift Package Manager I am trying to create Swift Package. This package uses a third-party compiled Objective-C framework to be integrated. Usually, when we integrate such a framework, we add it in Linked Frameworks and import it via bridging header.
But since it is a swift package, I cannot have a bridging header. I also tried to use the umbrella header but it is not working.
Below is my package.swift -
targets: [
    .target(
        name: "MySPM",
        dependencies: ["ObjCFramework"]),
    .binaryTarget(name: "ObjCFramework",
                  path: "Frameworks/ObjCFramework.xcframework")
]

And I tried to create an umbrella header as below -
module ObjCFrameworkModule {
    header "Frameworks/ObjCFramework.xcframework/Headers/"
    export *
}

I would really appreciate it if I can get some pointers for using the Objective-C framework inside SPM.

A: You can wrap the Objective C framework in its own Swift Package. Here's an example.
Or access the xcframework remotely like in https://stackoverflow.com/a/68665383/556617.


text:
Q: How to create and print multi level dictionary in python? Data structure required:
Name -->gene1
             --> CDS
                     1   3
                     6   10
             --> exon
                     4   8
       ->gene2
             --> CDS
                     4   9

I am trying to create and print the above data structure using python Dictionaries. I am very new to Python that's why I not able create it. Need help to create it.
Try:
dict = {'name' :{'gene1': {'CDS' : [1, 3]}}}
for name in dict:
        print name
        for gene in dict[name]:
                print "\t" +gene
                for feature in dict[name][gene]:
                        print "\t\t"+feature
                        print "\t\t\t",
                        print dict[name][gene][feature]

output:
name
        gene1
                CDS
                        [1, 3]

A: dct = {"gene1": {"CDS": [[1, 3], [6, 10]], "exon": [[4, 8]]}, "gene2": {"CDS": [[4, 9]]}}

for outer_key, outer_value in dct.items():
    print(outer_key)
    for inner_key, inner_value in outer_value.items():
        print("\t", inner_key)
        for elem in inner_value:
            print("\t\t", elem)

Your question is very unclear, but here is a possible solution.
items() in python2 is iteritems()
This will output:
gene2
         CDS
                 [4, 9]
gene1
         CDS
                 [1, 3]
                 [6, 10]
         exon
                 [4, 8]

The gene1 gene2 is the key in the outer dict, CDS and exon are inner dicts (values of the outer dict) and their values are lists (nested lists)


text:
Q: Android 4.1 - RTSP using VideoView and MediaController Developing a simple app to play a RTSP stream on Android 4.1, but unable to do so
Update
I am able Able to play if I use BigBuckBunny_115k.mov
Uri video = Uri.parse("rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov");

BUT
I tried with lot of RTSP streams mentioned here and here, but none worked :(
****Problem: I could not see any stream on my phone, only black screen is visible.. After some time, a dialog box appears "Can't play this video". I tried with many RTSP streams, but same result, so is it issue with all the streams mentioned? Or .sdp is not parsed properly? Is something missing in the code snippet? ****
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        VideoView videoView = (VideoView) findViewById(R.id.video);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        mediaController.setMediaPlayer(videoView);

        Uri video = Uri.parse("rtsp://ss1c6.idc.mundu.tv:554/prf0/cid_29.sdp");
        videoView.setMediaController(mediaController);
        videoView.setVideoURI(video);
        videoView.start();
    }

<VideoView
    android:id="@+id/video"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true" />

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.rdx.livetv.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

10-08 17:53:03.674: D/libEGL(22488): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
10-08 17:53:03.682: D/libEGL(22488): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
10-08 17:53:03.682: D/libEGL(22488): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
10-08 17:53:03.775: D/OpenGLRenderer(22488): Enabling debug mode 0
10-08 17:53:03.783: D/MediaPlayer(22488): Couldn't open file on client side, trying server side
10-08 17:53:03.900: D/MediaPlayer(22488): getMetadata
10-08 17:53:06.596: D/dalvikvm(22488): GC_CONCURRENT freed 102K, 2% free 11074K/11207K, paused 14ms+3ms, total 42ms
10-08 17:55:05.799: E/MediaPlayer(22488): error (1, -2147483648)
10-08 17:55:05.799: E/MediaPlayer(22488): Error (1,-2147483648)
10-08 17:55:05.799: D/VideoView(22488): Error: 1,-2147483648

A: another good solution for playing RTSP, using the native player.
mediaURL = "rtsp://192.168.0.119/Bolt.ts"
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mediaURL));
startActivity(intent);

A: I analyzed the streams given in these links using openRTSP.
"openRTSP" is a command-line program that can be used to open, stream, receive, and (optionally) record media streams that are specified by a RTSP URL - i.e., an URL that begins with rtsp://
Using this utility, I found that most of the SDP files mentioned had issues, and this is the reason for the issues coming in the application.


text:
Q: How to add 'Company Name' in customer register and billing info I've been trying to add 'company name' on customer register and onepage checkout but unsuccessfully so far. I tried https://magento.stackexchange.com/questions/15847/add-company-name-to-billing-shipping-dropdown-in-magento  but it didn't help at all.
I can't believe there isn't a simple way of doing that.

A: The company field is already part of the address entity in Magento, if it isn't showing on register and checkout forms you'll need to update the templates to include it.
I recommend that you look in either the base/default or rwd/default theme and look at:

*

*checkout/onepage/shipping.phtml

*persistent/customer/form/register.phtml

*persistent/checkout/onepage/billing.phtml

You should see company in there and can copy that into your active theme.
Hope that helps!

A: Adding a new field to Magento new customer registration can be done in 4 simple steps. Follow the steps given below to get done with it.
Step 1: We have to add php and .html form elements that are necessary to create new input boxes for each additional field in register.phtml.

<?php echo $this->__('Company Name') ?>

<input type="text" name="company_name" id="company_name" value="<?php echo $this->htmlEscape($this->getFormData()->getCompany()) ?>" title="<?php echo $this->__('Company Name') ?>" class="input-text" />

Step 2: We need to add elements under "getDefaultEntities()" in Setup.php (path: /app/code/core/Mage/Customer/Model/Entity/), one for each additional field created above:
company_name' => array(
'label' => 'Company Name',
'required' => false,
'sort_order' => 64,
),

Step 3: Add to the content of $customer in AccountController.php (path: /app/code/core/Mage/Customer/controllers/) by grabbing the new fields from posted info, in the createPostAction() function:
$customer = Mage::getModel('customer/customer')->
setCompany($this->getRequest()->getPost('company_name'));

Step 4: Finally, we will need to add database records to table eav_attribute, corresponding to the newly created fields. The idea is to add to the associated data model, where newly defined model data is entered as the "attribute_code", with the corresponding entity_type_id (which for this data happens to be '1').
Using your favourite SQL editor (i.e. phpMySQL or sqlYog — highly recommended), execute the following SQL statement for each field created above (replacing 'company' and 'Company Name' with the respective field name information as required):
INSERT INTO eav_attribute (entity_type_id, attribute_code, backend_type, frontend_input, frontend_label, is_global,is_visible, is_required, is_configurable, is_filterable_in_search) VALUES('1′, 'company', 'varchar',  'text', 'Company Name', '1′, '1′, '0′,  '1′,  '1′);


text:
Q: Number of point of intersection of $y=(x+2)$ and $y=(x+2)^2$
The solution curve of the differential equation $\displaystyle (x^2+xy+4x+2y+4)\frac{dy}{dx}-y^2=0,x>0$
Passes through the point $(1,3).$ Then
$(1)$ number of point of intersection of  $y=x+2$
$(2)$ number of point of intersection of $y=(x+2)^2$

Try: $$\bigg[(x+2)^2+y(x+2)\bigg]\frac{dy}{dx}=y^2$$
$$y^2\frac{dx}{dy}=(x+2)^2+y(x+2)$$
Could some help me to solve it , thanks

A: $$y^2 \frac{dx}{dy} = (x+2)^2 + y(x+2)\\
\frac{1}{(x+2)^2}\frac{dx}{dy}-\frac{1}{y(x+2)} = \frac{1}{y^2}$$
Observe it is a linear differential equation by treating $\frac{-1}{x+2}$ as some variable $t$. Integration factor will be $\frac{1}{y}$ and solution is
$$\frac{-1}{(x+2)y} = \int \frac{dy}{y^3} = \frac{-1}{2y^2}-c\\
2y=(x+2)(cy^2+1)$$
I think you can proceed.


text:
Q: prove $\sum \limits_{cyc} \frac{x}{x+\sqrt{(x+y)(x+z)}}\leq 1$
If $x$,$y$,$z$ are positive real numbers,Prove:$$\sum \limits_{cyc} \frac{x}{x+\sqrt{(x+y)(x+z)}}\leq 1$$
  Using this two inequality:
$\sum ^n_{i=1} \sqrt{a_ib_i}\leq\sqrt {ab} $ (we call it $A$ inequality)
$\frac {ab}{a+b} \geq \sum ^n_{i=1} \frac{a_ib_i}{a_i+b_i}$ (we call it $B$ inequality)
which $a_i$ and $b_i$ are positive and and $b= \sum ^n_{i=1} b_i$,$a= \sum ^n_{i=1} a_i$.
Additional info: The question emphasizes in using inequalities $A$ and $B$.Beside them we can use AM-GM and Cauchy inequalities only.We are not allowed to use induction.And if you like,here you can see Prove of inequality B.

Things I have tried so far:
Using inequality $A$ i can re write question inequality as$$\sum \limits_{cyc} \frac{x}{2x+\sqrt{xy}}\leq 1$$
And I can't go further.I can't observer something that could lead me to using inequality $B$.

A: Use the fact
$\sqrt{(x+y)(x+z)}\ge \sqrt{xy}+\sqrt{xz}$. Which is obvious after squaring and cancelling terms.
Now our inequality becomes :
$$\sum \limits_{cyc} \frac{x}{x+\sqrt{(x+y)(x+z)}}\le \sum \limits_{cyc} \frac{x}{x+\sqrt{xy}+\sqrt{xz}}=\sum \limits_{cyc} \dfrac{\sqrt{x}}{\sqrt{x}+\sqrt{y}+\sqrt{z}}=1$$

A: By your work and by C-S we obtain:
$$\sum_{cyc}\frac{x}{x+\sqrt{(x+y)(x+z)}}\leq\sum_{cyc}\frac{x}{2x+\sqrt{yz}}=\frac{3}{2}-\sum_{cyc}\left(\frac{1}{2}-\frac{x}{2x+\sqrt{yz}}\right)=$$
$$=\frac{3}{2}-\frac{1}{2}\sum_{cyc}\frac{\sqrt{yz}}{2x+\sqrt{yz}}=\frac{3}{2}-\frac{1}{2}\sum_{cyc}\frac{yz}{2x\sqrt{yz}+yz}\leq$$
$$\leq\frac{3}{2}-\frac{1}{2}\cdot\frac{\left(\sum\limits_{cyc}\sqrt{yz}\right)^2}{\sum\limits_{cyc}(2x\sqrt{yz}+yz)}=\frac{3}{2}-\frac{1}{2}=1.$$


text:
Q: Wrong function of the code in C. the program seems to display garbage I wrote a program to run the insertion sorting algorithms. Everything seems good.  But when I execute it there is a strange result.  It seems that the programs uses garbage in memory.  How could I fix it?
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

void insertion_inc(int Array[], int size)
{

    int i, j, key;
    for (i = 1; i < size; i++)
    {
        j = i - 1;
        key = Array[i];
        while (j >=0 && Array[j]>key )
        {
            Array[j + 1] = Array[j];
            j--;
        }
        Array[j++] = key;
    }
}

void insertion_dec(int Array[], int size)
{

    int i, j, key;
    for (i = 1; i < size; i++)
    {
        j = i - 1;
        key = Array[i];
        while (j >= 0 && Array[j] < key)
        {
            Array[j + 1] = Array[j];
            j--;
        }
        Array[j++] = key;
    }
}

void print_array(int arr[], int size)
{

    for (int i = 0; i < size; i++)
        printf(" %d ", arr[i]);
}

/////////////////////////////////////////////

int main()
{

    time_t t;
    srand((unsigned)time(&t));
    int Arr[10];
    int size = sizeof(Arr);
    printf("The unsorted Array : \n ");
    for (int i = 0; i < size;i++)
        Arr[i] = rand()/10;
    print_array(Arr, size);
    printf("\n\n\n The sorted Array : \n");
    insertion_inc(Arr, size);
    print_array(Arr, size);
    return 0;
}

**The output always looks like this : **
The unsorted Array :
12  23  54  87  2  68  29  57  97  12  -858993460  272204808  7601072  7742451  1  15039136  15044096  1  15039136  15044096  7601164  7742023  272204692  7738189  7738189  8462336  0  0  0  0  0  0  0  0  7775604  7775616  0  7601080  0  7601272
The sorted Array :
23  23  23  23  23  23  23  23  23  23  23  23  23  23  23  57  68  7601272  7738189  7738189  7738189  7742023  7775616  8462336  8462336  8462336  15039136  15039136  15039136  15039136  15044096  272204692  272204808  272204808  272204808  272204808  272204808  272204808  272204808  272204808
Even when I ignore the use of srand() and rand(), there is still the problem.

A: This line:
int size = sizeof(Arr);

does not do what you think it does. It is returning the size in bytes, rather than elements.
See How do I determine the size of my array in C?

A: You're not calculating the array size correctly:
int size = sizeof(Arr);

The sizeof operator gives the size of its operand in bytes.  So assuming an int is 4 bytes on your system, sizeof(Arr) evaluates to 40.
You instead want to divide the size of the array by the size of an element of the array to get the number of elements.
int size = sizeof(Arr) / sizeof(*Arr);


text:
Q: object passing as undefined in child component React I am trying to pass an object as a prop, but I am receiving it as undefined in the child component. If I try the same thing in codesandox works perfect. Any thoughts?
This an example:
Parent Component
import TestPage from "pages/Test";

  const text = {
  crono: "crono",
  watch: "clock",
  start: "start",
  stop: "stop",
  split: "split",
  pause: "pause",
  clear: "clear",
};

export default function Base() {

  return (

      <TestPage text={text} />

  );
}

Child Component
export default function Test({ text }) {
  console.log(text);
  return
{text.split}
;
}

here is the complete project


text:
Q: Angularjs binding issues when input has a directive with scope I've created a custom directive in AngularJS. The directive uses isolated scope, and it somehow prevents the binding for standard ngModel on the same element.
I want to create a confirm password field (text for readability in the example).
<input type="text" name="one" ng-model="fields.field_one">
<input type="text" validate-match="fields.field_one" name="two" ng-model="field_two">

My directive invalidates the field, when there is no match.
app.directive('validateMatch', function() {
  return {
    require: 'ngModel',
    scope: { matchValue: '=validateMatch' },
    link: function(scope, elm, attr, ctrl) {
      scope.$watch('matchValue', function(value) {
        ctrl.$setValidity('match',
            ctrl.$viewValue === value
            || !ctrl.$viewValue && !value);
        });

      function validate(value) {
        ctrl.$setValidity('match', value === scope.matchValue);
        return value;
      }
      ctrl.$parsers.push(validate);
      ctrl.$formatters.push(validate);
    }
  }
});

The thing is, why can't I change the value of that field by changing the model? First field works just fine.
Look at the plunker for details and commented code.

A: As mentioned in a comment, isolate scopes and ng-model don't mix well.  Further, we shouldn't be using an isolate scope here, since we're trying to create a directive/component that needs to interact with another directive (ng-model in this case).
Since the validateMatch directive does not create any new properties, the directive does not need to create any new scope.  $parse can be used to get the value of the property that attribute validate-match refers to:
app.directive('validateMatch', function($parse) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elm, attr, ctrl) {
      var model = $parse(attr.validateMatch);

      // watch for linked field change (field_one)
      scope.$watch(model, function(value) {
        console.log('linked change:', value, ctrl.$viewValue);
        // set valid if equal or both falsy (empty/undefined/null)
        ctrl.$setValidity('match',
            ctrl.$viewValue === value
            || !ctrl.$viewValue && !value);
      });

      // validate on parse/format (field_two)
      function validate(value) {
        var otherFieldValue = model(scope);
        console.log('validate:', value, otherFieldValue);
        // set valid if equal
        ctrl.$setValidity('match', value === otherFieldValue);
        return value;
      }

      ctrl.$parsers.push(validate);
      ctrl.$formatters.push(validate);
    }
  };
});

plunker

A: Following Mark's suggestion, I managed to produce a work-around.
When isolated scope exists on the element, ngModel refers to it. The trick is to look the parent scope from within. You can either change the ngModel by hand (prepending it with $parent.), or automatize this process inside the directive by proper compile function.
This is how i did this:
compile: function(element, attrs, transclude) {
    // reference parent scope, because isolated
    // scopes are not looking up by default
    attrs.$set('ngModel', '$parent.'+attrs.ngModel, false);

    return function(scope, elm, attr, ctrl) {
        // link function body there
    }
}

For the full example, look at this plunk.

A: From what I understand of AngularJS Directives you can use the transclude parameter to access the parent scope of the controller.


text:
Q: DotNetZip - create zip from accessed file it is possible to use DotNetZip to create a zip from an accessed file (eg log file from another application) ?
so create a zip when the log file gets written through the other application

A: Hmm, well, yes, if you are willing to write some code.
One way to do it is to compress the file AFTER it has been written and closed.
You would need to have an app that runs with a filesystem watcher, and when it sees the log file being closed, it compresses that log file into a zip.
If you mean to imply, a distinct app that writes to a file and it automagically writes into a zip file, no I don't know of a simple way to do that.  There is one possibility: if the 3rd party app accepts a System.IO.Stream in which to write the log entries. In that case, you can do that with DotNetZip. You can get a writeable stream from DotNetZip, into which the app writes content. It is compressed as it is written, and when the writing is complete, DotNetZip closes the zipfile.  To use this, check the ZipFile.AddEntry() method that accepts a WriteDelegate.  It's in the documentation.


text:
Q: Python 3.5 decimal placement I am making a POS system however no matter what I do, I can't get the money to show as 2 decimal places.
I will be very grateful if you could reply as I have been on this for hours. I am open to all responses. My code is below
import sqlite3
import time
from decimal import Decimal

conn = sqlite3.connect('jamesPOS.db')
c = conn.cursor()
total = float(0.00)

def creatTable():
       c.execute('CREATE TABLE IF NOT EXISTS price(product TEXT, cost TEXT, product_id TEXT)')

def dataEntry():

       print('Please type a product name')
       product = input()

       print('Please type a price')
       cost = input()

       print('please type the id for your product')
       product_id = input()

       c.execute("INSERT INTO price(product, cost, product_id) VALUES (?,?,?)", (product, cost, product_id))
       conn.commit()
       print('do you want to add another product? y/n')
       loop = input()
       if loop == 'y':
              dataEntry()
       else:
              main()
def removeProduct():
       print('Sorry this is not currently avalable :(')
       time.sleep(2)
       main()

def machine():
       global total
       print('If finished type /')
       search = input('Please type or scan the product id: ')

       if search == '/':
              print('Total to pay is:£',total)
              payment = float(input('Ammount given:£'))
              change = float(total-payment)
              change = round(change, 2)
              print('Change:£',change)
              time.sleep(3)
              total = float(0.00)
              main()
       else:

              c.execute("SELECT * FROM price WHERE product_id =?",(search,))
              for row in c.fetchall():
                     print(row[0],row[1])
              #total is at the top
              price = float(row[1])
              amount = int(input('quantity = '))
              total = float(total+price*amount)
              total = round(total,2)
              print('Your overall total is:£',total)

              machine()

def productCheck():
       search = input('Please type or scan the product id: ')
       c.execute("SELECT * FROM price WHERE product_id =?",(search,))
       for row in c.fetchall():
              print(row[0],row[1])
       time.sleep(1)
       main()

def productList():
       c.execute("SELECT * FROM price")
       for row in c.fetchall():
              print(row)
       print('press / to exit')
       leave = input()
       if leave == '/':
              main()
       else:
              productList()

def main():

       print('Welcome to James POS')
       print('What do you want to do?')
       print('option 1: Add a product')
       print('Option 2: Remove a product(currently not avalable)')
       print('option 3: Product check')
       print('option 4: Use the POS')
       print('option 5: Show all products')
       print('option 6: Exit')
       action = input()

       if action == '1':
              dataEntry()
       elif action =='2':
              removeProduct()
       elif action == '3':
              productCheck()
       elif action == '4':
              machine()
       elif action == '5':
              productList()
       elif action == '6':
              exit()
       else:
              print('Sorry something went wrong')
              main()

creatTable()
main()
c.close()
conn.close()

A: You have this part:
 payment = float(input('Ammount given:£'))
 change = float(total-payment)
 change = round(change, 2)
 print('Change:£',change)

Don't round your data of in order to get it shown with two decimals. Just ask to have it printed with two decimals using string formating:
print('Change: {0:.2f}'.format(change))
# Or, old syntax:
print('Change: %.2f' % change)

As mentioned in the comments, pyformat.info is a good reference.


text:
Q: Node Aggregate Log i am looking to get a simple random sample using Node.
In the console it works with db.commands.aggregate({$sample: { size: 1 }})
But when i console.log the result using Node it returns an AggregationCursor object.
commands.aggregate( [{ $sample: { size: 1 } }], function(err, result) {
    console.log(result);
    client.close();
});

A: Apparently aggregate returns an array, and can be iterated using forEach.
This was the solution that worked for me, ultimately returning the single document as an Object.
commands.aggregate([{ $sample: { size: 1 } }])
    .forEach((doc) => {console.log(doc)} ,
        (err) => {console.log(err);}
);


text:
Q: Using "Balance W0" in Payments & Applications screen I am trying to create a "Balance WO" document in Payments & Applications screen, after selecting customer when I click on save I got an error saying

Value cannot be null

Is this is the right place to enter the "Balance WO" document? I am doing this in fresh Acumatica instance with demo data installed and without any packages published.
Acumatica 2017 R2 - Build 17.210.0034

A: Seems like you can't manually create Balance WO. Acumatica has separate processing page for that purpose Write Off Balances and Credits where you can specify the limit and generate Balance WOs

After processing the Balance WO payment will be generated:


text:
Q: How to create noise on a 5V PCB? For randomness entropy I think I need some noise. My PCB is powered with 9V battery that's reduced to 5V using 7805 and I have a PIC16F15386 on it. There is little to no noise on the power lines so I cannot use that. My book on analog electronics says that zener diodes produces some noise, especially above 6V.
Question 1: Would it be possible to add a 7.5V zener to the board and use the PIC A/D to read the zener, and use the result as a start value for srand()? Or will that not be enough?
Question 2: The PIC uses INTOSC and I have the ability to use the clock out-pin. Can I feed the clock signal to the A/D and use that as a noise generator?
Are there any other ways I can explore?
EDIT: Added name of PIC.

A: Question 2: it looks like the clock you're proposing to use is the same clock that drives the ADC itself, so that would not work.  Even if it were an independent clock it would be a poor random number generator since the ratio of the clock to the ADC conversions would produce patterns in the numbers that you generate


text:
Q: Read information from Bluetooth NFC reader I'm trying to make an Android app (Java) that reads the information from an "NFC to Bluetooth reader" (like this one).
Basically, the device will read the information from the NFC and transfer it to Bluetooth.
I'm trying to make an app that reads the information from that device via Bluetooth, but I haven't found any solution.
Is there any link or keyword that could help?

A: Usually, these Bluetooth readers come with a library. The product you provided sells some development tools that would probably help you integrate it into your application. Though very costly.
I found a github repository, which provides a library to connect to NFC Readers via USB. Bluetooth connections are supported as Beta for exactly your linked product. So, I think the repository is a good starting point for you.
I personally worked with these readers, where a fully functional library was provided. I can 100% recommend them, however I think they were pretty costly.
EDIT: I looked again on the website of your product and they provide some downloads. Two of the downloads are for their sample Android application, which includes the application's source code as well as their library. So, if you got that product simply download their resources and integrate the parts you want in your applcation.


text:
Q: убрать пробелы из строки средствами c# Как лучше написать код для удаления символов пробела из строки?

A: Используйте Replace:
string original = " some string ";
string replaced = original?.Replace(" ", "");

Вывод:

somestring

Если на входе будет null, то вернёт null.

A: Этот код:
"      da ta    ".Replace(" ", "")

Вернет "data"
Еще пример:
var str = " some str ";
var strWithoutSpaces = str.Replace(" ", "");
Console.WriteLine(strWithoutSpaces); //somestr

Можно также добавить null-условный оператор:
string nullstr = null;
var nullstrWithoutSpaces = nullstr?.Replace(" ", "");
Console.WriteLine(nullstrWithoutSpaces); //null

Если необходимо убрать только пробелы из начала и конца строки, то можно воспользоваться методом Trim:
string str = "   da ta   ";
var trimmedstr = str.Trim();
Console.WriteLine(trimmedstr); //da ta


text:
Q: Какую команду написать чтобы у телеграмм бота сразу появились кнопки? Хотел бы, чтобы у моего бота появлялись сразу кнопки или когда написать любые сообщения, появлялись кнопки, которые есть у бота. Когда скидываю ссылку бота знакомым, кнопки сразу не появляются.

Чтобы не пришлось нажимать на иконку(кнопки бота) которую я отметил желтым цветом. То бишь, не все могут догадаться об этой иконке.


text:
Q: javascript: How to add div to table cell dynamically? I have a table which is filling dynamically via SignalR+knockout.js

I'd like to somehow add a new cell and draw chart (flotchart.org) with MemPercent to this cell.
How to add this?
In a static case the chart can be made this way:
var container1 = $("#placeholder1");
        var plot1 = $.plot(container1, dataSeries, {
            series: {
                shadowSize: 0
            },
            yaxis: {
                min: 0,
                max: 100
            },
            xaxis: {
                show: false
            }
    });

function update() {
            plot1.setData(series);
            plot1.draw();
            setTimeout(update, updateInterval);
        }

        update();

My questions:
1. how to add cell with chart dynamically?
2. how to access any chart containers during the update?
Thnx.

A: You can simply add chart to the table row with jQuery
$('tbody').append('

');

I think you will need to enter this code inside a loop.
To take the data to put in the cell, you can use an Ajax Call


text:
Q: InDesign resize Text Frame I want to resize entire indesign document width and height here is my code its give error
Error Number:11265
Error string: This value would cause one or more object to leave the paste board
please help me to fix, Thank you
var NEW_HEIGHT = '25 cm';
var NEW_WIDTH = '18 cm';

// MULTIPLE RESIZE() IN ONE STEP
// =============================
app.activeDocument.textFrames.everyItem().resize(

    // Target bounding box(es) -- Use OUTER_STROKE_BOUNDS if needed
    // ---
    [CoordinateSpaces.INNER_COORDINATES, BoundingBoxLimits.GEOMETRIC_PATH_BOUNDS],

    // Reference point -- Here resize is performed relative to the top edge
    // ---
    AnchorPoint.TOP_CENTER_ANCHOR,

    // Absolute replacement
    // ---
    ResizeMethods.REPLACING_CURRENT_DIMENSIONS_WITH,

    // [width, height] in points
    // ---
    [UnitValue(NEW_WIDTH).as('pt'), UnitValue(NEW_HEIGHT).as('pt')]
    );

A: You need to increase the size of the pasteboard before you begin resizing.
To do this add the following line of code before your resize step:
app.activeDocument.pasteboardPreferences.pasteboardMargins = [ '1000pt', '1000pt'];

Note: You may need to increase the x and y values (i.e. 1000pt) depending on the size of your document(s).
Further info regarding the PasteboardPreference class can be found here.


text:
Q: Import .txt file to matlab, anything works I have a problem importing data to matlab workspace. My file is a .txt file with 8 columns and a lot of rows (I cannot count them). The first 5 columns are numbers, but the 3 last are paths (letters), each path indicates the position of an image that correspond to the first 5 datas.
I want to save the whole file into a matrix, I have tried load (but it doesn't work when I mixed characters), textscan (but it gives me just a row vector), impordata (but only write the first column data), fscan.... I think I have tried every command, and still doesn't work.
I want to specify that the text I have is another variable I want to save to work with it in a future, is not a headline.
Can any one help me?
Thanks in advance.

A: You should store your data into a cell, not a matrix, textscan should work without any problems
fileID = fopen('file.txt');
C = textscan(fileID,'%f %f %f %f %f %s %s %s');
fclose(fileID);

If you have a particular delimiter between your column you can specify this delimiter:
C = textscan(fileID,'%f %f %f %f %f %s %s %s','Delimiter','|')


text:
Q: Joomla main menu customization How can I customize the joomla main menu like this:
http://www.ruckuswireless.com/

A: That's not going to be a quick and easy hack, but you might be able to pull it off with an HTML override. If you want something close, you can probably get close with one of the mega menu extensions.
If you want to hack it yourself, you will need to get a copy of JOOMLAINSTALL/modules/mod_mainmenu/tmpl/default.php and put it in JOOMLAINSTALL/templates/YOURTEMPLATE/mod_mainmenu/default.php once you have made the modifications.
You can use the menu item image for the image at the top of the dropdown. The menu description is a little trickier, but most menu systems use the menu Title for this purpose. When you put in the title you will need a separator so you can then split the title in to the the title and the description. The format would have to be something like MENU TITLE|MENU DESCRIPTION.
This is a pretty big modification but that is the general idea.


text:
Q: XeroAccountingApiException: 400: Invoice not of valid status for modification I am getting a validation error from the Xero API:

Invoice not of valid status for modification

The message is too generic, and we have no idea why we are getting it or how to fix it.
I've tried different status values:

*

*DRAFT

*AUTHORISED

But I get the same response:
{
  "ErrorNumber": 10,
  "Type": "ValidationException",
  "Message": "A validation exception occurred",
  "Elements": [
    {
      "Type": "ACCPAY",
      "InvoiceID": "1cb8f5c6-xxxx-xxxx-xxxx-9ca48a1cac06",
      "InvoiceNumber": "CS-001854",
      "Payments": [],
      "CreditNotes": [],
      "Prepayments": [],
      "Overpayments": [],
      "AmountDue": 1350.00,
      "HasErrors": true,
      "IsDiscounted": false,
      "Attachments": [],
      "Contact": {
        "ContactID": "3dd542c0-xxxx-xxxx-xxxx-176cc1c484d8",
        "Addresses": [],
        "Phones": [],
        "ContactGroups": [],
        "SalesTrackingCategories": [],
        "PurchasesTrackingCategories": [],
        "ContactPersons": [],
        "Attachments": [],
        "HasValidationErrors": false,
        "ValidationErrors": [],
        "Warnings": []
      },
      "DateString": "2018-08-31T00:00:00",
      "Date": "\/Date(1535673600000+0000)\/",
      "DueDateString": "2018-09-14T00:00:00",
      "DueDate": "\/Date(1536883200000+0000)\/",
      "Status": "DRAFT",
      "LineAmountTypes": "Exclusive",
      "LineItems": [
        {
          "Description": "Services",
          "UnitAmount": 450.00,
          "TaxType": "NONE",
          "TaxAmount": 0.00,
          "LineAmount": 450.00,
          "AccountCode": "6021",
          "Tracking": [],
          "Quantity": 1.0000,
          "ValidationErrors": [],
          "Warnings": []
        },
        {
          "Description": "Services",
          "UnitAmount": 450.00,
          "TaxType": "NONE",
          "TaxAmount": 0.00,
          "LineAmount": 450.00,
          "AccountCode": "6021",
          "Tracking": [],
          "Quantity": 1.0000,
          "ValidationErrors": [],
          "Warnings": []
        },
        {
          "Description": "Services",
          "UnitAmount": 450.00,
          "TaxType": "NONE",
          "TaxAmount": 0.00,
          "LineAmount": 450.00,
          "AccountCode": "6021",
          "Tracking": [],
          "Quantity": 1.0000,
          "ValidationErrors": [],
          "Warnings": []
        }
      ],
      "SubTotal": 1350.00,
      "TotalTax": 0.00,
      "Total": 1350.00,
      "CurrencyCode": "GBP",
      "ValidationErrors": [
        {
          "Message": "Invoice not of valid status for modification"
        }
      ],
      "Warnings": []
    }
  ]
}

Reference:

*

*Xero Developer API Documentation: Invoices

A: You can only modify Invoices that have the status of: 'DRAFT' or 'SUBMITTED', if it has any other status you cannot modify it, you have to delete it, and create a new one.
I believe you are probably trying to amend an 'AUTHORISED' invoice which isn't permitted via the API.
https://developer.xero.com/documentation/api/invoices
EDIT: You need to either Delete or Void an Invoice depending on Status. Here is an excerpt from my c# code using the .NET API.
If the invoice is AUTHORISED you need to set it's status to VOIDED, if it's DRAFT or SUBMITTED you set it's status to DELETED
        var invoice = new Invoice();
        var api = XeroApiHelper.CoreApi();
        try
        {
            invoice = api.Invoices.Find(invoiceno);
        }
        catch (Exception ex)
        {
            // Handle the exception
        }
        if (invoice.AmountPaid == null || (invoice.AmountPaid != null && invoice.AmountPaid == 0))
        {
            if (invoice.Status == InvoiceStatus.Voided || invoice.Status == InvoiceStatus.Deleted)
            {
                //Invoice is already deleted or voided
                return false;
            }
            invoice.Status = invoice.Status == InvoiceStatus.Authorised ? InvoiceStatus.Voided : InvoiceStatus.Deleted;
            try
            {
                api.Invoices.Update(new List<Invoice> { invoice });
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }
        // Invoice has a payment on it
        return false


text:
Q: Зачем нужен виртуальный деструктор при наследовании? Насколько я понял, виртуальный деструктор нужен, чтобы в наследованном классе можно было вызвать (прямо оттуда) деструктор базового, а т.к. простой деструктор наследованный класс не понимает, то нужно создавать виртуальный.
И всё это, чтобы не было никакой утечки памяти.
Так ли я понял суть?

A: Добавлю к очень хорошему объяснению пользователя VladD следующий код, который очень часто можно встретить везде:
#include <iostream>

class Base
{
public:
  Base() { std::cout << "Base constructor\n" << std::endl; }
  virtual ~Base() { std::cout << "Base destructor\n" << std::endl; }
};

class Derive : public Base
{
public:
  Derive() { std::cout << "Derive contructor\n" << std::endl; }
  virtual ~Derive() { std::cout << "Derive destructor\n" << std::endl; }
};

int main()
{
  Base * ptr = new Derive;
  delete ptr;
  return 0;
}

Результатом выполнения будет:
$ ./example
Base constructor

Derive contructor

Derive destructor

Base destructor

Обратите внимание на порядок вызовов конструкторов и деструкторов. Деструкторы вызываются в обратном порядке относительно вызовов конструкторов. А теперь уберите ключевое слово virtual из ~Base() и ~Derive(), как следствие деструктор класса Derive не будет вызван:
$ ./example
Base constructor

Derive contructor

Base destructor

Если от Вашего базового класса планируется далее наследоваться другие классный деструктор должен быть виртуальный. Рекомендую почитать Скота Мейерса, у него отличные книги по C++.

A: Не, немного не так. Деструктор базового класса из деструктора производного вызывать не надо (да и нельзя), он сам вызовется автоматически. Проблема в другом: деструктор производного класса может быть не вызван!
Представьте себе такую ситуацию:
class Person
{
    ~Person() { } // деструктор не виртуальный
};

class Spy : public Person
{
    Gadget* gadgets;
public:
    Spy() { gadgets = new Gadget[10]; }
    ~Spy() { delete[] gadgets; }
};

std::vector<Person*> citizens;
// наполнить значениями
for (Person* citizen : citizens)
    delete citizen;

Что случится, если в списке будет один Spy? А вот что: при уничтожении объекта типа Spy по указателю типа Person* вызовется невиртуальный деструктор ~Person. Значит, память под массив gadgets не будет освобождена. Вот вам и утечка памяти.
На самом деле, кроме утечки памяти может произойти любая другая неприятность, ведь деструктор, на который вы рассчитывали, не вызовется! Например, может не закрыться файл, и при следующей попытке его открыть программа вылетит. Или не отпустится мьютекс, и при попытке его получить программа зависнет. Ну и ещё куча всяких катастроф может произойти.
Хуже того, по стандарту отсутствие виртуального деструктора в данном случае является undefined behaviour, то есть, программа имеет право сделать что угодно: отформатировать винчестер, признаться в любви к вашей химичке через «Вконтакте» или подлить валерьянки в миску с Вискасом.

Да, а в C деструкторов нету вовсе.


text:
Q: Streaming media from a download link There often discussions and many facilities available to download streaming media (eg Youtube, Vimeo, etc), however is there a way it can stream a download link? Currently, my internet connection is prohibitively slow to download a video and I would prefer if I could watch the video while it is still downloading but I couldn't find how to do this. I did find this article but it appears to need your own media server.

A: At least some file formats [please edit if anyone knows which!] can be played in part before the download is complete.
If that doesn't work, it might be only because your downloader (e.g. Chrome) changes the file extensions to something like ".part" or whatever, which prevents your player from recognizing it. In that case, you might try copying and renaming the partially downloaded file.
If the video format is supported, some players will allow you to stream it by simply inputting the download URL in your player like you would a local file path. Have you tried VLC Media Player? If not, download that and try going to "Media" > "Open Network Stream..." and enter the download URL for the video you want to watch. (VLC also makes it fairly easy to serve a stream if you want to (see the docs).)
Finally I will echo points made in comments again here: 1) A slow connection means downloading is generally more advisable then streaming. 2) If the video you want is available by Torrent, clients like Vuze will stream it. A Torrent download will make the most of your slow connection compared to HTTP.

A: Follow these instructions (For the  best result use computer)

Step 1. Open the notepad or any text editor and paste the following code on that.
    <html>
    <body>
    <video src="Download link" controls></video>
    </body>
    </html>

Step 2. Replace Download link with the actual download link.
Step 3. Now save this text as html
Step 4. Now open this html file and enjoy your show.

A: In Openload.co:
To convert stream link: https://openload.co/stream/somecodeshere
From Dowload Link, just replce the word "stream" to "f".
The DLink should be like this: https://openload.co/f/somecodeshere
Hope it helps.


text:
Q: Displaying a GridView after using a new xml for dimesion I ran the example program for Gridview. I had set the layout params to 400, 400 which was working fine on the nexus 5. But when I executed the same for a samsung tablet and an emulator with 2.3.3 the image size was a chaos overlapping on each other. In one of the links I came to know that I should use a new dimension.xml file and setLayoutParams should pick the dimension from that file. It worked fine on the tablet and the emulator, the problem is in nexus 5 now. I am not able to see a single picture although application launches. I can see only a grey color page. Thanks in advance.
My ImageAdapter class is as follows
 public class ImageAdapter extends BaseAdapter {

         private Context mContext;

            public ImageAdapter(Context c) {
                mContext = c;
            }

            public int getCount() {
                return mThumbIds.length;
            }

            public Object getItem(int position) {
                return null;
            }

            public long getItemId(int position) {
                return 0;
            }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
                imageView = new ImageView(mContext);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8,8,8,8);
                imageView.setLayoutParams(new GridView.LayoutParams(R.dimen.width,R.dimen.height));
            } else {
                imageView = (ImageView) convertView;
            }

            imageView.setImageResource(mThumbIds[position]);
            return imageView;
        }

        // references to our images
        private Integer[] mThumbIds = {
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_7, R.drawable.wallpaper,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_7, R.drawable.wallpaper
        };
    }

My activity_main.xml is as follows
    <?xml version="1.0" encoding="utf-8"?>
    <GridView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="2dp"
        android:numColumns="2"
        android:verticalSpacing="5dp"
        android:horizontalSpacing="1dp"
        android:stretchMode="columnWidth"
        android:drawSelectorOnTop="True"

        android:gravity="center_vertical|center_horizontal"
        android:layout_gravity="center"
    />

My dimens.xml is as follows
    <?xml version="1.0" encoding="utf-8"?>
    <resources>

        <!-- Default screen margins, per the Android Design guidelines. -->

        <dimen name="width">150dp</dimen>
        <dimen name="height">150dp</dimen>
    </resources>

A: Don't rely on hard-coded values for your dimensions if you don't have to. Android devices have so many form factors you will drive yourself crazy trying to figure out proper values for every device. Since you are already setting the number of columns in the GridView, why not let that determine the size? If you want, you can vary the number of columns to accommodate larger screens or landscape orientation.
In res/layout/activiy_main.xml:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="2dp"
    android:numColumns="@integer/gridview_columns"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="1dp"
    android:stretchMode="columnWidth"
    android:drawSelectorOnTop="True"

    android:gravity="center_vertical|center_horizontal"
    android:layout_gravity="center"
/>

In res/values/dimens.xml:
<integer name="gridview_columns">2</integer>

In res/values-sw600dp/dimens.xml:
<integer name="gridview_columns">3</integer>

In res/values-sw720dp/dimens.xml:
<integer name="gridview_columns">4</integer>

A: Create dimensions for different screens. Dont use default dimen.xml from values folder.
Kindly create as follows.
values-hdpi
     -dimens.xml
values-mdpi
     -dimens.xml
values-xhdpi
     -dimens.xml
values-xxhdpi
     -dimens.xml
values-large-mdpi
     -dimens.xml
values-600dp(for 7" Tablet)
     -dimens.xml
values-720dp(for 10" Tablet)
     -dimens.xml
Set the values according to the screen sizes in the above folders. This will suit all the screen densities in android devices including Tablets and mobiles. for converting dp's and sp's to support different screen resolutions kindly use this link


text:
Q: How do unit tests and integration tests actually run? There are plenty of resources that explain what unit and integration testing are and why they are important. That is not what I am asking here.
I am trying to understand how unit/integration tests are run and how they work.
I have a very tenuous grasp of how these tests work behind the scenes and I'd like some help in understanding them. I'm not asking about the inner workings of specific testing frameworks but what happens with the code when you decide to run a test.
Based on my understanding:
Unit tests
You have a function Foo() and in a separate class, you write a test for Foo() called TestFoo().  You decide to run your test using some framework. When running the test, the framework spins up a running version of your code and a fake mock database and uses the test inputs given in TestFoo to call Foo. Any dependency injected code is mocked away via the test and given dummy values as well. Once the function Foo() is done executing, we assert that the results are as expected.
Integration tests
You have a test that covers multiple units of the system including hitting a dev database. You run the test which spins up a running platform, calls Foo() and queries the return values and/or database for the appropriate changes.
As you can tell, it's a very handwavy explanation. I'd like to some help to flesh out my understanding of how the tests are run, how mocks are set up and how the tests manage to call functions with mock/live components.

A: Tests are just programs that run test cases. Some test frameworks have a separate test runner that can discover and execute all test cases. How that works depends a lot on the programming language. Sometimes the test runner is integrated in an IDE.
Integration tests are more likely to be standalone programs that runs the System Under Test. Often, integration tests are scripts that set up the test environment and then launch the software being tested. On one project I'm working on, there is a large corpus of integration tests. Each test has its own directory with data and extra software, plus a script that controls how the test is compiled and executed. The test runner is little more than a loop through all the directories to launch the test script.
Unit tests don't necessarily involve dependency injection. The unit test should test some unit in isolation, which means that the unit should not involve external dependencies. However, some software is already designed in a way that this is easy to do. It is also not mandatory to isolate the unit – it can be perfectly fine to keep hardcoded dependencies, especially if those dependencies have no side effects.
It's also useful to note that tests do not have to be automated — you can theoretically run unit tests in a debugger or a REPL, and run integration tests by hand. Of course, scripting the tests has the advantage that they are easily repeatable and therefore add a lasting benefit to the project. That's also part of the idea of TDD: to first write a test and then the software to make it pass, rather than writing some software and afterwards experimenting to see whether it even works.

A: I think you are confusing Unit/Integration tests with mocking.
A unit test runs on real classes. The dependencies can be "real world" classes or fake instances - it depends on how you write the tests.
For mocking classes you can use external libraries like Moq or NSubstitute. Or you can use real classes.
The concept of "unit" test is about what you are testing, not how. If a class requires an object in the constructor but you are not using it in the part you are testing, you can also use a real implementation instead of a mock.


text:
Q: How to test a method that uses the cache variable? <?php

use yii\db\ActiveRecord;

class Model extends ActiveRecord
{
    protected static $ids = [];

    public static function getIds()
    {
        if (empty(static::$ids)) {
            static::$ids = static::find()->select('id')->column();
        }

        return static::$ids;
    }
}

How to use the test to make sure that the query is executed once by repeatedly calling this method ?
Preferably using codeception or phpunit.

A: Tests are not just a way to ensure your code works, they also help identify code smells. In your case writing a test is hard, because you use static methods.
There used to be a staticExpects method but that was deprecated in phpunit long ago, so that's not really feasible. The best way to make this code testable is to remove the static keyword. This is easy for getIds() but since the static find() is defined by a 3rd party (yii's ActiveRecord) you can't really remove it. Instead you could wrap it in a non-static method. This gives you the benefit of being able to move away from the Active Record to some other implementation like Doctrine in the future, by just touching these small methods wrapping the 3rd party code.
Once you do this you could create a partial mock of your model to make sure that method is called:
class Model extends ActiveRecord
{
    private $ids;

    protected function findIds()
    {
        return static::find()->select('id')->column();
    }

    public function getIds()
    {
        if (empty($this->ids)) {
            $this->ids = $this->findIds()
        }

        return $this->ids;
    }
}

and in your test:
public function testFindIdsIsCalledWhenGetterIsNotInitialized()
{
    $model = $this->getMockBuilder(Model::class)
        ->setMethods(['findIds'])
        ->getMock();
    $model->expects($this->once())
        ->method('findIds')
        ->will($this->returnValue([1, 2, 3]));

    $ids = $model->getIds();

    $this->assertEquals([1, 2, 3], $ids);
}

This should have 2 assertions, one for the expected method call and one for the returned values. This test bypasses the Active Record and only ensures that your getIds() method works as expected. Another way to approach this is, as mentioned in the comments to your question, to use a functional test that actually tests the database interactions by fetching the data from a (test) database. Obviously since this requires having a database connection and retrieving test data, e.g. from some previously setup fixtures, it's a bit more work and the test will be slower. Depending on how big your project is that might not be an issue and you might feel more comfortable testing the logic in the Active Record implementation as well.


text: Q: How to disable dots in around the controls in c#.net Hi there i want to disable the dots around the controls when user selected it (for example in a tab control ) but I can't. I tried to set false all fields in controls properties but nothing happened.


text:
Q: How to display random posts in Wordpress? How to display random posts for each category when the url style like : http://www.whatever.com/category/all-english/poetry/, so each time I click the category link it display different posts
I tried this :
$cat=get_query_var( 'cat' );
query_posts('cat=$cat&orderby=rand');
if (have_posts()) :
    if ( $is_top_single ) $GLOBALS['more'] = false; //important
    while (have_posts()) : the_post(); ?>

but the result is not true, it display random posts for all categories !

A: You need to learn how to use query_posts. You can edit your archive.php or category.php as follows:
query_posts(array(
    'showposts' => 6,
    'orderby' => 'rand',
    'category_name' => 'News' //You can insert any category name
));
if (have_posts()) : while (have_posts()) : the_post();


text:
Q: Differentiability of function definition Study the continuity and differentiability of function in point $(0,0) $ where $f:\mathbb{R}^2\rightarrow \mathbb{R}$
$f(x,y)= \begin{cases}
0 & \left(x,y\right)\:=\left(0,\:0\right) \\
\frac{x^3y}{x^4+y^2} & \left(x,y\right)\ne \left(0,0\right) \\
   \end{cases}
$
I can see that the function will go towards 0 as (x,y) goes towards 0, so that makes it continuous. But what about differentiability?
The definition I got in class is rather fuzzy. Basically, it's like this:
Step 1. Check if the function can be derived in point a - in my case $(0,0)$
If it isn't the function wont be differentiable in point a.
If it is, calculate the partial derivatives and proceed to step 2.
Step 2. Study the limit:
$$l=\lim _{h->O_m}\left(\frac{f\left(a+h\right)-f\left(a\right)-<h,\Delta f\left(a\right)>}{\left|\left|h\right|\right|}\right)$$
if $l=O_m$ then the function is differentiable in point a. Otherwise it is not.
Also, $l=\lim _{\left(h_1,....,h_m\right)\rightarrow O_m}\left(\frac{f\left(a_1+h_1+...+a_m+h_m\right)-f\left(a_1,...,a_m\right)-\sum h_j\left(\frac{\:∂L}{\:∂x_j}\left(\right)\right)}{\sqrt{h_1^2+...+h_m^2}}\right)$
My problem is that I don't really understand the definition. I also might've written it down wrong, and I also have problems understand the terms that appear in it. I tried looking online but what I could find didn't really answer all my questions. Can someone help me understand this, so that I can solve exercises such as these, and possibly with more variables as well, in other points?


text:
Q: I can't add data to chartjs from codeigniter How can I encode json for $info['data'] in codeigniter framework
public function chartjs(){
        $info['title'] = 'Chartjs';
        $info['data'] = $this->post_model->get_posts();
        $this->load->view('templates/header');
        $this->load->view('chartjs',$info);
        $this->load->view('templates/footer');
    }

A: // This Is edited Code for encode json for $info['data']
public function chartjs(){
        $info['title'] = 'Chartjs';
        $post_data = $this->post_model->get_posts();
        $info['data'] = json_encode($post_data);
        $this->load->view('templates/header');
        $this->load->view('chartjs',$info);
        $this->load->view('templates/footer');
    }

I am sure help of this code You can encode json correctly.
Thanks,
Kamiyab ali


text:
Q: Linq expression where clause with generic type In my Data access layer,  I am calling the GET method with the following Lambda expression :
public List<T> Get<T>() where T : class
{
   var list = Context.Set<T>().ToList().Distinct().Where(x => x.Content_type == "Test");
   return list;
}
But getting error

"Cannot resolve symbol Content_type"

How can i resolve this issue ?

A: The problem is that Content_type is not a part of T class because it's just a class.
As @tchelidze says, you can set a where clause on your function to specify a type, like this :
public List<T> Get<T>() where T : IYourCommonInterface
{
    var list = Context.Set<T>().Where(x => x.Content_type == "Test").Distinct().ToList();
    return list;
}

But if you need to be totaly generic, you can add a selector to your function like this :
public List<T> Get<T>(Func<T, object> selector) where T : class
{
    var list = Context.Set<T>().Where(x => selector(x) == "Test").Distinct().ToList();
    return list;
}

And use it like that :
Get(x => x.Content_type);

Also, if you want to go further, you can pass the entire condition :
public List<T> Get<T>(Func<T, bool> condition) where T : class
{
    var list = Context.Set<T>().Where(condition).Distinct().ToList();
    return list;
}

And use it like this :
Get(x => x.Content_type == "test");

Hope it helps.

A: Reason is that all you know about T is that it is a class. You do not know if it contains Content_type property or not.
If you always pass T class which contains definition for Content_type try following .
Context.Set<T>().ToList().Distinct().Where(x => (x as SomeClassWithContentTypeField).Content_type == "Test");
Better way will be if you introduce interface IHasContentTypeField which declared Content_type property
public interface IHasContentTypeField
{
  string Content_type { get; set; }
}

then constraint T to this interface.
public List<T> Get<T>() where T : IHasContentTypeField

Then you can implement IHasContentTypeField in classes for which you want to call Get<T> method.
public class A : IHasContentTypeField
{
  public string Content_type { get; set; }
}


text:
Q: AdapterHandler - abstract class Null Pointer Exception I have onClickListener in my Custom Adapter for ListView
 holder.name.setText(dataModelList.get(position).getRadio_name());

    final ViewHolder finalHolder = holder;
    holder.name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(adapterhandler !=null) {
                adapterhandler.updateText(dataModelList.get(position).getRadio_name());
            }

            if(!mRadioManager.isPlaying()) {

                mRadioManager.connect();
                mRadioManager.startRadio(dataModelList.get(position).getRadio_url());

            }
            else
            {
                mRadioManager.stopRadio();
            }

        }
    });

Then I made Abstract Class to update TextView
    public abstract class InterfaceUpdate

{
    public void updateText(String text) {}
}
and Listener in Fragment to update TextView:
 @Override
public void onRadioStarted() {

    adapter.adapterhandler = new InterfaceUpdate() {
        @Override
        public void updateText(String text) {

            super.updateText(text);
            title.setText(text);

        }
    };

What is my problem? I cannot make
adapterhandler.updateText(dataModelList.get(position).getRadio_name());
without checking if it's null, because it's generate NullPointerException
when I click on list element first time, TextView is not changing, second time is changing perfect ...;/ Any idea how to not make this adapterhandler null?

A: The problem is your adapterhandler is not being created until after the first time you try and call updateText.  (It's not called until the onRadioStarted() callback is called by mRadioManager.startRadio)
Try this (although constructing your handler in onClick is not a great design)
holder.name.setText(dataModelList.get(position).getRadio_name());

final ViewHolder finalHolder = holder;
holder.name.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (null == adapterhandler) {
            adapterhandler = new InterfaceUpdate() {
                @Override
                public void updateText(String text) {
                    title.setText(text);
                }
            }
        }
        adapterhandler.updateText(dataModelList.get(position).getRadio_name());
        if(!mRadioManager.isPlaying()) {
            mRadioManager.connect();
        } else {
            mRadioManager.stopRadio();
        }
    }
});

And change your onRadioStarted:
@Override
public void onRadioStarted() {
     mRadioManager.startRadio(dataModelList.get(position).getRadio_url());
};


text:
Q: A poset with small "cycles" (A followup to this recent question.)
I noticed the following curious property of a poset (which I strongly believe to be a lattice, I'm still trying to prove that…):
Suppose that $z$ is covered by $x$ and $y$.  Then there is a common upper bound $w$ of $x$ and $y$ such that either

*

*$w$ covers both $x$ and $y$, or

*$w$ covers either $x$ or $y$  (say $y$), and the other element is separated from $w$ by exactly one more element (say $a$).

(There is an example poset, computed using sage-combinat and dot2tex.)
Using ASCII art, all relations are covering:

    w                 w
   / \               / \
  x   y      or     a   |
   \ /              |   |
    z               x   y
                     \ /
                      z

Does this property have some name?  Could it be helpful for proving that the poset is a lattice?
Although it's rather trivial, let us note that there are non-lattices having this property:

    1
   / \
  2   3
  |\ /|
  |/ \|
  4   5
   \ /
    6

Hm, could it be that such a poset (i.e., with restricted cycle lengths) and with no occurrences of

  a   b            a    d
  |\ /|     and    |\  /|
  |/ \|            b \/ |
  c   d            | /\ |
                   c    e

is a lattice...?  No, this is not the case:

      1
     /|\
    / | \
   /  |  \
  2   3   4
  |\ / \ /|
  |/ \ / \|
  5   6   7
   \ / \ /
    8   9
     \ /
      0


text:
Q: Slow IO Performance with PERC H700/710 with current linux distributions we noticed really bad write performance, on our new Dell R720 with Perc 710.
Especially when it come to writing a lot of small files.
The funny thing is that this bad performance only occurs on newer linux distributions like ubuntu 14.04. or latest centos. Doing the same operation on
Ubuntu 10.04 or other distributions from around 2012 the performance is okay. I fear it's related to something in the kernel like new megaraid_sas driver ?
Below you can see some of the configurations and tests i was using/doing.
Setup:
Dell R720
RAID: PERC 710 Mini Rev: 21.3.011 -00009
HDD: 2x600GB 15K SAS SEAGATE  ST3450857SS

Raid 1
Write Policy: Write Back
Read Policy: Read Ahead
Disc Cache: Enabled
Filesystem: tested with xfs and ext4
lspci: 03:00.0 RAID bus controller: LSI Logic / Symbios Logic MegaRAID SAS 2208 [Thunderbolt] (rev 05)

Results Ubuntu 14.04:
dd if=/dev/zero of=/root/testfile bs=512 count=10000 oflag=dsync
10000+0 records in
10000+0 records out
5120000 bytes (5.1 MB) copied, 1.33572 s, 3.8 MB/s

Results Ubuntu 10.04:
dd if=/dev/zero of=/root/testfile bs=512 count=10000 oflag=dsync
10000+0 records in
10000+0 records out
5120000 bytes (5.1 MB) copied, 0.702619 s, 7.3 MB/s

The same results i got on a Dell R710 which has the PERC H700.
I wonder if anyone has a solution to that or a recommendation for a RAID Controller card which works better with the mega_raid_sas driver or uses another driver ?
btw: I did an IOMeter Test according to Dell, same poor results on latest Linux distribution e.g. Redhat. On Windows it works fine, so really looks like a driver/kernel Problem.


text:
Q: A point measure is radon This is taken from the Chapter 3 of Resnick's Extreme Values, Regular Variation and Point Processes.
Consider a point process with state space $E$ which is locally compact with a countable basis. Let $\mathcal E$ be the Borel $\sigma$-algebra of subsets of $E$.
For $x\in E$, define the measure $\varepsilon_x(A)=1$ if $x\in A$, $\varepsilon_x(A)=0$ if $x\notin A$.
Now take a countable collection $\left\{x_i,i\geq 1\right\}$ of points of $E$ and define
$m:=\sum_{i=1}^\infty\varepsilon_{x_i}$
Then for any $K\in\mathcal E$ compact, $m(K)<\infty$.
There is something I do not understand, because if I take $E=\mathbb R$, then I can find compact sets with an infinite number of points, so $m(K)=\infty$. Where is my confusion?

A: You're right, of course.  But I think what Resnick means is to make this condition part of the definition of a "point measure".  That is, a point measure should be a measure $m$ of the form $m=\sum_{i=1}^\infty \varepsilon_{x_i}$, with the additional requirement that $m(K) < \infty$ for each compact $K$.  So, for instance, taking $\{x_i\} = \mathbb{Q}$  isn't supposed to yield a point measure.
Resnick's wording (page 123) isn't very clear, but I think this is the only sensible interpretation.


text:
Q: Function that calculates the total number of unique words in a textfile I'm using Python 3 and I am trying to write a function that calculates the total number of unique words in a textfile. I wrote some code below but when I run it, for some reason I only get 26 unique words when in reality there should be at least 200. Can anyone spot something wrong with my code?
def countUniqueWords():
    words = open('phrases.txt')
    numberofUniqueWords = {}
    for word in words:
         try:
             numberofUniqueWords[word] += 1
         except KeyError:
             numberofUniqueWords[word] = 1
    print(len(numberofUniqueWords))

print(countUniqueWords())

A: You are iterating through the charters in the file not the words. You need to make the file a list of words with words = open('phrases.txt').read().split() Also you should make sure to remove any punctuation.

A: 1) Use a set instead of a dictionary
2) words is just a string, you need to use .split() in order to get the words in the string.
def countUniqueWords():
    words = open('phrases.txt')
    uniqueWords = set(words.split())
    return len(uniqueWords)

print(countUniqueWords())


text:
Q: Keyboard is hid when alertview show up on iOS 8.3 The keyboard is hid when UIAlertView show on iOS 8.3 ,and it will show after the alertView dismiss.
So there is a problem:
A view -> B view(has UITextField) -> keyboard(custom) show -> alertView show(keyboard hide) -> user clicke -> B view dismiss -> A view & keyboard show(this keyboard belongs to B view, and it crash when I click).
How to solve this problem?

A: I found two solutions.
Like Gajendra said : hide keyboard by adding some logic like [self.view endEditing = YES];
We can also use this delegate method to handle alertview click

*

*(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex


text:
Q: Generic type constraint for numerical type only I'm trying to figure out how to implement a type constraint for a generic class (in Swift) that will limit the generic types to numeric types only. For instance Double, Int, etc., but not string. Thanks for any help.

A: You can specify type constraints (using both classes and protocols) for a generic class (same syntax applies to functions) using angle brackets:
class Foo<T: Equatable, U: Comparable> { }

To specify more than one requirement on a single type, use a where clause:
class Foo<T: UIViewController where T: UITableViewDataSource, T: UITextFieldDelegate> { }

However, it doesn't look like you can specify optional requirements in a generic parameter clause, so one possible solution is to create a protocol that all the numeric types implement via extensions and then constrain your class on that requirement:
protocol Numeric { }

extension Float: Numeric {}
extension Double: Numeric {}
extension Int: Numeric {}

class NumberCruncher<C1: Numeric> {
    func echo(num: C1)-> C1 {
        return num
    }
}

NumberCruncher<Int>().echo(42)
NumberCruncher<Float>().echo(3.14)

A: Strideable is the smallest standard protocol that every standard number type conforms to, but it also has a few more types conforming to it.
http://swiftdoc.org/protocol/Strideable/hierarchy/
Or you can use IntegerType and FloatingPointType.

A: As talked about here and here, the Numeric protocol is now part of Swift 4, so - for example - you can overload + for numeric tuples as follows:
func +<T : Numeric> (x: (T, T), y: (T, T)) -> (T, T) {
     return (x.0 + y.0, x.1 + y.1)
}

(1,1) + (2,3) // (3, 4) : (Int, Int)
(1.25, 1.5) + (2.5, 2.25) // (3.75, 3.75) : (Double, Double)


text:
Q: Should I avoid using "!" in if statement in Java? Our team's Java Coding Guideline says:

Avoid using "!" in if statement as much as possible.

I have asked other colleagues, but no one gave me clear ideas why, because the guideline was created a long time ago and the author might have left our company.
Do you have any idea?

A: The rule is likely an adaptation from Robert Martin's Clean Code, page 302:

Negatives are just a bit harder to understand than positives.  So, when possible, conditionals should be expressed as positives.  For example:
if(buffer.shouldCompact())

is preferable to
if(!buffer.shouldNotCompact())

As an example, suppose you're creating a validator that requires two things to be false for the entity to be valid:

*

*The entity must not have been created within the last 12 hours, and

*The entity's bank account total sum must not exceed $50,000.

Naturally the idea would be to write two methods for this:
boolean isCreatedWithinLastTwelveHours(BankAccount account)
boolean hasMoreThanTotalSumCap(BankAccount account)

...at which point, you then invoke these as:
boolean newAccount = isCreatedWithinTheLastTwelveHours(account);
boolean highEndAccount = hasMoreThanTotalSumCap(account);

if(!newAccount && !highEndAccount) { // ... other logic

// The more astute would use DeMorgan's law in an effort to make this more readable

if(!(newAccount || highEndAccount)) { // other logic

Well...wouldn't it be nicer if you just said what they weren't instead?
boolean isNotCreatedWithinLastTwelveHours(BankAccount account)
boolean hasLessThanTotalSumCap(BankAccount account)

That'd make the expression a bit more concise:
if(notNewAccount && notHighEndAccount) { // .. carry on!

A: With the information provided, this calls for some speculation.  One possible reason is that the intent was not for an if-statement by itself but for an if-else statement.  In that case, I can see where you might say that you should reverse the cases so that you don't have the extra operation of the negation.  Instead of
if (! boolVar) {
  // Something
} else {
  // Something else
}

you might prefer
if (boolVar) {
  // Something else
} else {
  // Something
}

Whether this is worth it or not is probably more a matter of taste and standardization than anything else.

A: Of course "!" can be used when you like. There is no "unless" in java and you have no other choices in some conditions.

A: Looks like yet-another-useless-rule. Generally speaking, there are no absolute terms in this scenario, true that if you are in a if-else clause then possibly it is better to write
if(myCondition) {
    doThis()
} else {
    doSomethingElse()
}

Instead of
if(!myCondition) {
   doSomethingElse()
} else {
   doThis()
}

However, that said, in some scenarios is actually quite ok to use the negation operator, particularly if no else clause is provided, example
if (!tokenDoesCompute()) {
   throw InvalidTockenException("Whatever")
}

And actually in that scenario, using "!" makes quite a bit of sense for me.
Finally, if no one can really explain WHY the rule is there, maybe it is time to remove it, the only good reason I could find for it would be to provide consistency regarding the code style.

A: Okay, I answer my own question.
As other say, maybe this is written for the readability.
In The Art of Readable Code (p. 72) says:

Prefer dealing with the positive case first instead of the negative-e.g., if(debug) instead of if(!debug)

I found below post as well:

*

*Readable Code - Remove Checking null
bool func(String name)
{
    if ( (name != null) && (name.equals("true") ) {
        //...
    } else {
        //...
    }
}

bool func(String name)
{
    if ( "true".equals(name) ) {
       //...
    } else {
        //...
    }
}

A: Ofcourse you can use the negation operator ! whenever you like.
However, if you have a situation where you have to write some actions in both if and else block then the following is more readable :
if(status){
//do something
}
else{
//do something else
}

than
if(!status){
//do something
}
else{
//do something else
}

But if you have situation where you only need to perform certain actions based on just one condition, i.e. if you have only an if block & no else block, then it is reasonably fine to use ! in if

A: I haven't seen anyone else suggest this, which is probably because they hate it as much as I do, but I'm showing it for completeness.
// Using not operator (preferred)
if (! someTest) { ... }

// Using compact not operator (kind of hides it)
if (!someTest) { ... }

// Comparing to false (ok, explicitly states what you want)
if (someTest == false) { ... }

// Comparing to true (a bit obscure)
if (someTest != true) { ... }

They all do the same, but please keep using !, just make sure you add a space after it, so it's easier to see.


text:
Q: HABTM relationship with an array I am a beginner with Rails 3 programming and I have one problem with creating the right model.
Let's say there is an application to manage the bibliography of a book, that is manage the mapping for each chapter of the list of referenced articles. So for the article part
I could have something like:
create_table :articles do |t|
  t.string :title
  t.text   :content
  ...

On the bibliography side I would like to have a model like
create_table :bibliographies do |t|
  t.string :chapter
  t.text   :ref
  ...

where ref is actually an array of references to articles, so it would be managed via serialize ActiveRecord method.
Ok, so now the issue is about how to make so that the elements of the array @bibliography.ref are references (in Ruby sense) to several article_id.
How do I model such a relationship, and what Rails 3 code should I write to express that?
The thing that confuses me is that a single field of a single instance of @bibliography would reference to many @article.id .
Thanks in advance

A: If you really want to store relationships like that, then I would define a method in Bibliography model, something like this
(Assuming that ref is an array of ids)
def articles
  Article.where(:id => self.ref)
end

I would store the relationship differently though. Add a third table/model articles_bibliographies with article_id and bibliography_id fields. Then you can use the has_many :through association which is built into ActiveRecord.
in your Bibliography class you would then have something like:
has_many :articles_bibliographies
has_many :articles, :through => :articles_bibliographies

then you can just do @bibliography.articles
Read more here http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

A: Following egze's suggestion, I found a way to solve my problem (without using arrays!).
So, I create a has_many-through relationship, but as I want to save the order for the
articles how they are mentioned in the bibliography, the table articles_bibliographies
has also a order_nr field, where I store which is the first, second, etc. article mentioned
in the bibliography:
create_table :articles_bibliographies do |t|
   t.references  :article
   t.references  :bibliography
   t.integer     :order_nr

This way I can retrieve and show an ordered list of elements with:
@bibliography.articles.order("order_nr ASC")


text:
Q: Eclipselink not saving update to a field inside an Entity I am using Eclipselink and I have a JPA Entity that is basically a byte array of gzipped data stored as a blob in the database. However, this data is wrapped in a class that manages the byte array and can decode it correctly (GzipByteArray). I used the @Converter and @Convert annotations to convert from the internal byte[] array in the database to my GzipByteArray wrapper class. The Entity actually stores the GzipByteArray class as the variable type. That all works OK.
However, when I want to append some text to the GzipByteArray, I call a method on it to append the text. Eclipselink is not detecting the change to this parameter of the parent Entity class.
I put a .equals() and .hashCode() method on my GzipByteArray to make sure it takes into account the change in the internal byte[] array. That doesn't help. Based on my logging statements, .equals() is not even being called by Eclipselink.
The only way I can get the changes to be detected is to create a new instance of GzipByteArray and use the setter to modify it.
I assume that Eclipselink is using the default DeferredChangeDetectionPolicy. How does this work? I even downloaded the source of Eclipselink, but I can't figure it out. Can I manually force this field to be marked as "dirty" somehow? Does the instance ID of the object have to change in order for Eclipselink to detect it?

A: In your converter you need to return true for isMutable(), this will ensure EclipseLink uses deferred change detection.  You could also add @Mutable to your mapping.
If possible, it is more efficient if you call the set method when you change the value instead of using mutable.  This will allow EclipseLink to use attribute change tracking, instead of having to compare the entire byte-array for changes on every commit.