text:
Q: Imported Aperture library into Photos, "Show Referenced File in Finder" does nothing I just finished importing my Aperture library into Photos using the official import process. My Aperture library used referenced masters on an external drive, and I had my external drive connected during the import process.
With my external drive still connected, nothing happens when I two-finger click on a thumbnail and choose "Show Referenced File in Finder." Any ideas?

A: I had a similar issue, which seemed like it had something to do with access permissions. Try the following:

*

*Pick a random photo for which "Show Referenced File in Finder" does nothing.

*Select it and hit space to view it.

*Photos will pop up a dialog saying that it can't access some files outside the Photos library and will ask you to select a certain folder (for me it was the root of all my referenced files).

After I'd done that, "Show Referenced File in Finder" now works for all my images.


text:
Q: maven 2 plugins (less and handlebars) I would like to add my handlebars and less pre-compiling into a Maven build. All the plugins i can find are for Maven 3, however I am stuck using Maven 2.0.11.
I have found handlebars-maven-plugin and lesscss-maven-plugin but both choke the build.
I am currently doing the precompiling in gulp tasks, but we cannot put node.js on the server to allow me to run these either!
Any help would be greatly appreciated.

A: For anyone in the same boat as me, stuck with out-dated versions, I have managed to find a solution.
For the handlebars i found this solution, Precompiling handlerbars tempates with Rhino.js. I had to tweak the rhino-handlebars-compiler.js to take into account the extension change for handlebars, but that was it.
With regards to LESS, i discovered that version 1.3.0 of lesscss-maven-plugin is compatible with maven2 and jdk 1.5

A: To compile Less files, you can use biz.gabrys.maven.plugins:lesscss-maven-plugin, which is compatible with:

*

*Less 1.7.5

*Maven 2.0.11

*JDK 1.5

redpajama_set_name: RedPajamaStackExchange


text:
Q: Export and Import FIle Content I have 2 class that are:

*

*Rep (for repositories)

*Files

Repositories have a collection of repositories and files. Files have a list<string> of lines.
I'm currently parsing repositories to construct my tree of folders and files (and file content).
I'm using binary serialization to export the all thing, but if files content is loaded I'm running out of memory.
What I want to achieve, is loading thousands of file to do quick search of string in it. I don't know what way would be the best in this case. I want to avoid that long moment of loading and "ReadAllLines()" on each file.
Edit
I do have a lot of files to export, each file could contains many lines. I'm looking for a way to load it once a day. And loading it every time I use my searching application that needs to be as fast as possible. I was thinking about exporting binary files of my Repositories/Files/lines. And then loading it quickly every time I need :) Maybe I'm not thinking right, any ideas?
My code so far
[Serializable]
public class PlkFichier
{
    public List<PlkLigne> PNVLignes = new List<PlkLigne>();
    public List<string> PNVStrLignes = new List<string>();

    private string _PNVNom;
    private string _PNVRepertoire;
    private string _PNVExetension;
    public bool PNVChargerLignes;

    public string PNVRepertoire
    {
        get { return _PNVRepertoire; }
        set { _PNVRepertoire = value; }
    }
    public string PNVNom
    {
        get { return _PNVNom; }
        set { _PNVNom = value; }
    }
    public string PNVExtension
    {
        get { return _PNVExetension; }
        set { _PNVExetension = value; }
    }
    public PlkFichier()
    {

    }

    public PlkFichier(string pPath) : this(pPath, false) { }

    public PlkFichier(string pPath, bool pLoadLignesFile)
    {
        PNVNom = Path.GetFileNameWithoutExtension(pPath);
        PNVRepertoire = Path.GetFullPath(pPath);
        PNVExtension = Path.GetExtension(pPath);
        PNVChargerLignes = pLoadLignesFile;

        if (PNVChargerLignes) this.PNVLoadLignesFile();
    }

    public void PNVLoadLignesFile()
    {
        string[] LignesLues = File.ReadAllLines(PNVRepertoire);
        PNVStrLignes = LignesLues.ToList();
        foreach (string vLignes in LignesLues)
        {
            PNVLignes.Add(new PlkLigne(vLignes));
        }
    }
}

[Serializable]
public class PlkRepertoire
{
    public List<PlkRepertoire> PNVRepertoires = new List<PlkRepertoire>();
    public List<PlkFichier> PNVFichiers = new List<PlkFichier>();
    public string PNVNom;
    public bool PNVChargerArborescenceRep;
    public bool PNVChargerListeFichiers;
    public bool PNVChargerLignesFichiers;
    private List<PlkRepertoire> RemoveList = new List<PlkRepertoire>();
    private List<PlkFichier> NonSourceFiles = new List<PlkFichier>();
    private bool _NonSourceFilesVisible;

    public PlkRepertoire(string pNom) : this(pNom,false) {}

    public PlkRepertoire(string pNom, bool pLoadSubDirectory) : this(pNom, pLoadSubDirectory, false) { }

    public PlkRepertoire(string pNom, bool pLoadSubDirectory, bool pLoadListeFiles) : this(pNom, pLoadSubDirectory, pLoadListeFiles, false) { }

    public PlkRepertoire()
    {
    }

    public PlkRepertoire(string pNom, bool pLoadSubDirectory, bool pLoadListeFiles, bool pLoadLignesFichiers)
    {
        PNVNom = pNom;
        PNVChargerListeFichiers = pLoadListeFiles;
        PNVChargerArborescenceRep = pLoadSubDirectory;
        PNVChargerLignesFichiers = pLoadLignesFichiers;
        PNVLoadFiles(PNVNom);
    }

    public void PNVLoadFiles()
    {
        //Console.WriteLine("pnvLoadFies: " + PNVNom  );
        if (Directory.Exists(PNVNom))
        {
            if (PNVChargerListeFichiers == true)
            {
            string[] fileEntries = Directory.GetFiles(PNVNom);
            foreach (string fileName in fileEntries)
            {
                PNVAddFichier(fileName);
            }
            }
            if (PNVChargerArborescenceRep == true)
            {
                string[] subdirectoryEntries = Directory.GetDirectories(PNVNom);
                foreach (string subdirectory in subdirectoryEntries)
                {
                    PNVAddRepertoire(subdirectory);
                }
            }
        }

    }

    public bool IsEmpty()
    {
        return (this.PNVFichiers.Count == 0 && this.PNVRepertoires.Count == 0);
    }

    public bool NonSourceFilesVisible
    {
        get
        {
            return _NonSourceFilesVisible;
        }
        set
        {
                _NonSourceFilesVisible = value;
                this.PNVClearNonSourceFiles();
        }
    }

    /*
    public void ToXml(XmlWriter writer)
    {
        this.ToXml(writer,this.PNVRepertoires);
    }
    public void ToXml(XmlWriter writer, List<PlkRepertoire> ListeReps)
    {
        foreach (PlkRepertoire rep in ListeReps)
        {
            writer.WriteStartElement("Repertoire");
            writer.WriteElementString("Nom", rep.PNVNom);
            ToXml(writer, rep.PNVRepertoires);
            foreach (PlkFichier file in rep.PNVFichiers)
            {
                writer.WriteStartElement("Fichier");
                writer.WriteElementString("NomFichier", file.PNVNom);
                writer.WriteElementString("ExtFichier", file.PNVExtension);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }
    }
    */

    public void PNVClearNonSourceFiles()
    {
        foreach (PlkRepertoire SousRep in this.PNVRepertoires)
        {
            SousRep.PNVClearNonSourceFiles();
        }
        foreach (PlkFichier FileASuppr in NonSourceFiles)
        {
            if (NonSourceFilesVisible)
            {
                if (PNVFichiers.Contains(FileASuppr) != true) PNVFichiers.Add(FileASuppr);
            }
            else
            {
                PNVFichiers.Remove(FileASuppr);
            }
        }
    }

    public bool PNVClearEmptyFolders ()
    {
        this.RemoveList.Clear();
        foreach (PlkRepertoire SousRep in this.PNVRepertoires)
        {
            if (SousRep.PNVClearEmptyFolders()) RemoveList.Add(SousRep);
        }
        foreach (PlkRepertoire RepASuppr in RemoveList)
        {
            PNVRepertoires.Remove(RepASuppr);
        }
        return this.IsEmpty();
    }

    public void PNVLoadFiles(string pRepertoire)
    {
        //if (pRepertoire.Contains(".xml")) PNVLoadFromXml(pRepertoire);
        PNVNom = pRepertoire;
        this.PNVLoadFiles();
    }

    public void PNVToXml(string pathAndName)
    {
        XmlSerializer xs = new XmlSerializer(typeof(PlkRepertoire));
        TextWriter tw = new StreamWriter(pathAndName);
        xs.Serialize(tw, this);
    }

    public void PNVToBinary(string pathAndName)
    {
        using (Stream stream = File.Open(pathAndName, FileMode.Create))
        {
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            binaryFormatter.Serialize(stream, this);
            stream.Close();
        }
    }

    public static PlkRepertoire PNVFromBinary (string pathandname)
    {
        using (Stream stream = File.Open(pathandname, FileMode.Open))
        {
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            return (PlkRepertoire)binaryFormatter.Deserialize(stream);
        }
    }

    public static PlkRepertoire PNVLoadFromXml(string pXml)
    {
        XmlSerializer xs = new XmlSerializer(typeof(PlkRepertoire));
        using (var sr = new StreamReader(pXml))
        {
            return  (PlkRepertoire)xs.Deserialize(sr);
        }
    }

    public void PNVAddRepertoire(string path)
    {
        this.PNVRepertoires.Add(new PlkRepertoire(path, PNVChargerArborescenceRep, PNVChargerListeFichiers, PNVChargerLignesFichiers));
    }

    // Insert logic for processing found files here.
    protected void PNVAddFichier(string path)
    {
        PlkFichier vFile = new PlkFichier(path, PNVChargerLignesFichiers);
        if (vFile.PNVExtension != ".p" && vFile.PNVExtension != ".i" && vFile.PNVExtension != ".cls" && vFile.PNVExtension != ".lab" && vFile.PNVExtension != ".w" && vFile.PNVExtension != ".lep") this.NonSourceFiles.Add(vFile);
        this.PNVFichiers.Add(vFile);
    }

}

[Serializable]
public class PlkLigne
{
    public bool PNVIsEmpty;
    public string PNVLigne;

    public PlkLigne()
    {

    }

    public PlkLigne(string pCOntenu)
    {
        PNVLigne = pCOntenu;
        if (PNVLigne == "") PNVIsEmpty = true;
        else PNVIsEmpty = false;
    }
}

A: I would take advantage of Lazy loading your lines.  That will likely speed your calls up significantly and reduce memory.
private List<string> _pnvStrLignes;
public List<string> PNVStrLignes => _pnvStrLignes ?? (_pnvStrLignes = GetLignes());

private List<string> GetLignes()
{
    return File.ReadAllLines(PNVRepertoire).ToList();
}

So you're not having the constructor of your class read the entire contents of the file, rather only when you intend to use the property (which will hopefully be one at a time)


text:
Q: Javascript `?.` operator: why is `not defined` not treated as `undefined`? Assuming w has not been previously defined, the following JS code gives ReferenceError: w is not defined:
w?.y;

whereas this code simply returns undefined:
let w; w?.y;

Why does the ?. operator not treat not defined as undefined?

A: This is mentioned in the documentation

Optional chaining cannot be used on a non-declared root object, but can be used with an undefined root object.

which means you have to declare the root object, in this case, it's w

A: The difference is between trying to access a (potentially) non-existent variable vs a (potentially) non-existent property.
From MDN:
On reference errors:

The ReferenceError object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced.

This is the case in your first example:

const value = w?.y;
//            ^ ReferenceError occurs here
console.log(value);

On optional chaining (?.):

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.

This is the case in your second example:

let w;
const value = w?.y;
//            ^ Reference exists (but it is undefined)
console.log(value);


text:
Q: How to define function that variable is optional? I want to define some function that I can do something for the troubleshooting purpose.
kk[x_, L_] := Module[{x1, x2},
x1 = "x is too big"; x2 = "x is too small" ;
If[L == 1, If[x>1,Print[x1],Print[x2]]];
Print[x];
]

If I plug in L value in the function, then I will get the message. However, if I do not plug in L, then This function will not work because I did not define L.
I want to make this function work no matter there is L or not. So I want to make L optional. Is it possible for me to define such thing in Mathamtica?


text:
Q: React-Native: conditional styling of child component I've got an array full of numbers 1, 2, 3. I'm trying to map over it for each number to render a Square component. This worked fine. Now I want to conditionally style the Square component depending on the value (1, 2 or 3). I've got a syntax error on the line with 'switch' (Unexpected token) that I can't seem to spot the reason for.
class MainMaze extends Component {

  generateMaze() {
    const { tiles, cols, rows } = this.props.grid;
    return (
      tiles.map((sq, i) =>
        switch (sq) {
          case 3:
            return <Square style={{ backgroundColor: 'red' }}>{sq}</Square>;
          case 2:
            return <Square style={{ backgroundColor: 'blue' }}>{sq}</Square>;
          default:
            return <Square style={{ backgroundColor: 'green' }}>{sq}</Square>;
        }
    );
  }
  render() {
    const { grid, position, status } = this.props;

    return (
      <View>
        <CardSection>
          <Text>{grid.cols}</Text>
        </CardSection>
        <CardSection>
          {this.generateMaze()}
        </CardSection>
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    status: state.status,
    position: state.position,
    grid: state.grid
  };
};

export default connect(mapStateToProps)(MainMaze);

the Square component:
import React from 'react';
import { View, Text } from 'react-native';

const Square = (props) => {
  return (
    <View style={[styles.containerStyle, props.style]}>
      <Text>
        {props.children}
      </Text>
    </View>
  );
};

const styles = {
  containerStyle: {
    borderWidth: 1,
    borderColor: '#ddd',
    elevation: 1,
    alignItems: 'center',
    justifyContent: 'center',
    margin: 0,
    height: 30,
    width: 30
  }
};

export { Square };

A: Here is the correct syntax of an arrow expression function with multiple statements (taken from mozilla docs):
(param1, param2, …, paramN) => { statements }
ie, you should wrap the switch block with {...}:
generateMaze() {
    const { tiles, cols, rows } = this.props.grid;
    return (
      tiles.map((sq, i) => {
        switch (sq) {
          case 3:
            return <Square style={{ backgroundColor: 'red' }}>{sq}</Square>;
          case 2:
            return <Square style={{ backgroundColor: 'blue' }}>{sq}</Square>;
          default:
            return <Square style={{ backgroundColor: 'green' }}>{sq}</Square>;
        }
      }
  ))
  }


text:
Q: Uncaught TypeError: $(...).typeahead is not a function when using typeahead.js I'm trying to do a basic example with typeahead.js
I have included files in the following order.
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

(application js contains jquery)
Following is my initialisation code.
$('#custom-templates .typeahead').typeahead(null, {
  name: 'best-pictures',
  display: 'value',
  source: '/search',
  templates: {
    empty: [
      '
',
        'unable to find any Best Picture winners that match the current query',
      '
'
    ].join('\n'),
    suggestion: function(data) {
    return '
' + data.name + ' – ' + data.id + '
';
}
  }
});

and the markup is

            <input class="typeahead" type="text" placeholder="Oscar winners for Best Picture">

But in the console i'm getting the following error.
Uncaught TypeError: $(...).typeahead is not a function when using typeahead.js and there are no other errors too.
What am i doing wrong ?
typeahead.js has also been loaded properly when i check the page source.


text:
Q: Sieve of Eratosthenes variant I want to do a sieve that doesn't take advantage of the obvious math hacks. I want to brute force it. My algorithm is conceived with the notion that the sieve does a lot of checking for what are not prime numbers and just returning the result of the operations to check those rather than to figure out what are prime numbers. I think some Carmichael Numbers prove it to be invalid for something very large. I could be wrong on that. I went on to check numbers from a range, and followed the basic algorithm given from Wikipedia.
def primes(n)
  nums = (2..n)
  not_prime = []
  primes = []
  nums.to_a.each_with_index do |it, idx|
      primes << it unless not_prime.include?(it)
      p primes.last
      p nums.step(primes.last).to_a
      nums.step(primes.last).each_with_index do |num, idx|
        next if idx == 0
        not_prime << num
      end
  end

  primes
end

When my range does the line:
nums.step(primes.last).each_with_index

for numbers other than the first one (2), I get an off-by-x error (compounding on the list I believe). For example, all the non prime two multiples are found, but for the multiples of three, the step on the range returns 2, 5, 8, 11, etc., which are off by one.
I'm trying to figure out a solution using Range objects or converting to an Array, but I like the conciseness of my (wrong) solution. Anyone think they can help me solve this?
EDIT:
I fixed it! The solution was creating an entirely new range to iterate over rather than taking the original range. See below. Shout out to Jörg W Mittag for the inspiration to just create a new range instead of trying to fiddle with the original immutable object which is what I was trying to do. Square peg in round hole sounds so much better sometimes.
def primes(n)
  nums = (2..n)
  not_prime = []
  primes = []
  nums.to_a.each_with_index do |it, idx|
      next if not_prime.include?(it)
      primes << it
      ((primes.last)..n).step(primes.last).each_with_index do |num, idx|
        next if idx == 0 || num == primes.last
        not_prime << num
      end
  end

  primes
end

A: def primes(n)
  nums = (2..n)
  not_prime = []
  primes = []
  nums.to_a.each_with_index do |it, idx|
      next if not_prime.include?(it)
      primes << it
      ((primes.last)..n).step(primes.last).each_with_index do |num, idx|
        next if idx == 0 || num == primes.last
        not_prime << num
      end
  end

  primes
end


text:
Q: Add Hours, minutes and seconds to Spark dataframe Is there a Spark SQL function to add Hours, Minutes and Seconds to existing timestamp column.
For example:
+----------+-------------------+-------------------+
|        dt|             txn_dt|          txn_dt_tm|
+----------+-------------------+-------------------+
|2008-08-15|2008-08-15 00:00:00|2008-08-15 05:00:00|
+----------+-------------------+-------------------+

I need add 23 hours 59 minutes and 59 seconds to txn_dt column.
Output:
+----------+-------------------+-------------------+
|        dt|             txn_dt|          txn_dt_tm|
+----------+-------------------+-------------------+
|2008-08-15|2008-08-15 23:59:59|2008-08-15 05:00:00|
+----------+-------------------+-------------------+

Update:
I was able to get it using INTERVAL, but not sure this is efficient way of doing it.
df.select((F.col("txn_dt") + F.expr("INTERVAL 23 HOURS") + F.expr("INTERVAL 59 MINUTES") + F.expr("INTERVAL 59 SECONDS")).alias("txn_dt_tm"))

A: You need to customize the udf function, such as:
import org.apache.spark.sql.functions._
val timeUdf = udf{(time: java.sql.Timestamp) => new java.sql.Timestamp(time.getTime + 24*60*60*1000 - 1000)}
df.withColumn("dt", timeUdf(df("dt"))).show()

and the result:
+--------------------+---+
|                dt| id|
+--------------------+---+
|2008-08-15 23:59:...|  1|
+--------------------+---+

i hope this will help you.


text:
Q: Remove empty/newline from an output file How do I remove empty lines from an output file so I can use diff to compare a reference file to my output file?
I found a post about removing new lines such as:
tr '\n' ' ' < input_filename > out

So I tried something like
tr '\n\n' '\n' < input_filename > out

But it does seems to do anything.
How do I go from
1 <somecode>
2 <somecode>
3
4 <somecode>
5 <somecode>
6 <somecode>
7 <somecode>
8
9 <somecode>

to
1 <somecode>
2 <somecode>
3 <somecode>
4 <somecode>
5 <somecode>
6 <somecode>
7 <somecode>
8
9

Also the reference output is not
\n\n

but rather
\n<sometabs>\n

Which makes
tr -s '\n' < input > output

not stripping all the consecutive newlines.

A: You can use sed command:
 cat input_filename | sed '/^$/d' > out

That delete all line that match expression ^$ (that means that are empty)


text:
Q: flutter windows issue: When I go to select image from desktop gallery Please help!
Unhandled Exception: MissingPluginException(No implementation found for method pickImage on channel plugins.flutter.io/image_picker)

A: Maybe your plugin is not supporting the windows.

A: To use that plugin on Windows, you need to add the image_picker_windows package. It's still in early stages, so isn't included by default with image_picker.


text:
Q: Errors running builder 'AspectJ Builder' on project I am working on SpringSource Tool Suite with Spring Roo. Everything was working well up until  few days ago after I installed GWT plugin (I think this might be a problem, I am not sure ).
Every time I code something and press Save (ctrl+s), it shows a dialog box showing
    Errors occurred during the build.
Errors running builder 'AspectJ Builder' on project xyz123
org/eclipse/ajdt/core/builder/AJBuilder$SourceFilesChangedVisitor

eclipse.buildId=2.6.0.201103161000-RELEASE
java.version=1.6.0_24
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments:  -product com.springsource.sts.ide
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product com.springsource.sts.ide

Error
Wed Apr 27 14:33:03 EDT 2011
Problems occurred when invoking code from plug-in: "org.eclipse.core.resources".

java.lang.ClassFormatError: org/eclipse/ajdt/core/builder/AJBuilder$SourceFilesChangedVisitor
at org.eclipse.ajdt.core.builder.AJBuilder.sourceFilesChanged(AJBuilder.java:1707)
at org.eclipse.ajdt.core.builder.AJBuilder.hasChangesAndMark(AJBuilder.java:1639)
at org.eclipse.ajdt.core.builder.AJBuilder.build(AJBuilder.java:185)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:629)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:172)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:203)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:255)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:258)
at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:311)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:343)
at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:144)
at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:242)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

Can anyone please help me out in solving this?
Thanks,

A: The ClassFormatError occurs when a class file is malformed or corrupted.  See here:
http://download.oracle.com/javase/6/docs/api/java/lang/ClassFormatError.html
It could very well be that your installation of AJDT was somehow corrupted.  I would recommend trying one or all of the following:

*

*Uninstall the Google plugin.  Does the problem go away?

*Upgrade to the latest dev snapshot of AJDT.  Update site is here:  http://download.eclipse.org/tools/ajdt/36/dev/update  After upgrading does your error go away?

*As a last resort, try reinstalling STS.  You can leave your workspace in tact, just unzip STS again.


text:
Q: Returning a value in Java How do I write a method which returns a primitive datatype value when inside the method it has an if statement which returns a different datatype depending on the result?
int minimum = 5;
int students = 4;
int studentGrades = 100;

public double getAverage(){
    if(students >= minimum){
        return studentGrades / students;
    }
    else {
        System.out.println(null, "Sorry, you don't have enough students.");
        return false;
    }
}

A: You can't really return two different primitive types from the same method. With reference types you could return Object, that that isn't a good idea anyway.
Your return false looks like an error condition, so you might think about throwing an exception here:
public double getAverage(){
    if(students >= minimum){
        return studentGrades / students;
    }
    else {
       throw new IllegalStateException("not enough students");
    }
}

A: In the example you've given, you should throw an exception - the state of the object isn't valid for the method call, basically. You might want to use IllegalStateException for this, or choose a different type of exception. (That exception extends RuntimeException, so it isn't a checked exception. That may or may not appropriate for your real use case.)
(As an aside, the division in your sample code won't do what you want either - you should cast one of the operands to double if you want it to execute floating point division instead of integer division.)

A: public Object getAverage()
but then you should check the return class

A: You can as example return a composite object that contains the score and a flag for success.
Or in the above version you could return Double.NaN to indicate the failure. Or as others have suggested throw an Exception in case of failure.

A: I'm no Java expert but I think the good practice here is to throw an exception if you have less than the required amount of students. If you must return 2 completely different values I suggest you encapsulate them in a class of your own.

A: A java method can have only one return type. So you should try some other approche in handling this situation. As others above have pointed out you could throw a exception. Or you could use a nullable data type, and return null when this special condition is true. But this is ugly and is not recommended.


text:
Q: undefined reference to c++ static field Look at this very basic c++ class:
class MyClass {
 public:
  static std::map<int, std::string> test;

  void method1()
  {
     std::cout << test[1] << std::endl;
  }
};

int main()
{
    MyClass::test[1]="test";

    return 0;
}

As you can see, this very basic class contains a static field.
But when i am trying to access it, i get this compiler error:
undefined reference to `MyClass::test[abi:cxx11]'

In order to make it work, i have tried to create a static method and declare my static field inside this method.
It works, but it looks ugly.
I want to understand why my first code does not work and why this second code works...
class MyClass {
 public:
  static std::map<int, std::string>  get_test()
  {
    static std::map<int, std::string> test;
    return test;
  }

  void method1()
  {
     std::cout << get_test()[1] << std::endl;
  }
};

int main()
{
    MyClass::get_test()[1]="test";

    return 0;
}

Thanks


text:
Q: compare client certificates in go My use case looks like I know the public certificates of my clients and only want to allow them. I have a go server based on gin and a TLS configuration in which I have assigned a method to the property "VerifyPeerCertificate".
The function looks like
func customVerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {

if len(verifiedChains) < 1 {
    return errors.New("Verified certificate chains is empty.")
}
if len(verifiedChains[0]) < 1 {
    return errors.New("No certificates in certificate chains.")
}
if len(verifiedChains[0][0].Subject.CommonName) < 1 {
    return errors.New("Common name can not be empty.")
}

fmt.Println(verifiedChains[0][0].Raw)

publicKeyDer, _ := x509.MarshalPKIXPublicKey(verifiedChains[0][0].PublicKey)

publicKeyBlock := pem.Block{
    Type:  "CERTIFICATE",
    Bytes: publicKeyDer,
}
publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))
}

The problem is, however, that the string in the variable "publicKeyPem" does not look like the client public certificate I used to send the request to the server, it's also shorter in length.

A: A certificate is more than its public key. The entire x509.Certificate object represents the certificate presented by the client, the public key field is only the actual value of the public key.
If you want to compare certificates for strict equality, you should use the rawCerts [][]byte argument passed to your callback. This is mentioned in the tls.Config comments for VerifyPeerCertificate:
    VerifyPeerCertificate, if not nil, is called after normal
    certificate verification by either a TLS client or server. It
    receives the raw ASN.1 certificates provided by the peer and also
    any verified chains that normal processing found. If it returns a
    non-nil error, the handshake is aborted and that error results.

A: Thanks to Marc, I know that I used the wrong variable. To convert the certificate as a string, as used by the client, use the following code
publicKeyBlock := pem.Block{
  Type:  "CERTIFICATE",
  Bytes: rawCerts[0],
}
publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))


text:
Q: sortable divs created on the fly with jquery ui I'm trying to enable sortable feature on div's that are being created on the fly. I could not reproduce the example from jquery UI. Am I missing something?
Here's the JS Fiddle:
<div id="sortable">
</div>

<input type='button' id='btn' value='add'/>

$(function(){
    var c = 1;
    $("#btn").click(function(){

        var d = $("<div/>");
        d.html(c++);
        d.addClass('d');

        $("#sortable").append(d);
    });

    $( "#sortable" ).sortable();
    $( "#sortable" ).disableSelection();
});

#sortable{
    width: 300px;
    border:1px solid black;
    height:350px;
}

#sortable div
{
    margin: 0 3px 3px 3px;
    padding: 0.4em;
    padding-left: 1.5em;
    font-size: 1.4em;
    height: 18px;

}

/*#sortable li span {  }*/

.d{
     background-color:yellow;
     border:1px solid orange;
     height:20px;
}

http://jsfiddle.net/28jwu4y2/3/

A: You need to refresh sortable on every new addition of element ,
  $( "#selector" ).sortable( "refresh" );

See the working fiddle
P.S
Had you mis-configured the given fiddle? It has jquery-ui plug-in missing.


text:
Q: sql server datetime to float error I trying to calculate work shift from as flollows by comparing the datetime::float value with 1/3 as follows:
select t,
    cast( ( cast( cast(t as datetime) as float) - floor(cast( cast(t as datetime)  as float ) ) ) * 3.0 as decimal(38,30) ) x,
    floor(
        ( cast( cast(t as datetime) as float) - floor(cast( cast(t as datetime)  as float ) ) ) * 3.0
        ) x1
from ( values ('2019-01-01 00:00:00.0') , ('2019-01-01 07:59:59.0') ,
              ('2019-01-01 08:00:00.0') , ('2019-01-01 15:59:59.0') ,
              ('2019-01-01 16:00:00.0') , ('2019-01-01 23:59:59.0') ) test_sample(t)

But the result is confusing:
2019-01-01 00:00:00.0   0E-30   0.0
2019-01-01 07:59:59.0   0.999965277776937010000000000000    0.0
2019-01-01 08:00:00.0   1.000000000007276000000000000000    1.0
2019-01-01 15:59:59.0   1.999965277784212900000000000000    1.0
2019-01-01 16:00:00.0   1.999999999992724100000000000000    1.0 <----- inconsistency, expected 2.0
2019-01-01 23:59:59.0   2.999965277769661100000000000000    2.0

Why is 16:00:00  different from other values ?
What can I do to correctly work around this error (without comparing dates with lot of case whens ) ?


text:
Q: Java - IOException: Failed to open file: Access denied I've been developing some software in Java that'll be distributed for use with Windows or MacOS. I'm programming on an iMac at the moment (because of the Apple specific requirements). The following method drags a helpfile (.pdf) out of resources and copies it locally so that it can be displayed on the local machine.
private void mHelpActionPerformed(java.awt.event.ActionEvent evt) {
    String sourceFile = "resources/BRC2Help.pdf";
    String destFile = "brc2help.pdf";
    File f = new File (destFile);
    if (!f.exists()) {
            try {
            URL url = ClassLoader.getSystemResource(sourceFile) ;
            InputStream is = url.openStream();
            OutputStream os = new FileOutputStream(destFile);
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) != -1) {
                os.write(b, 0, length);
            }
            is.close();
            os.close();
            System.out.printf("loaded pdf file from resources: %d bytes\n",f.length());
            } catch (IOException ex) {System.out.printf("loadPDF: %s\n",ex);}
    } else {
        System.out.printf("%s exists: %d bytes\n",destFile,f.length());
    }

    try {
        if (f.exists()) {
                f.setReadable(true);
                if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().open(f);
            } else {
                System.out.println("Awt Desktop is not supported!");
            }
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this,
                String.format("%s\n",ex),
                "Helpfile Problem?",
                JOptionPane.ERROR_MESSAGE);
    }
}

This all works well enough on the Mac but gives an IOException on Windows 7:
java.io.IOException: Failed to open file:/C:/Program%20Files/BRC2/brc2help.pdf. Error message: Access denied.
Any idea what's going wrong here ? I've tried copying the .pdf file to other locations but the result is the same.

A: What is the working directory for the program when running on Windows?  It is possible that the user context running the program doesn't have rights to write to c:\Program Files\.
You did not specify the path to the file so my assumption is that c:\program files\brc\ is the working directory while running the program.  Since Windows Vista, you need to have full administration rights to be able to write to the Program Files and other directories.
Updated: 7/1/2012
Ok, I was able to stub out your program and run it as a main class and was able to have Desktop.getDesktop().open(f); open a PDF file on Windows 7.  I manually put a PDF file into the bin directory where Eclipse compiled my class file to.
I now need to try moving the class file and pdf into a subdirectory of c:\program files\ and see if I get the access denied exception you receive.
Hum, I was able to get Desktop.getDesktop().open(f); open the PDF file when it was in c:\program files\test\, see my output below:
C:\Program Files\test>"\Program Files (x86)\Java\jre7\bin\java.exe" MyTestClass
brc2help.pdf exists: 943123 bytes

C:\Program Files\test>dir
 Volume in drive C is OS
 Volume Serial Number is 2035-793F

 Directory of C:\Program Files\test

07/01/2012  10:25 PM    <DIR>          .
07/01/2012  10:25 PM    <DIR>          ..
07/01/2012  09:55 PM           943,123 BRC2Help.pdf
07/01/2012  09:57 PM             2,391 MyTestClass.class
               2 File(s)        945,514 bytes
               2 Dir(s)  567,516,254,208 bytes free

What JRE are you using?  Mine is java version "1.7.0_01" Java(TM) SE Runtime Environment (build 1.7.0_01-b08)

A: I agree with HeatfanJohn, it is definitely a permission issue.
Try compiling your java code as Administrator from the command line. Simply run cmd.exe as Administrator and then try compiling/running again.

A: I'm experiencing the same issue. Don't know the reason, but found a solution.
Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL \"" + StringEscapeUtils.escapeJava(f.getAbsolutePath()) + "\"");

you should use this only if the Desktop method fails, because this is only for Windows.


text:
Q: need to stop initv service before rpm removal/upgrade? Is there a need to stop a service before performing the removal or upgrade of the service's RPM package?
Normally, what the RPM package manager does when performing an upgrade is to install the new package first, then remove the old one. Excerpt:
Run %pre from "software-2".
Place files from "software-2".
Run %post from "software-2".
Run %preun from "software-1".
Delete files unique to "software-1".
Run %postun from "software-1".

In this case, shouldn't the service be stopped in %pre before installing the new package?
Here is a portion of my specfile for reference:
%preun
# do not run if this is an upgrade
if [ $1 -eq 0 ]; then
  /sbin/service myservice stop > /dev/null 2>&1
  /sbin/chkconfig --del /etc/init.d/myservice
fi
exit 0

%post
/sbin/chkconfig --add /etc/init.d/myservice
exit 0

What I have is what everyone seems to be doing and I do not understand why this would work in the case of an upgrade, without stopping the service first in %pre.

A: You've forgotten how UNIX filesystems work. As long as the link-loader leaves the object files open then the process will see the object files it was started with, as it holds a handle to the now-removed file. Once that handle is close()ed then the file is actually removed.  So it is safe to leave the daemon running whilst deleting and installing new object files.
Of course it's the old version of the daemon which is running, so 'safe' isn't so safe if the upgrade is to address a security issue. Which is why Debian's APT has a different policy and stop/starts daemons upon an upgrade.
You might find this specification on RPM scriptlets to be useful if you want to alter your package's policy.


text:
Q: Check how many columns contain value in each row of table I have these two tables in MSSQL database.
Student Preferences Tables
(This table has preferences columns numbered from 1-7 in database)
 ------------------------------------------------------------------------------
    Student Name |   Preference 1|  Preference 2 | Preference 3  |Group ID
    -----------------------------------------------------------------------
    Student A    |   Student G   |   Student F   |  Student G    |
    Student B    |   Student H   |   Student K   |  Student L    |
    Student C    |   Student I   |   Student A
    Student D    |   Student H   |   Student K
    Student E
    Student F
    Student G
    Student H
    Student I
    Student J
    Student K
    Student L
    -----------------------------------------------------------------------------

Groups Table
 |Group ID |
     ---------
    1
    2
    3
    ----------

I am creating groups of student based on preferences(preferred partners/team mates) entered by student.
Each group can have 5-8 students.Not all students will enter preferences.
To create a group i will check for the students who have entered 4-7 preferences and add them to a group.
For example, Student A has entered 4 preferences. Including student A now i have 5 students minimum number required for group. So, i would like to insert in "Groups table" and retrieve that number and insert in "Group ID" column for each student.
In cases if student has entered less than 4 preferences, i will have to create a new "group id" and assign to students but i also have to check that 5-8 students per group condition is not breached.
Can someone please guide me on this.
How to check for rows where more than 4 preference columns contain data(names)?
If students with more than 4 preferences exist, than how can i insert new record in Groups table(Group ID (auto-inc)) and retrieve it back to insert in Student Preference table.
How can i check 5-8 students condition is not breaching before inserting group id?
I am trying to find out how can these problems be solved (using c# or SQL) in easiest way?
I am writing application in C#.

A: That's a pretty horrible table design.  You'd probably be a lot better off with multiple tables.  One for student/group, and one for student/preference.  So:
T_STUDENTS
StudentID
GroupID

T_STUDENT_PREFERENCES
StudentID
Preference

Then you could simply query your preferences table:
select
studentid,
count(preference)
from
pref_table
group by
studentid
having count(preference) >4

Since you can't do that, you'll have to do something gnarly with case statements.
Something like
select
student,
case when preference1 <>''  then 1 else 0 end as pref1 //or something to check for empty/null,
case when preference2 <>'' then 1 else 0 end as pref2
....

then add up the 7 columns and filter for your desired number of preferences.


text:
Q: What could cause DAMAGE: after normal block error? I keep getting this error after my application is running for 2 days.
I've been told it's been some kind of buffer overflow, but is it the only option?
The app is written in C++ using Visual C++ 6.0.

A: The simplest way to reproduce this is something like this:
//Allocate space for holding 10 ints
int *p = new int[10];

//Overwrite the memory.. doesn't crash here
p[10] = 8;

//Try to delete..crashes..
delete[] p;

Check whether you are writing to the memory location beyond its allocated space.

A: In debug, when you get dynamic buffer by new, a special code gets inserted before and after the buffer to guard the buffer.
Ex:
<Guard>=====buffer allocated on heap of required size=======<Guard>

If you overrun the buffer, the guard inserted gets corrupted and when you try to delete the buffer, then debugger would assert after detecting buffer overrun.
Its bit difficult to find the buffer overrun in large code base. I would suggest couple of ways which can help you to detect this scenario:

*

*Using tools like Rational Purify:
      Its good tool to detect memory corruption.

*Debugging by Windbg with GFlags
enabled:
Refer my answer to similar question here

A: With the correct options, Visual C++ throws a guard value at the end of each buffer. When you free the buffer, it checks that this is still valid. If not, it raises the error that you're seeing.
The most common cause of this error is a buffer overrun. However, it can (theoretically) be caused by a random pointer write (after all, it could write to the guard value).
Odds are, though, it's an overrun.


text:
Q: Error with MPI_Bcast I am getting an error with MPI_Bcast (I think it is an old one) I am not sure why this is happening. The error is as follows:
An error occurred in MPI_Bcast
on communicator MPI_COMM_WORLD
MPI_ERR_TRUNCATE: message truncated
MPI_ERRORS_ARE_FATAL: your MPI job will now abort

The code where it happens is:
for (int i = 0; i < nbProcs; i++){
    for (int j = firstLocalGrainRegion; j < lastLocalGrainRegion; j++){
        GrainRegion * grainRegion = microstructure->getGrainRegionAt(j);
        int grainSize = grainRegion->getBoxSize(nb);
        double * newValues;
        if (myId == i)
            newValues = grainRegion->getNewValues();
        else
            newValues = new double[grainSize];
        MPI_Bcast(newValues, grainSize, MPI_DOUBLE, i, MPI_COMM_WORLD);
        MPI_Barrier(MPI_COMM_WORLD);

        if (myId != i)
            grainRegion->setNewValues(newValues);
    }
}

A: There are two possible reasons for the error.
The first one is that you have a pending previous MPI_Bcast, started somewhere before the outer loop, which did not complete, e.g. in a manner similar to the one in this question.
The second one is a possible buffer size mismatch because of grainRegion->getBoxSize(nb) returning different values in different processes. You can examine the code with a parallel debugger or just put a print statement before the broadcast, for example:
int grainSize = grainRegion->getBoxSize(nb);
printf("i=%d j=%d rank=%02d grainSize=%d\n", i, j, myId, grainSize);

With this particular output format, you should be able to simply run the output through sort and then quickly find mismatched values. Because of the barrier, which is always synchornising (the broadcast might not necessary be so), it is hardly possible for the different calls to MPI_Bcast to interfere with one another as in the first possible case.
If it happens so that your data structure is distributed and indeed the correct value of grainSize is only availalbe at the broadcast root process, then you should first notify the other ranks of the correct size. The simplest (but not the most efficient) solution would be to broadcast grainSize. A better solution would be to first perform an MPI_Allgather with the number of grain regions at each process (only if necessary), then perform an MPI_Allgatherv with the sizes of each region.


text:
Q: Authorize microphone for wildcard subdomain in Chrome? How can I authorize a wildcard subdomain for microphone access? My company uses domains like chat.client1.companyname.com and talk.QA2.companyname.com for its videoconference software. It's extremely annoying having to approve microphone access to each and every subdomain separately.
How can I get Chrome to authorize *.companyname.com for microphone access so I am not bombarded with permissions pop-ups throughout my day? There seems to be some use of subdomains for load-balancing, so it's not like the problem slowly goes away once I've approved more or less all the subdomains I'd use on a regular basis.

A: You will need to authorize the sites one by one.
Chrome used to have in the page
Settings > Privacy and security > Site Settings > Microphone two
"Add" buttons with which you could add websites and even use
wildcards. However, these buttons have now disappeared.


text:
Q: "Link to a Document" Content Type on non-English SharePoint I'm following the code at https://blogs.msdn.microsoft.com/cliffgreen/2008/06/23/creating-a-link-to-a-document-item-in-a-sharepoint-document-library-programmatically/, and I'm worried about the line:
item["Content Type"] = "Link to a Document";

Does the value here need to be localized to the language of the SharePoint installation?  I can't find any documentation either way (or much documentation relevant to this code at all), and I've been burned by too many SharePoint localization problems before (e.g. Is stsadm output guaranteed to be XML?) to assume it will work.  But at the same time, I don't have a non-English system to test with.

A: You can refer to the localized Content Type Name with SPUtility.GetLocalizedString
However make it simple for yourself and just refer to content type ID.
item["ContentTypeId"] = ID;
The below page lists all of the Content Type ID's for out of box content types.
https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ms452896(v%3Doffice.14)


text:
Q: Flutter : API isn't respond when send Field? I create a Future function for Multipart API post request with upload image. But  when I use request.fields.addAll(updateProfileInfo.toJson()); it's not responding.

Here is the code sample -

    Future<Map<String, dynamic>> updateprofile(
      UpdateProfileInfo updateProfileInfo, File imageFile) async {
    var stream = http.ByteStream(Stream.castFrom(imageFile.openRead()));
    var length = await imageFile.length();

    String url = "$baseAPIUrl/update-profile-info";
    String _token = await SavedData().loadToken();
    String authorization = "Bearer $_token";

    final body = jsonEncode(updateProfileInfo);
    final headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      "Authorization": authorization
    };

    var request = http.MultipartRequest("POST", Uri.parse(url));
    var multipartFile = http.MultipartFile('image', stream, length,
        filename: basename(imageFile.path));
    request.headers.addAll(headers);
    request.files.add(multipartFile);

    request.fields.addAll(updateProfileInfo.toJson());

    http.StreamedResponse response = await request.send();

    String respStr = await response.stream.bytesToString();
    dynamic respJson;

    try {
      respJson = jsonDecode(respStr);
    } on FormatException catch (e) {
      print(e.toString());
    }

    print('API ${response.statusCode}\n  $respJson');

    bool isSuccess = response.statusCode == 200;
    var data = json.decode(respStr);

    return {
      'isSuccess': isSuccess,
      "message": isSuccess ? data["success"]["message"] : null,
      "name": isSuccess ? data["success"]["name"] : null,
      "classgroup": isSuccess ? data["success"]["classgroup"] : null,
      "image": isSuccess ? data["success"]["image"] : null,
      "error": isSuccess ? null : data['error']['message'],
    };
  }

How can I send body field request ? please someone help me

A: request.fields is a map of type <String, String>. So all of your fields data must be string. In other way updateProfileInfo.toJson() must return Map<String, String> type object.
Hope this might solve your issue.


text:
Q: If value >= 15 statement TypeScript I work at the moment with the ZapWorks program. The code is write in TypeScript. With this program I try to make a game. Now I have the following problem. I have created a score:
var score = 0;

When an object is pressed:
score++;

Now I want if the score is 16 (which is printed on all objects) you get the message that you have found them all. This is now my if statement:
if (score >= 15)
{
 CharcuterieSansInline_ttf1.visible(true);
 CharcuterieSansInline_ttf1.text("Je hebt alle dieren!");
 console.log(score.toString());
}

Only If statement is not working. The score works, because in the console I can see increment of score, and the text changed too, but not in the if. What goes wrong?

A: It works! The problem: on all the pointerdowns i have to place the if statement. Thanks everybody!

A: i don't know why its is not working in your code .. i just try following code in my pc its works fine.
<html>
<script>
var a = 0;
a++
if(a>=0)
{
    alert("sdsd");
}
</script>
</html>

as u mention you use typeScript so you need to define type of var like
var score:number = 0 ;

and after you can score++ and then condition check


text:
Q: Help finding what formula can solve this problem I am trying to calculate out something, but no matter how much I try I keep running into issues, such as making formulae that are infinitely recursive without finding an answer.
So I am trying to calculate out the velocity that an object would be at, given drag forces, if it somehow changes mass. I know how to find the velocity ignoring Drag, given Conservation of Momentum.
$m_1v_1 = \frac{1}{am_1v_1}$
$v_2 = v_1 * a$
Kinetic energy would be,
$\frac{(mv_1^2 * a)}{2}$
But I can not find a formula wherein this takes into account how such an object, while speeding up, is also slowed down by drag. To find the true velocity that it would be made to reach.
Note, this is not about a falling object, I know how to do that. This is about an object in a horizontal direction. Furthermore, I know this is better suited towards physics stack exchange, but they are both very picky with what is asked there, and I also feel that since this is mainly based on mathematics, it is better here.
This has been driving me insane and help would be greatly appreciated.

A: Let $m$ be the mass of the object at time $t$, $v$ be the velocity at time $t$, $F_D$ be the size of the drag force at time $t$. These are all functions of $t$.
Since the only force exerted to the object is drag, we have the following by Newton's second law of motion:
$$\frac{d(mv)}{dt}=-F_D$$
$$\implies v\frac{dm}{dt}+m\frac{dv}{dt}=-F_D$$
Let $\frac{dm}{dt}/m=r$. If we want to find $v$:
$$\frac{dv}{dt}+rv=\frac{-F_D}{m}$$
Apply the formula of the solution to a linear differential equation.
$$v=e^{-\int rdt}\bigg(\int\frac{-F_D}{m}e^{\int rdt}dt \;+C \bigg)$$
All the indefinite integrals have no integration constant and $C$ is a constant. We can use this to find the velocity when $m$ decreased to $\frac{1}{a}m$. Notice the result would be different when how $m$ changes is different.


text:
Q: Android SQLITE database and spinner Hi geek am new to android,actually i need the code for
selected data to be added into spinner from Db,in spinner when i select an item it should show me the details of column from Db.
fields of the DB:
1.Bank name
2.account number
3.amount details
4.Task
Note:(Bank name to be added to spinner,when i select a bank name in spinner it should show me the account number,amount details and task in a list view).

A: Selected data to be added into spinner from Db ->
you have to have a bit experience in SQLite or any other compatible database with android.. If its SQLite, you have to get a List of objects form the Database. (There are severla ways to do it. If you want I can help you about this).
If you can come up with a List, then you can load it to a Spinner like this.
public void fillSpinner(Spinner yourSpinner, List yourListFromDB) {
    ArrayAdapter spinnerAdapter = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, yourListFromDB);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    yourSpinner.setAdapter(spinnerAdapter);
}


text:
Q: What does the social idiom "not received" mean in 19th century America? I am struggling with a use of the word "received" that I have never seen before, in conjunction with a social status in 19th century America. Specifically, in Margaret Mitchell's Gone With The Wind, Chapter VI, Cathleen gossips to Scarlett that Rhett Butler is attending the barbecue because he is "Not received." I am writing a piece that spans this period and would like to know the scope and meaning of that cultural idiom.
Scene summary

*

*Scarlett O'Hara has been playing the field of beaus at the party and spots Rhett who looks out of place. She's drawn to his "bad boy" vibe and seeks out gossip on him from Cathleen. Cathleen tells Scarlett that he is "not received," which excites Scarlett and she prompts Cathleen for an explanation.

*Cathleen explains Rhett's terrible reputation, that he took a girl out on a date, brought her home late with no chaperone, and the next day refused to marry her. The girl's brother called him out (for a shotgun wedding), Rhett claimed nothing happened but was challenged just the same. Rhett won the duel and killed the brother, and had to leave town "and now nobody receives him."

*The result was that the girl did not get pregnant but was "ruined just the same." I don't know if that ties in to the condition.

I would like to know what the idiom means, and if it would be understood to an 1860's British society as well because my story spans those two cultures. (If there was a different equivalent in England that would be helpful)

A: An early meaning of "received" was "accepted or approved" (this still lives on in the phrase "received pronunciation", which refers to the high-class British accent). So when Rhett is described as "not received", it means that proper society didn't approve of him.

A: I think it means he won't be asked over, and if he comes, the door won't be answered.
Merriam-Webster receive
verb
3a : to permit to enter : admit
b : welcome, greet

A: He's not accepted in society.
In particular, if he tried to call on a lady, or a gentleman, he would be told the other person was "not at home," even if he had seen other visitors received just before, or just after, his attempt.  Calls being the basic unit of society in those days, dinners and balls being larger and more fancy, if you won't be received, you are not in society.
It was, in fact, a practice to receive such visitors weekly, and a matter of great importance:

If your circle of visiting acquaintance is very large, while at the same time your time is fully occupied, or your home duties make it inconvenient to dress every morning to receive visitors, it is a good plan to set aside one morning in the week for a reception day.. . . .

Your friends will, unless there is some especial reason for a call in the interval, pay their visit upon the day named.
Let nothing, but the most imperative duty, call you out upon your reception day. Your callers are, in a measure, invited guests, and it will be an insulting mark of rudeness to be out when they call. Neither can you be excused, except in case of sickness.
Having appointed the day when you will be at home to see your friends, you must, for that day, prepare to give your time wholly to them. The usual hours for morning receptions are from twelve to three, and you should be dressed, and ready for callers, at least half an hour before that time.

The Ladies' Book of Etiquette, and Manual of Politeness by Florence Hartley, Boston 1860


text:
Q: 16/18 VAC to 5 VDC UPS I'm new here so please bear with me.
I'm planning to replace my old central alarm system with a new raspberry pi, which takes 5 VDC input.
My old central uses a separate 230 VAC to 16/18 VAC transformer and 12 Volts lead-acid battery as backup.
I'd like to leverage, if possible, the transformer and the battery in order to build a UPS which would feed 5 VDC into the raspberry pi.
Does it make sense to re-use these components? I'd like it to be energy efficient since it would run 24/7. If so, I'd appreciate any help on how to get started.
Thanks,
Juan

A: You should be able to keep the original batteries, charger and wall wart. This will give you a good 12V rail to work on.
About the 5V rail you can get one of those USB phone chargers for cars, and those should be able to cut it. If you want to roll your own converter go with a LM2596-5.0 fixed buck chip.
As a backup plan, you can use a normal phone charger, a USB battery bank and a 5V supercap to power your Pi continuously.

A: You would need a high efficient buck converter - take wide input option as the battery charger can output voltages even more than 15V.  There are plenty of them on ebay, or an automotive phone charger as suggested by Maxthon Chan - make sure it is not a linear voltage regulator, but buck (step down) DC/DC converter.

A: That should be fine.

*

*Float charge your battery from the existing charger / PSU.

*Buy a 12 V in, 5 V out 'buck converter' to drop the voltage to the RPi. Go a bit high on the current specification - maybe 1200 mA - so you can power peripherals, if required.


text:
Q: TFS build publish test results TRX via REST API & PowerShell I have a TFS build process that incorporates asynchronous remote functional test executions. When the tests have finished executing, I want to publish the generated TRX file in the originating build summary and update the build status (if required).
I've been searching for awhile now and have so far been unsuccessful in finding exactly what I'm looking for: is it possible to publish the TRX file to the build summary via a PowerShell scripted REST API call?

A: I am afraid there is not a rest api available to publish the TRX file to the build summary page.
During the pipeline execution, the tasks consume the trx file and read the test result to generate a report which you see on the build summary page. So even if you managed to upload the trx file afterwards, the trx file will not be processed and you cannot get test report on the build summary page.
If your pipeline waits for the test execution to complete, you can try using scripts to  copy the generated TRX file back to the local agent machine and published via publish tesk results task.
If the pipeline finished before the test execution completed. You can create new pipeline to publish the trx file as workaround. But this will end up showing the test result in a different pipeline build summary page. If it is acceptable to you, you can copy the trx file back to the local agent machine and trigger the new pipeline via Build Queue rest api. You can also consider publishing the trx file to a git repo and add this git repo to the new pipeline as git source.


text:
Q: Bespoke SQL Server 'encoding' sproc - is there a neater way of doing this? I'm just wondering if there's a better way of doing this in SQL Server 2005.
Effectively, I'm taking an originator_id (a number between 0 and 99) and a 'next_element' (it's really just a sequential counter between 1 and 999,999).
We are trying to create a 6-character 'code' from them.
The originator_id is multiplied up by a million, and then the counter added in, giving us a number between 0 and 99,999,999.
Then we convert this into a 'base 32' string - a fake base 32, where we're really just using 0-9 and A-Z but with a few of the more confusing alphanums removed for clarity (I, O, S, Z).
To do this, we just divide the number up by powers of 32, at each stage using the result we get for each power as an index for a character from our array of selected character.

Thus, an originator ID of 61 and NextCodeElement of 9 gives a code of '1T5JA9'

(61 * 1,000,000) + 9 = 61,000,009
61,000,009 div (5^32 = 33,554,432) =  1 = '1'
27,445,577 div (4^32 =  1,048,576) = 26 = 'T'
   182,601 div (3^32 =     32,768) =  5 = '5'
    18,761 div (2^32 =      1,024) = 18 = 'J'
       329 div (1^32 =         32) = 10 = 'A'
         9 div (0^32 =          1) =  9 = '9'

so my code is 1T5JA9

Previously I've had this algorithm working (in Delphi) but now I really need to be able to recreate it in SQL Server 2005.  Obviously I don't quite have the same functions to hand that I have in Delphi, but this is my take on the routine. It works, and I can generate codes (or reconstruct codes back into their components) just fine.
But it looks a bit long-winded, and I'm not sure that the trick of selecting the result of a division into an int (ie casting it, really) is necessarily 'right' - is there a better SQLS approach to this kind of thing?

CREATE procedure dummy_RP_CREATE_CODE @NextCodeElement int, @OriginatorID int,
  @code varchar(6) output
as
begin
  declare @raw_num int;
  declare @bcelems char(32);
  declare @chr int;

  select @bcelems='0123456789ABCDEFGHJKLMNPQRTUVWXY';
  select @code='';

  -- add in the originator_id, scaled into place
  select @raw_num = (@OriginatorID * 1000000) + @NextCodeElement;

  -- now to convert this to a 6-char code

  -- 5^32
  select @chr = @raw_num / 33554432;
  select @raw_num = @raw_num - (@chr * 33554432);
  select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);

  -- 4^32
  select @chr = @raw_num / 1048576;
  select @raw_num = @raw_num - (@chr * 1048576);
  select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);

  -- 3^32
  select @chr = @raw_num / 32768;
  select @raw_num = @raw_num - (@chr * 32768);
  select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);

  -- 2^32
  select @chr = @raw_num / 1024;
  select @raw_num = @raw_num - (@chr * 1024);
  select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);

  -- 1^32
  select @chr = @raw_num / 32;
  select @raw_num = @raw_num - (@chr * 32);
  select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);

  -- 0^32
  select @code = @code + SUBSTRING(@bcelems, 1 + @raw_num, 1);

  -- that's it!
end;

I'm not desperately concerned about optimisation unless this method is actually an order of magnitude (or so) worse than any alternative.
The code only ever gets executed in small bursts, maybe generating 20 or 30 codes every 10 minutes or so. Because of the large range of numbers I don't want to pre-calculate the codes into a huge table (only small pockets of the overall code range will be used in any given installation).
However, I'm sure there's probably a tidier way of achieving the same result - particularly those divisions and subtractions.
Any constructive criticism, observations or suggestions would be most welcome.

A: Seeing as it's SQL Server 2005, any reason not to use a CLR stored procedure? You could use your CLR language of choice then and it'd probably be a relatively direct port of your existing Delphi code.

A: Although it can clearly be done in SQL Server 2005, I think that it's of sufficient 'non-database-ness' that some kind of precompiled, high-level language routine makese sense.
I've written DLLs for Interbase/Firebird, and T-SQL sprocs for SQL Server, but never a CLR routine. It will be an interesting exercise!


text:
Q: RelayCommand in ViewModel: invocation does not have access to bound UI data in ViewModel I'm implementing a basic search text box->button, but I also want to have the user be able to hit the Enter/Return key on the keyboard/pad, as per How to enable enter button on keyboard on wp7?
When the RelayCommand gets invoked, I just get a null value for the contents of the search text box.
I'm using MVVM Light.
I have a PhoneApplicationPage that is bound to a ViewModel with the properties:
public class MainViewModel : ViewModelBase

{

private string _searchString;

public RelayCommand Search { get; private set; }
public RelayCommand<KeyEventArgs> SearchTextBoxKeyDown { get; private set; }

public string SearchString
{
    get { return _searchString; }
    set
    {
        if (_searchString != value)
        {
            _searchString = value;
            RaisePropertyChanged("SearchString");
        }
    }
}

public MainViewModel()
{
    if (IsInDesignMode)
    {
        // Code runs in Blend --> create design time data.
    }
    else
    {
        // Code runs "for real"
        SearchTextBoxKeyDown=new RelayCommand<KeyEventArgs>((e)=>
        {
            if (e.Key == Key.Enter)
            {
                // SearchString is empty here?
                Search.Execute(null);
            }
        });
        Search = new RelayCommand(() =>
        { // invokes Search with SearchString

        },
        () =>
        {
            bool isEnabled = true;
            if (string.IsNullOrWhiteSpace(SearchString)) isEnabled = false;
            return isEnabled;
        });
    }
}

The View uses the MVVM Light toolkit to invoke the method for KeyDown on the AutoComplete control (it is a Telerik control, but it looks like a TextBox and smells like a TextBox):
                <telerikInput:RadAutoCompleteBox
                    InputScope="Search"
                    Text="{Binding SearchString,Mode=TwoWay}"
                    SuggestionsSource="{Binding MruSearchStrings}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="KeyDown">
                            <cmd:EventToCommand x:Name="searchStringTextBoxKeyDown" Command="{Binding SearchTextBoxKeyDown, Mode=OneWay}" PassEventArgsToCommand="True">
                            </cmd:EventToCommand>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </telerikInput:RadAutoCompleteBox>

In the invoked code, I just get null when I access the SearchString, which is what the TextBox is bound to - even though I have entered text into it. It's almost as if the SearchTextBox has not sent its data back to the ViewModel for the ViewModel to pick up in the event code.
What am I doing wrong?

A: Your ViewModel is not updated with value from TextBox because when you press Enter you still have focus in TextBox. By default, ViewModel will be updated after you leave TextBox control. However, you can change this situation by using custom behavior. This one works for me
 like a charm: http://zoltanarvai.com/2009/07/22/binding-update-on-textbox-textchanged-event-using-behaviors/


text:
Q: How do I fix inconsistent types in InfluxDB? In InfluxDB (1.5), I have a table where the fields have become inconsistently typed. Most rows in the table are Integer, however, some rows have become strings.

*

*How is this possible? I thought, once a field's types were set (upon first insert), any insert into the table with incorrect typing would fail.

*What do I do now? If I go back and attempt to overwrite the data in the inconsistent rows, I get errors saying the field is a string.

A: After some more research, here's what I've discovered:
Answer to Part 1:
InfluxDB uses a system they refer to as 'sharding' - while I don't know the specifics, I do know that data from the same measurement/table can be stored across multiple, different 'shards'.
According to the InfluxDB documentation, field types can differ between these shards, within the same field, on the same table.
Answer to Part 2:
In order to fix this, the currently-suggested answer is to make a new table, download all the data, and re-insert while ensuring the data that gets inserted is the proper types.
If you had a tag which changed type and became a field, this can be especially difficult to fix, the link above does not address that. To do selects only on tag or field, you can use tag_name::tag or field_name::field within a select statement.
The GROUP BY * clause suggested in the link is required in order to preserve tags, but seemed to cause issues when I used it.
My current solution is a PHP script that uses curl, downloads the points, chunks them, then re-inserts the points into the new table, ensuring each point that gets inserted is casted to the new, uniform type, and properly inserted.
The best way to stopping future issues, is simply not to have them. I went looking for how to lock field types in all cases, across all shards, for a particular measurement table.
Unfortunately, it seems impossible to guarantee 100% type consistency across all current and future shards. "Don't make mistakes because it's really difficult to clean up" seems to be InfluxDB's modus operandi.


text:
Q: removing class from a div in c# I tried using the server-side .CssClass, but this isn't available for me to use.
My div has runat="server" so I can access it, but I just cannot see .CssClass in the drop-down when i hit ".". Does anyone know how to get past this or any other solution that might work?
Ok, my bad. I just found out that this does not work for HTML controls, only for asp controls

A: HTML

Code Behind
add =>       Test.Attributes.Add("class", "myClass")

remove =>    Test.Attributes.("class") = "";

A: This would be more specific:
HTML

Server code:
Test.Attributes.Remove("class");

A: If you are wanting to read the class name, you will need to use the code:
string className = Test.Attributes["class"].ToString();

If you are wanting to replace a specific class you will need to use the code:
Test.Attributes.Add("class", Test.Attributes["class"].ToString().Replace("spacerDiv", ""));

A: This is the same solution as Tim, but I removed the not needed toString method.
myDiv.Attributes.Add("class", myDiv.Attributes["class"].Replace("spacerDiv", ""));

To add a class to a div is somewhat the same.
myDiv.Attributes.Add("class", "spacerDiv");

A: A better approach to handle adding or removing class for any HtmlGenericControl would be to use the extension as provided below:
  public static void RemoveCssClass(this HtmlGenericControl controlInstance, string css)
    {
        var strCssClass = controlInstance.Attributes["class"];
        controlInstance.Attributes["class"] = string.Join(" ", strCssClass.Split(' ').Where(x => x != css).ToArray());
    }

    public static void AddCssClass(this HtmlGenericControl controlInstance, string css)
    {
        var strCssClass = controlInstance.Attributes["class"];
        controlInstance.Attributes["class"] = string.Join($" {css} ", strCssClass.Split(' ').ToArray());
    }

For WebControl the same code can be modified as below:
public static void RemoveCssClass(this WebControl controlInstance, string css)
        {
            controlInstance.CssClass = string.Join(" ", controlInstance.CssClass.Split(' ').Where(x => x != css).ToArray());
        }

    public static void AddCssClass(this WebControl controlInstance, string css)
    {
        controlInstance.CssClass = string.Join($" {css} ", controlInstance.CssClass.Split(' ').ToArray());
    }

A: Remove css class
myDiv.Attributes["class"]=" ";


text:
Q: How to transform a column with many variables into separate variable columns I provide a simple version of my dataset at the end.
Given a Time, I have for every Activity values for the nine different subjects.
I want to achieve that the Subject column is transformed into 9 new variables, such that I have the following structure:
Time, Activity, Subject 1, Subject 2,...., Subject 9
Where the Subject variables contain the corresponding entries of Value.
So at the end I want to have for every point of Time, the 8 Activities and
 Time | ACTIVITY | Subject1 | Subject2 | ... | Subject9
    -----| ---------|----------|----------|-----|----------
    1995 | A        | example  | example  |     | example
    1995 | F        | example  | example  |     | example
    1995 | K        | example  | example  |     | example
    1995 | J        | example  | example  |     | example

...
I already tried the reshape command,
reshape wide ACTIVITY, i(Value) j(Subject) string but I suspect that reshape isn´t the correct command here to obtain the result I want.
clear
input int Time str55 Subject str3 ACTIVITY str18 Value
1995 "Average hours worked per person employed"                "A"   "-2.426848"
1995 "Gross value added per hour worked, constant prices"      "A"   "19.235807"
1995 "Gross value added per person employed, constant prices " "A"   "16.342135"
1995 "Labour compensation per employee "                       "A"   "-8.435628"
1995 "Labour compensation per hour worked"                     "A"   "-7.921433"
1995 "Total employment (number of persons employed)"           "A"   "4.14512"
1995 "Total hours worked"                                      "A"   "1.617676"
1995 "Unit Labour Costs"                                       "A"   "-22.776078"
1995 "Unit Labour Costs, employment based "                    "A"   "-21.297326"
1995 "Average hours worked per person employed"                "F"   "-1.653278"
1995 "Gross value added per hour worked, constant prices"      "F"   "1.703939"
1995 "Gross value added per person employed, constant prices " "F"   ".02249"
1995 "Labour compensation per employee "                       "F"   "2.544764"
1995 "Labour compensation per hour worked"                     "F"   "3.459858"
1995 "Total employment (number of persons employed)"           "F"   "1.784137"
1995 "Total hours worked"                                      "F"   ".101362"
1995 "Unit Labour Costs"                                       "F"   "1.726501"
1995 "Unit Labour Costs, employment based "                    "F"   "2.521708"
1995 "Average hours worked per person employed"                "K"   "1.694564"
1995 "Gross value added per hour worked, constant prices"      "K"   "1.221264"
1995 "Gross value added per person employed, constant prices " "K"   "2.936522"
1995 "Labour compensation per employee "                       "K"   "9.752344000000001"
1995 "Labour compensation per hour worked"                     "K"   "7.939534"
1995 "Total employment (number of persons employed)"           "K"   "1.113274"
1995 "Total hours worked"                                      "K"   "2.826703"
1995 "Unit Labour Costs"                                       "K"   "6.637213"
1995 "Unit Labour Costs, employment based "                    "K"   "6.621383"
1995 "Average hours worked per person employed"                "J"   "1.271221"
1995 "Gross value added per hour worked, constant prices"      "J"   ".416748"
1995 "Gross value added per person employed, constant prices " "J"   "1.693267"
1995 "Labour compensation per employee "                       "J"   "6.733944"
1995 "Labour compensation per hour worked"                     "J"   "4.750437"
1995 "Total employment (number of persons employed)"           "J"   "3.961272"
1995 "Total hours worked"                                      "J"   "5.28285"
1995 "Unit Labour Costs"                                       "J"   "4.315704"
1995 "Unit Labour Costs, employment based "                    "J"   "4.956746"
1995 "Average hours worked per person employed"                "C"   "-.961265"
1995 "Gross value added per hour worked, constant prices"      "C"   "3.918341"
1995 "Gross value added per person employed, constant prices " "C"   "2.919411"
1995 "Labour compensation per employee "                       "C"   "9.327536"
1995 "Labour compensation per hour worked"                     "C"   "10.142572"
1995 "Total employment (number of persons employed)"           "C"   "-.615951"
1995 "Total hours worked"                                      "C"   "-1.571295"
1995 "Unit Labour Costs"                                       "C"   "5.989541"
1995 "Unit Labour Costs, employment based "                    "C"   "6.226353"
1995 "Average hours worked per person employed"                "BDE" ".052094"
1995 "Gross value added per hour worked, constant prices"      "BDE" "9.885144"
1995 "Gross value added per person employed, constant prices " "BDE" "9.942387"
1995 "Labour compensation per employee "                       "BDE" "13.808441"
1995 "Labour compensation per hour worked"                     "BDE" "12.406663"
1995 "Total employment (number of persons employed)"           "BDE" "-3.86639"
1995 "Total hours worked"                                      "BDE" "-3.81631"
1995 "Unit Labour Costs"                                       "BDE" "2.294686"
1995 "Unit Labour Costs, employment based "                    "BDE" "3.516435"
1995 "Average hours worked per person employed"                "MN"  ".131723"
1995 "Gross value added per hour worked, constant prices"      "MN"  "-6.173118"
1995 "Gross value added per person employed, constant prices " "MN"  "-6.049526"
1995 "Labour compensation per employee "                       "MN"  ".8593380000000001"
1995 "Labour compensation per hour worked"                     "MN"  ".451672"
1995 "Total employment (number of persons employed)"           "MN"  "7.730918"
1995 "Total hours worked"                                      "MN"  "7.872824"
1995 "Unit Labour Costs"                                       "MN"  "7.060652"
1995 "Unit Labour Costs, employment based "                    "MN"  "7.35373"
1995 "Average hours worked per person employed"                "G_I" "-1.07602"
1995 "Gross value added per hour worked, constant prices"      "G_I" "4.234882"
1995 "Gross value added per person employed, constant prices " "G_I" "3.113293"
1995 "Labour compensation per employee "                       "G_I" "3.355356"
1995 "Labour compensation per hour worked"                     "G_I" "3.935881"
1995 "Total employment (number of persons employed)"           "G_I" "2.40757"
1995 "Total hours worked"                                      "G_I" "1.305644"
1995 "Unit Labour Costs"                                       "G_I" "-.286853"
1995 "Unit Labour Costs, employment based "                    "G_I" ".234754"
1996 "Average hours worked per person employed"                "A"   "2.25265"
1996 "Gross value added per hour worked, constant prices"      "A"   "5.369203"
1996 "Gross value added per person employed, constant prices " "A"   "7.742802"
1996 "Labour compensation per employee "                       "A"   "10.454575"
1996 "Labour compensation per hour worked"                     "A"   "5.366434"
1996 "Total employment (number of persons employed)"           "A"   ".451591"
1996 "Total hours worked"                                      "A"   "2.714414"
1996 "Unit Labour Costs"                                       "A"   "-.002628"
1996 "Unit Labour Costs, employment based "                    "A"   "2.516895"
1996 "Average hours worked per person employed"                "F"   "1.728397"
1996 "Gross value added per hour worked, constant prices"      "F"   "3.759875"
1996 "Gross value added per person employed, constant prices " "F"   "5.553258"
1996 "Labour compensation per employee "                       "F"   "5.375732"
1996 "Labour compensation per hour worked"                     "F"   "1.426935"
1996 "Total employment (number of persons employed)"           "F"   "-2.600872"
1996 "Total hours worked"                                      "F"   "-.9174290000000001"
1996 "Unit Labour Costs"                                       "F"   "-2.248403"
1996 "Unit Labour Costs, employment based "                    "F"   "-.168186"
1996 "Average hours worked per person employed"                "K"   "-.480611"
1996 "Gross value added per hour worked, constant prices"      "K"   "7.184181"
1996 "Gross value added per person employed, constant prices " "K"   "6.669043"
1996 "Labour compensation per employee "                       "K"   "7.474571"
1996 "Labour compensation per hour worked"                     "K"   "7.808084"
1996 "Total employment (number of persons employed)"           "K"   ".219797"
1996 "Total hours worked"                                      "K"   "-.26187"
1996 "Unit Labour Costs"                                       "K"   ".582085"
1996 "Unit Labour Costs, employment based "                    "K"   ".755166"
1996 "Average hours worked per person employed"                "J"   "1.146989"
1996 "Gross value added per hour worked, constant prices"      "J"   "2.294382"
1996 "Gross value added per person employed, constant prices " "J"   "3.467687"
1996 "Labour compensation per employee "                       "J"   "-.888716"
1996 "Labour compensation per hour worked"                     "J"   "-1.391543"
1996 "Total employment (number of persons employed)"           "J"   "3.804509"
1996 "Total hours worked"                                      "J"   "4.995135"
1996 "Unit Labour Costs"                                       "J"   "-3.603252"
1996 "Unit Labour Costs, employment based "                    "J"   "-4.2104"
1996 "Average hours worked per person employed"                "C"   ".127422"
1996 "Gross value added per hour worked, constant prices"      "C"   ".390807"
1996 "Gross value added per person employed, constant prices " "C"   ".5187270000000001"
1996 "Labour compensation per employee "                       "C"   "-.219582"
1996 "Labour compensation per hour worked"                     "C"   "-.44278"
1996 "Total employment (number of persons employed)"           "C"   "1.171237"
1996 "Total hours worked"                                      "C"   "1.300151"
1996 "Unit Labour Costs"                                       "C"   "-.830342"
1996 "Unit Labour Costs, employment based "                    "C"   "-.734499"
1996 "Average hours worked per person employed"                "BDE" "-.10856"
1996 "Gross value added per hour worked, constant prices"      "BDE" "8.380025"
1996 "Gross value added per person employed, constant prices " "BDE" "8.262368"
1996 "Labour compensation per employee "                       "BDE" "6.231358"
1996 "Labour compensation per hour worked"                     "BDE" "7.102013"
1996 "Total employment (number of persons employed)"           "BDE" "-7.014769"
1996 "Total hours worked"                                      "BDE" "-7.115713"
1996 "Unit Labour Costs"                                       "BDE" "-1.179195"
1996 "Unit Labour Costs, employment based "                    "BDE" "-1.876007"
1996 "Average hours worked per person employed"                "MN"  "-.353884"
1996 "Gross value added per hour worked, constant prices"      "MN"  "1.076035"
1996 "Gross value added per person employed, constant prices " "MN"  ".718343"
1996 "Labour compensation per employee "                       "MN"  "1.12435"
1996 "Labour compensation per hour worked"                     "MN"  "1.117737"
1996 "Total employment (number of persons employed)"           "MN"  "3.155591"
1996 "Total hours worked"                                      "MN"  "2.790539"
1996 "Unit Labour Costs"                                       "MN"  ".041258"
1996 "Unit Labour Costs, employment based "                    "MN"  ".403111"
1996 "Average hours worked per person employed"                "G_I" "-.798141"
1996 "Gross value added per hour worked, constant prices"      "G_I" "4.965412"
1996 "Gross value added per person employed, constant prices " "G_I" "4.127639"
1996 "Labour compensation per employee "                       "G_I" "10.194463"
1996 "Labour compensation per hour worked"                     "G_I" "10.477853"
1996 "Total employment (number of persons employed)"           "G_I" ".885576"
1996 "Total hours worked"                                      "G_I" ".080367"
1996 "Unit Labour Costs"                                       "G_I" "5.251674"
1996 "Unit Labour Costs, employment based "                    "G_I" "5.826333"
1997 "Average hours worked per person employed"                "A"   ".731776"
1997 "Gross value added per hour worked, constant prices"      "A"   "-3.186056"
1997 "Gross value added per person employed, constant prices " "A"   "-2.477594"
1997 "Labour compensation per employee "                       "A"   "-5.06916"
1997 "Labour compensation per hour worked"                     "A"   "-6.890363"
1997 "Total employment (number of persons employed)"           "A"   "2.698438"
1997 "Total hours worked"                                      "A"   "3.44996"
1997 "Unit Labour Costs"                                       "A"   "-3.826213"
1997 "Unit Labour Costs, employment based "                    "A"   "-2.657405"
1997 "Average hours worked per person employed"                "F"   "2.117396"
1997 "Gross value added per hour worked, constant prices"      "F"   "5.906121"
1997 "Gross value added per person employed, constant prices " "F"   "8.148573000000001"
1997 "Labour compensation per employee "                       "F"   "1.279112"
1997 "Labour compensation per hour worked"                     "F"   "1.322872"
1997 "Total employment (number of persons employed)"           "F"   "1.8041"
1997 "Total hours worked"                                      "F"   "3.959696"
1997 "Unit Labour Costs"                                       "F"   "-4.327652"
1997 "Unit Labour Costs, employment based "                    "F"   "-6.351874"
1997 "Average hours worked per person employed"                "K"   ".43239"
1997 "Gross value added per hour worked, constant prices"      "K"   "8.700056999999999"
1997 "Gross value added per person employed, constant prices " "K"   "9.170064999999999"
1997 "Labour compensation per employee "                       "K"   "11.205117"
1997 "Labour compensation per hour worked"                     "K"   "11.399443"
1997 "Total employment (number of persons employed)"           "K"   "-1.822407"
1997 "Total hours worked"                                      "K"   "-1.397898"
1997 "Unit Labour Costs"                                       "K"   "2.483335"
1997 "Unit Labour Costs, employment based "                    "K"   "1.864112"
1997 "Average hours worked per person employed"                "J"   "-3.236768"
1997 "Gross value added per hour worked, constant prices"      "J"   "21.34373"
1997 "Gross value added per person employed, constant prices " "J"   "17.416115"
1997 "Labour compensation per employee "                       "J"   "14.072785"
1997 "Labour compensation per hour worked"                     "J"   "18.627454"
1997 "Total employment (number of persons employed)"           "J"   "-7.862875"
1997 "Total hours worked"                                      "J"   "-10.84514"
1997 "Unit Labour Costs"                                       "J"   "-2.238497"
1997 "Unit Labour Costs, employment based "                    "J"   "-2.84742"
1997 "Average hours worked per person employed"                "C"   ".198729"
1997 "Gross value added per hour worked, constant prices"      "C"   "3.620337"
1997 "Gross value added per person employed, constant prices " "C"   "3.826261"
1997 "Labour compensation per employee "                       "C"   "4.423006"
1997 "Labour compensation per hour worked"                     "C"   "4.697621"
1997 "Total employment (number of persons employed)"           "C"   "-.840977"
1997 "Total hours worked"                                      "C"   "-.643919"
1997 "Unit Labour Costs"                                       "C"   "1.039645"
1997 "Unit Labour Costs, employment based "                    "C"   ".574753"
1997 "Average hours worked per person employed"                "BDE" "1.753725"
1997 "Gross value added per hour worked, constant prices"      "BDE" "4.57343"
1997 "Gross value added per person employed, constant prices " "BDE" "6.40736"
1997 "Labour compensation per employee "                       "BDE" ".474943"
1997 "Labour compensation per hour worked"                     "BDE" "-.653428"
1997 "Total employment (number of persons employed)"           "BDE" "-2.690283"
1997 "Total hours worked"                                      "BDE" "-.983739"
1997 "Unit Labour Costs"                                       "BDE" "-4.998266"
1997 "Unit Labour Costs, employment based "                    "BDE" "-5.575195"
1997 "Average hours worked per person employed"                "MN"  ".420778"
1997 "Gross value added per hour worked, constant prices"      "MN"  "-1.055989"
1997 "Gross value added per person employed, constant prices " "MN"  "-.639655"
1997 "Labour compensation per employee "                       "MN"  "5.067928"
1997 "Labour compensation per hour worked"                     "MN"  "4.630638"
1997 "Total employment (number of persons employed)"           "MN"  "7.493905"
1997 "Total hours worked"                                      "MN"  "7.946215"
1997 "Unit Labour Costs"                                       "MN"  "5.747318"
1997 "Unit Labour Costs, employment based "                    "MN"  "5.744327"
1997 "Average hours worked per person employed"                "G_I" ".532551"
1997 "Gross value added per hour worked, constant prices"      "G_I" "3.058326"
1997 "Gross value added per person employed, constant prices " "G_I" "3.607164"
1997 "Labour compensation per employee "                       "G_I" "2.245979"
1997 "Labour compensation per hour worked"                     "G_I" "2.114407"
1997 "Total employment (number of persons employed)"           "G_I" ".621482"
1997 "Total hours worked"                                      "G_I" "1.157342"
1997 "Unit Labour Costs"                                       "G_I" "-.9159080000000001"
1997 "Unit Labour Costs, employment based "                    "G_I" "-1.313795"
end

A: In Stata, columns are columns of matrices. What you call columns are variables.
Your screenshot shows the following problems:

*

*Your Time variable and Value variable are string. That looks wrong. There is probably some garbage somewhere in those variables. Perhaps headers have been copied into the data. list Time if missing(real(Time)) is the kind of command that will show you non-numeric values.

*Your Subject variable shows trailing spaces. That could cause problems if it's not consistent.

*Your Subject variable's distinct values couldn't be parts of variable names given the embedded spaces. So, we need some extra work.
This code generates a toy example and shows some technique. Contrary to your guess, reshape is the command of choice.
clear
set obs 6
gen location = "AUS"
gen time = 1995
gen subject = cond(mod(_n, 2), "Fooling around ", " Wasting time")
gen activity = word("A F K", ceil(_n/2))
gen value = _n
replace subject = trim(subject)
list

     +-----------------------------------------------------+
     | location   time          subject   activity   value |
     |-----------------------------------------------------|
  1. |      AUS   1995   Fooling around          A       1 |
  2. |      AUS   1995     Wasting time          A       2 |
  3. |      AUS   1995   Fooling around          F       3 |
  4. |      AUS   1995     Wasting time          F       4 |
  5. |      AUS   1995   Fooling around          K       5 |
     |-----------------------------------------------------|
  6. |      AUS   1995     Wasting time          K       6 |
     +-----------------------------------------------------+

egen group = group(subject), label
su group, meanonly
local gmax = r(max)
forval g = 1/`gmax' {
    local lbl`g' "`: label (group) `g''"
}
drop subject

reshape wide value, i(location time activity) j(group)

forval g = 1/`gmax' {
   label var value`g' "`lbl`g''"
}
list

     +----------------------------------------------+
     | location   time   activity   value1   value2 |
     |----------------------------------------------|
  1. |      AUS   1995          A        1        2 |
  2. |      AUS   1995          F        3        4 |
  3. |      AUS   1995          K        5        6 |
     +----------------------------------------------+

describe

Contains data
  obs:             3
 vars:             5
 size:            60 (99.9% of memory free)
--------------------------------------------------------------------------------
              storage  display     value
variable name   type   format      label      variable label
--------------------------------------------------------------------------------
location        str3   %9s
time            float  %9.0g
activity        str1   %9s
value1          float  %9.0g                  Fooling around
value2          float  %9.0g                  Wasting time
--------------------------------------------------------------------------------
Sorted by:  location  time  activity


text:
Q: Android Activity Instance in Service In my android project I have the MainActivity and a Service. How can I get the activity's instance in my service?

A: Why do you want to? Are you trying to communicate between the Service and the Activity? If so, then getting the Activity object in the Service is probably not the way you want to go.
An Activity fits into the MVC model as a combination View/Controller. A Service is a Controller. To pass information between them, you need to update the Model, which can be SharedPreferences, a broadcast Intent, a content provider, and so forth. What you shouldn't do is assume that various components in your app are all part of a monolithic "whole". An Android app is a loose connection of individual pieces that should communicate with each other using Android constructs rather than variables, and so forth.

A: That's not an appropriate approach. Instead, send messages to the activity, if it exists, to do things. Use LocalBroadcastManager, or a third-party message bus like Square's Otto, or a Messenger, or something to pass messages from the service to the activity.


text:
Q: C# CS0266 using "this" to current instance of class I have am creating a program where a person can equip a sandwich. I keep getting error CS0266 and I can't figure out why? I am using this to refer to the current instance of the person.
 class Sandwich : IEquip
 {
    public void Equip(Person person)
    {
        person.EquippedSandwich = this; //I get the error on "this" here.
    }
    ...
  }

  interface IEquip
  {
     void Equip(Person person);
  }

class Person
{
  private Sandwich equippedSandwich;
  //methods and properties

  public BiteSandwich equippedSandwich
  {
      get {  return EquippedSandwich; }
      set { equippedSandwich = value; }
  }
}

A: Usually you get this error when your code tries to convert between two types that cannot be implicitly converted, but where an explicit conversion is available.
You need to do an explicit cast with a type that EquippedSandwich belongs to.
 person.EquippedSandwich = (IEquip)this;


text:
Q: Scrollviewer not visible inside Usercontrol WPF WPF Scrollviewer not visible inside Usercontrol.
I am using PRISM architecture.
I have a scrollviewer inside usercontrol and the scrollviewer contains a stackpanel.
<UserControl x:Class="SomeView"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      mc:Ignorable="d" >

     <UserControl.Resources>
     <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
     </UserControl.Resources>

     <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
     <StackPanel>
<TextBlock Text="Initialize" HorizontalAlignment="Center" VerticalAlignment="Center"/>

 <StackPanel Orientation="Horizontal">
 <Label Content="Left"/>

 <ComboBox ItemsSource="{Binding LeftComboItems}"  SelectedItem="{Binding LeftSelectedItem}" />
 <Label Content="Right"/>
<ComboBox ItemsSource="{Binding RightComboItems}" SelectedItem="{Binding RightSelectedItem}"/>
 <Label/>

<Button Content="Save" Command="{Binding SaveCommand}"/>
 </StackPanel>
 <StackPanel Visibility="{Binding IsVisible,Converter={StaticResource BooleanToVisibilityConverter}}">

 <Grid>

Skipping column definitions
<StackPanel Grid.Column="1" Grid.ColumnSpan="2">
 <Label Content="Left"  />
 <DataGrid ItemsSource="{Binding LeftDataGrid}" AutoGenerateColumns="False" ColumnWidth="*" Grid.Column="2" >
 <DataGrid.Columns>
 <DataGridTextColumn Header="ID" Binding="{Binding ID}" />
 <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
 </DataGrid.Columns>
 </DataGrid>
 </StackPanel>

 <StackPanel Grid.Column="4" Grid.ColumnSpan="2">
 <Label Content="Left Grid" />
 <DataGrid ItemsSource="{Binding RightDataGrid, Mode=OneWay}" AutoGenerateColumns="False" ColumnWidth="*" CanUserAddRows="False" CanUserDeleteRows="False" >

 <DataGridTextColumn Header="ID" Binding="{Binding id}" />
 <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>

 </DataGrid>
 </StackPanel>

    </StackPanel>
 </Grid>
     </StackPanel>
     </ScrollViewer>

LeftComboItems, RightComboItems are Observable Collections of type string.

A: Remove the StackPanel (use Grid/Panel) or set some large height for StackPanel.

A: As far as I know the ScrollViewer control is used to enable scrolling in overflow situations like in a  ListBox with many items for example. So if I where you I would put the DataGrid in a ScrollViewer and remove any fixed Row heights to let it overflow otherwise there is no point in using the ScrollViewer.
Hope it helps.

A: You have not mention any where the height and width of your screen. Scroll viewer displays
after a specific limit. So if you want scroll viewer to get displayed mention at least minimum height for the case of vertical scroll bar. when your data/controls in that scroll viewer exceeds the limit of height it will appear.

ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" MinHeight="300" MinWidth="200"