text:
Q: What architectural model is commonly used in large, enterprise, functional F# development? I've been using F# in scripting (data science work) and developing class libraries to use with C#. In the latter case, I've been creating modules with pure functional code.
If I wanted to start developing large applications entirely in F#, I'm not sure how I'd structure it. I find the functional style of development very intuitive, but can it scale to large enterprise applications? Is it more common to, say, use an OO structure and then flesh out the objects using functional code?
Intuitively, it feels like writing lots of functions without some kind of class structure could get unwieldy. But I'm perfectly willing to accept that might just be down to years of "brainwashing" from working on OO projects.
Presumably there must be Haskell enterprise applications that are entirely functional, so maybe this is also true in F#. Or maybe it's a lot of pain to do everything functionally, so F# devs mix and match. I don't know.
Can anyone point me at articles that discuss how to scale up the functional paradigm to large enterprise application development?

A: I don't have a complete answer to the question, but I think there is a lot you can learn from some of the large community projects in F#. They might not be large enterprise software, but they are fairly large if you count all the F# dependencies they use.
I think that well-designed functional libraries can be extremely composable and this is an approach that works overall quite well for the community.

*

*I did a talk about the F# open source community at the F# eXchange (the second part is more interesting), the slides are here.

*I talked about library design (slides) at NCRAFTS in Paris

*I wrote two articles on this topic - one is about multiple levels of abstraction and one is about libraries vs. frameworks.

All of this focuses more on components (libraries) than complete applications, but I think the complete application can very well be just s thin layer combining multiple composable components together.


text:
Q: Application with java.lang.OutOfMemoryError: Java heap space Recently, I started using a Java application a former colleague of mine designed. After performing certain actions, the application freezes and the error.log file shows the following:
Exception in thread "Thread-4" java.lang.OutOfMemoryError: Java heap space
    at org.apache.poi.poifs.storage.BATBlock.<init>(BATBlock.java:57)
    at org.apache.poi.poifs.storage.BATBlock.<init>(BATBlock.java:210)
    at org.apache.poi.poifs.storage.BATBlock.createBATBlocks(BATBlock.java:87)
    at org.apache.poi.poifs.storage.BlockAllocationTableWriter.simpleCreateBlocks(BlockAllocationTableWriter.java:150)
    at org.apache.poi.poifs.storage.BlockAllocationTableWriter.createBlocks(BlockAllocationTableWriter.java:103)
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.writeFilesystem(POIFSFileSystem.java:221)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:744)
    at net.ndmystko.qa.QAJobReporter.writeWorkbook(QAJobReporter.java:478)
    at net.ndmystko.qa.QAJobReporter.writeResults(QAJobReporter.java:458)
    at net.ndmystko.qa.QAJobReporter.writeResults(QAJobReporter.java:402)
    at net.ndmystko.qa.QA.displayEvolutionProgress(QA.java:1257)
    at net.ndmystko.qa.QA.access$9(QA.java:1186)
    at net.ndmystko.qa.QA$4.actionPerformed(QA.java:1176)
    at net.ndmystko.analysis.evolution.Evolution.run(Evolution.java:191)

I have read that I would need to increase the heap size allotted to the application. However, I do not know how to achieve this, or where I could enter the code needed. Any help would be greatly appreciated.
Note: I am not experienced in programming. I run the program from a .bat file.

A: You can use the following Java commandline parameters
-Xms: initial heap size
-Xmx: Maximum heap size

Set it when you run your application, e.g.
java -Xmx1024m YourClass

for allocating 1024 MB
java -Xmx2g YourClass

for allocating 2 GB
Edit: In regard to your note the java command is probably inside the .bat file. So you should open it up, find the java command and add the commandline arguments there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Venn diagram of networks? I am using igraph on R and would like to create a Venn Diagram of multiple networks, to show how many edges they share. I haven't figured out an easy way to do this.
For instance:
> net1 <- graph.data.frame(data.frame(a=letters[1:10],b=letters[11:20]),
+                          directed=F)
> net2 <- graph.data.frame(data.frame(a=c(letters[1:5],letters[15:25]),
+                          b=c(letters[11:20],letters[c(21:26)])),
+                          directed=F)
>
> net1_2 <- graph.intersection(net1,net2,keep.all.vertices=F)
>
> net1
IGRAPH UN-- 20 10 --
+ attr: name (v/c)
> net2
IGRAPH UN-- 21 16 --
+ attr: name (v/c)
> net1_2
IGRAPH UN-- 15 5 --
+ attr: name (v/c)

And then do something like this, but that could work also on multiple networks, not only 2:
GraphsVenn(net1,net2)

If you are thinking why I don't just draw the merged network and color the intersection it's because the networks are huge and it would be a mess.
Thank you!

A: I am not an expert on igraph, but I think you can get a list of edges which might be the input for (among others) my nVennR package:
library(igraph)
library(nVennR)

net1 <- graph.data.frame(data.frame(a=letters[1:10],b=letters[11:20]), directed=F)
net2 <- graph.data.frame(data.frame(a=c(letters[1:5],letters[15:25]), b=c(letters[11:20],letters[c(21:26)])), directed=F)

myV <- plotVenn(list(net1=as_ids(E(net1)), net2=as_ids(E(net2))))

And the result:

You can then query the elements in each region:
> listVennRegions(myV)
$`0, 1 (net2)`
 [1] "o|p" "p|q" "q|r" "r|s" "s|t" "t|u" "u|v" "v|w" "w|x" "x|y" "y|z"

$`1, 0 (net1)`
[1] "f|p" "g|q" "h|r" "i|s" "j|t"

$`1, 1 (net1, net2)`
[1] "a|k" "b|l" "c|m" "d|n" "e|o"

This package can handle any number of sets, although more than six is really slow and not very informative. If you are interested, there is a vignette with more information.


text:
Q: Как получить список статей в зависимости от выбранной категории в виджете? Всем привет! Делаю сайт, используя CMS Wordpress. Создаю виджет, получаю все категории в переменную и вывожу их в select, значениями value являются id категорий. Как мне в зависимости от выбранной категории получить id и вытащить все статьи данной категории, которые пойдут в следующий select?
Заранее спасибо.

A: Когда пользователь  выбирает значение первого select, в браузере возникает событие, которое можно перехватить в функции change в jQuery. В этой функции надо извлечь выбор первого select, и отправить ajax запрос.
Полученные из ajax данные вставить во второй select с помощью jQuery.


text:
Q: How to Run Python on Komodo IDE that read from text file? I am using Komodo IDE and have a python file that reads text from a text file, does calculations, then outputs to the console. I am using a command to run the file, with the phrase %(python3) -u "%F in the command part.
When I run this file in debugger, it works fine, but when I run it using the command to output to Command Output, this error pops up:
Traceback (most recent call last):
  File "C:\Users\Haseeb\Desktop\Saud\A School Work\Z-Computer Programming\ECOO Practice\2010Problem1.py", line 1, in <module>
    f = open('2010DATA.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: '2010DATA.txt'
This command runs other programs, just not ones that read from text files.  Here is a picture of the code, command and and error.

Any help would be highly appreciated.

A: You need to set the "Start in" directory to the directory on which you are executing your command, or refrain from using relative paths.


text:
Q: Python use of ConfigParser I have some properties stored in a .txt file that are used by several different classes and functions stored over multiple modules. To be able to access the properties from these different locations I've got a blank module.
Is it better to set the module itself to be the ConfigParser object, or to read in all the parameters and set them to module level attributes?
I.e. first way
blank_module = ConfigParser.ConfigParser()
blank_module.read("file.txt")

Then access with blank_module.get('section1', 'property1')

vs
local_var = ConfigParser.ConfigParser()
local_var.read("file.txt")

blank_module.property1 = local_var.get('section1', 'property1')
blank_module.property2 = local_var.get('section1', 'property2')
etc...
then access with blank_module.property1

The second way would look more elegant when coming to access the parameters, but I'm unsure how they would differ in terms of performance.

A: I don't think that it is performance you should worry about here.  The issue is ease of use.  The users of the modules would probably find it more convenient to access the variables already extracted from the file instead of using the ConfigParser API.
Further, you can do error checking in the module so that you can account for problems reading your file:
import ConfigParser
local_var = ConfigParser.ConfigParser()
try:
    local_var.read("file.txt")
except (ConfigParser.Error, OSError) as e:
    # Error reading 'file.txt' or something like that

try:
    blank_module.property1 = local_var.get('section1', 'property1')
except ConfigParser.Error as e:
    # Handle the error
try:
    blank_module.property2 = local_var.get('section1', 'property2')
except ConfigParser.Error as e:
    # Handle the error
etc...


text:
Q: LNK1104 When trying to link with boost_filesystem*.lib I'm using CMake to create a cross platform project using some Boost libraries. I have used the following command to create the libraries.
.\b2.exe --prefix=C:/Boost install --with-python --with-system --with-filesystem address-model=32 toolset=msvc-12.0 link=shared threading=multi --layout=tagged --build-type=complete

The project links fine with the python and system libraries, but when it tries to link with the file system library, it fails. It is looking for "libboost_filesystem*.lib" (which doesn't exist) and then uses the "boost_python*.lib" and "boost_system*.lib" files with no problems.
My top level CMakeLists.txt is as follows:
file(GLOB SOURCES src/*.cpp)

add_subdirectory(shape)
add_subdirectory(py_shape)

#define sources and executable
set(EXECUTABLE_NAME "renderer2d")
add_executable(${EXECUTABLE_NAME} ${SOURCES})

#find python
find_package(PythonInterp)
find_package(PythonLibs 2.7 REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})

#detect and add SFML
#this line checks a cmake file for hints on where to find cmake
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules"     ${CMAKE_MODULE_PATH})
#find any version 2.x of SFML
#see the FindSFML.cmake file for additional details and instructions
find_package(SFML 2 REQUIRED system window graphics network audio)
include_directories(${SFML_INCLUDE_DIR})

#find and include Boost python libraries
set(Boost_USE_STATIC_LIBS OFF)
find_package(Boost COMPONENTS python system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})

#link all found libraries to the executable
target_link_libraries(${EXECUTABLE_NAME} ${PYTHON_LIBRARIES}     ${SFML_LIBRARIES} ${Boost_LIBRARIES} shape)

#install target
install(TARGETS ${EXECUTABLE_NAME} DESTINATION bin)

And my lone source file for this exe:
#include <iostream>
#include <SFML/Graphics.hpp>
#include "../shape/inc/Shape.hpp"
#include <boost/python.hpp>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::python;
using namespace boost::filesystem;

int main(int argc, char* argv[])
{
  try
  {
    Py_Initialize();

    //need to insert working directory into path
    path working_directory = absolute("./").normalize();
    PyObject* sys_path = PySys_GetObject("path");
    PyList_Insert(sys_path, 0,     PyString_FromString(working_directory.string().c_str()));

    sf::RenderWindow window(sf::VideoMode(800, 600), "renderer2d");
    Shape shape;
    shape.Initialize();

    while(window.isOpen())
    {
      sf::Event event;
      while(window.pollEvent(event))
      {
        if(event.type == sf::Event::Closed)
          window.close();
        if(event.type == sf::Event::KeyPressed)
        {
          if(event.key.code == sf::Keyboard::Q)
            window.close();
          else if(event.key.code == sf::Keyboard::U)
            shape.Update();
          else if(event.key.code == sf::Keyboard::S)
            shape.SetGreen(255);
        }
      }

      window.clear();
      window.draw(*shape.GetShape());
      window.display();
    }
  } catch(error_already_set){PyErr_Print();}

  return 0;
}

So, why would it be trying to link against "libboost_filesystem" rather than "boost_filesystem"?

A: The issue here is that Boost has an auto-linking feature which can be useful if you're not using CMake.
To disable this feature, you simply have to apply a preprocessor definition as shown in the table in the docs for Boost.Config:

BOOST_ALL_NO_LIB: Tells the config system not to automatically select which libraries to link against. Normally if a compiler supports #pragma lib, then the correct library build variant will be automatically selected and linked against, simply by the act of including one of that library's headers. This macro turns that feature off.

To add a preprocessor definition via CMake, you can use the target_compile_definitions command.  If you want to limit the definition to just the MSVC compiler for example, you can use a generator expression:
target_compile_definitions(${EXECUTABLE_NAME} PRIVATE $<$<BOOL:${MSVC}>:BOOST_ALL_NO_LIB>)


text:
Q: How can I enforce a numeric condition in the value of an EditText? How can I put condition in my EditText, the EditText is for age and should be a number.
So I want:

*

*put condition it is allow to the user to insert number from 1 to 100

*if the user insert more than 100, the EditText will be automatically 100

*retrieve the EditText value as string

This is my code:
package mm.app.pkg;

import android.app.Activity;     import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;

public class CreateNewForm extends Activity implements OnItemSelectedListener, InputFilter         {

Button Browse;
ImageView  CasePic;
Spinner CaseDurationH, CaseDurationM;
TextView tesst;
RadioGroup GenderSelection;
EditText CaseName, CaseClothes, CaseMoreInfo, CaseAge;
Button Next;
//For Browsering Picture
 private static final int SELECT_PICTURE = 1;
private String selectedImagePath;

 @Override
 protected void onCreate(Bundle savedInstanceState)
{

// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create_new_form);

//To Call initializer Function
initializer();

//j list

// 1-For Uploading Picture
Browse.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub
         // in onCreate or any event where your want the user to
        // select a file
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,
                "Select Picture"), SELECT_PICTURE);
    }
});

// 1-Name
final MyCase case1 = new MyCase();
case1.setName(CaseName.getText().toString());

// 2-Gender For Group Radio
GenderSelection.clearCheck();
GenderSelection.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    public void onCheckedChanged(RadioGroup group, int checkedId) {
         switch (checkedId) {
        case R.id.radio0:
            case1.setGender("Male");
            break;
        case R.id.radio1:
            case1.setGender("Female");
            break;
        default:
            break;
        }

    }
     });

   //3-Age
   String age = CaseAge.getText().toString();

   private int min, max;

   public void InputFilterMinMax(int min, int max) {
    this.min = min;
    this.max = max;
}

  public void InputFilterMinMax(String min, String max) {
    this.min = Integer.parseInt(min);
    this.max = Integer.parseInt(max);
}

     public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
       try {
        int input = Integer.parseInt(dest.toString() + source.toString());
        if (isInRange(min, max, input))
            return null;
    } catch (NumberFormatException nfe) { }
    return "";
   }

    private boolean isInRange(int a, int b, int c) {
    return b > a ? c >= a && c <= b : c >= b && c <= a;
   }
     CaseAge.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "100"))};

   /*int tstnum =case1.getAge();
   tesst.setText(tstnum); */

    //4-Duration Time
   ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
    this, R.array.feedbacktypelist, android.R.layout.simple_spinner_item);
   adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  CaseDurationH.setAdapter(adapter);

  //5-Case Clothes
 case1.setClothes(CaseClothes.getText().toString());

 //6-Case More Information
 case1.setMoreInfo(CaseMoreInfo.getText().toString());

 //Move to 2nd form page
 Next= (Button)findViewById(R.id.Next2);
 Next.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.Next2:
            try
            {
                 Intent k = new Intent(CreateNewForm.this, CreateNewForm_2.class);

                 startActivity(k);

            }catch(Exception e){

            }

            break;

        }
    }

   });

   //Spinner
   CaseDurationH.setOnItemSelectedListener(new OnItemSelectedListener() {
      int i =CaseDurationH.getSelectedItemPosition();
      public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
          int i = CaseDurationH.getSelectedItemPosition();

         if(i==2){
             CaseDurationM.setEnabled(false);
        }
         String str = parent.getSelectedItem().toString();

         if(str.equals("hr0"))
                {
            CaseDurationM.setEnabled(true);
            }

         if(str.equals("hr1"))
                {
            CaseDurationM.setEnabled(true);
             }

           if(str.equals("hr2"))
                   {
               CaseDurationM.setEnabled(false);
               }
       }
       public void onNothingSelected(AdapterView<?> arg0) {
          // TODO Auto-generated method stub

       } });

 }

 // To initialize the variables
 private void initializer() {
   // TODO Auto-generated method stub
   //This information will be filled by a user
           //CasePic = (ImageView) findViewById(R.id.imageView1);
           CaseName= (EditText) findViewById(R.id.caseNm);
           GenderSelection= (RadioGroup) findViewById(R.id.radioGroup1);
           CaseAge= (EditText) findViewById(R.id.caseaage);
           tesst= (TextView) findViewById(R.id.textView8);
           CaseDurationH= (Spinner) findViewById(R.id.Shr);
           CaseDurationM= (Spinner) findViewById(R.id.Smin);
            CaseClothes= (EditText) findViewById(R.id.caseClothes);
            CaseMoreInfo= (EditText) findViewById(R.id.caseMrInfo);
            CasePic = (ImageView) findViewById(R.id.casepic);
            Browse = (Button) findViewById(R.id.browseCasePic);
  }

//For Uploading Picture
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
        }
     }
}

 //For Uploading Picture
 public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
   Cursor cursor = managedQuery(uri, projection, null, null, null);
   int column_index = cursor
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
 }

 public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
      long arg3) {
    // TODO Auto-generated method stub

}

public void onNothingSelected(AdapterView<?> arg0) {
  // TODO Auto-generated method stub

}

public CharSequence filter(CharSequence source, int start, int end,
      Spanned dest, int dstart, int dend) {
   // TODO Auto-generated method stub
   return null;
 }

 }

A: First - it's not good idea to make those kind of checks manually - see, if the component that you're using - ExitText supports some sort of built-in validators.
Then - all after all, if you want to code the validation yourself - here's an example:
EditText CAge;
CaseAge= (EditText) findViewById(R.id.caage);
String age = CaseAge.getText().toString();
  if (Integer.parseInt(age) < 1) {
      //handle invalid value
     } else {
         if ((Integer.parseInt(age) > 100){
            CaseAge.setText("100");
              }
            }

Hope this helps.

A: try out below code which implements textWatcher which listens the text event of edittext so that you can control user while typing the text.
You can get value of editText by
String value= edt.getTest().toString();

and
edt.addTextChangedListener(new TextWatcher() {

             public void onTextChanged(CharSequence s, int start, int before, int count) {

             }
             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                 previous_text=s.toString();
                }
                  public void afterTextChanged(Editable s) {
                Integer.parse
                      int val= Integer.parseInt(s.toString());
                       if(val>100)
                            {
                             edt.setText("100");
                            }
                          if(val<0)
                            {
                             edt.setText("");
                            }

             }
               });

A: Here is your class fixed without imports insert your imports and try it out.
hope it helps.
EDIT: a simplified version of the activity to text with one EditText and the InputFilter class and it sure is working.
public class CreateNewForm extends Activity {
    EditText  CaseAge;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout
                 ll = new LinearLayout(this);
        CaseAge = new EditText(this) ;
        CaseAge.setWidth(69);
        ll.addView(CaseAge);
        setContentView(ll);
        CaseAge.setFilters(new InputFilter[]{new InputFilterMinMax(1, 100)});
    }
    class InputFilterMinMax implements InputFilter {
        private int min, max;
        public InputFilterMinMax(int min, int max) {
            this.min = min;
            this.max = max;
        }
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            try {
                int input = Integer.parseInt(dest.toString() + source.toString());
                if (isInRange(min, max, input))
                    return null;
            } catch (NumberFormatException nfe) {
            }
            return "";
        }

        private boolean isInRange(int a, int b, int c) {
            return b > a ? c >= a && c <= b : c >= b && c <= a;
        }
    }
}

public class CreateNewForm extends Activity implements OnItemSelectedListener {

    Button Browse;
    ImageView CasePic;
    Spinner CaseDurationH, CaseDurationM;
    TextView tesst;
    RadioGroup GenderSelection;
    EditText CaseName, CaseClothes, CaseMoreInfo, CaseAge;
    Button Next;
    //For Browsering Picture
    private static final int SELECT_PICTURE = 1;
    private String selectedImagePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_new_form);
//To Call initializer Function
        CaseName = (EditText) findViewById(R.id.caseNm);
        GenderSelection = (RadioGroup) findViewById(R.id.radioGroup1);
        CaseAge = (EditText) findViewById(R.id.caseaage);
        tesst = (TextView) findViewById(R.id.textView8);
        CaseDurationH = (Spinner) findViewById(R.id.Shr);
        CaseDurationM = (Spinner) findViewById(R.id.Smin);
        CaseClothes = (EditText) findViewById(R.id.caseClothes);
        CaseMoreInfo = (EditText) findViewById(R.id.caseMrInfo);
        CasePic = (ImageView) findViewById(R.id.casepic);
        Browse = (Button) findViewById(R.id.browseCasePic);

        final MyCase case1 = new MyCase();
        case1.setName(CaseName.getText().toString());

        GenderSelection.clearCheck();
        GenderSelection.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radio0:
                        case1.setGender("Male");
                        break;
                    case R.id.radio1:
                        case1.setGender("Female");
                        break;
                    default:
                        break;
                }
            }
        });

        Browse.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // in onCreate or any event where your want the user to
                // select a file
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,
                        "Select Picture"), SELECT_PICTURE);
            }
        });

        CaseAge.setFilters(new InputFilter[]{new InputFilterMinMax(1, 100)});
        CaseAge.setInputType(InputType.TYPE_CLASS_NUMBER);
//String age = CaseAge.getText().toString(); //not used anywhere

// CaseAge.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "100")}); //this one can be used too
        //4-Duration Time
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.feedbacktypelist, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        CaseDurationH.setAdapter(adapter);
        case1.setClothes(CaseClothes.getText().toString());
        case1.setMoreInfo(CaseMoreInfo.getText().toString());
        Next = (Button) findViewById(R.id.Next2);
        Next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.Next2:
                        try {
                            Intent k = new Intent(CreateNewForm.this, CreateNewForm_2.class);
                            startActivity(k);
                        } catch (Exception e) {
                        }
                        break;
                }
            }
        });

        //Spinner
        CaseDurationH.setOnItemSelectedListener(new OnItemSelectedListener() {
            int i = CaseDurationH.getSelectedItemPosition();

            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                int i = CaseDurationH.getSelectedItemPosition();

                if (i == 2) {
                    CaseDurationM.setEnabled(false);
                }
                String str = parent.getSelectedItem().toString();

                if (str.equals("hr0")) {
                    CaseDurationM.setEnabled(true);
                }

                if (str.equals("hr1")) {
                    CaseDurationM.setEnabled(true);
                }
                if (str.equals("hr2")) {
                    CaseDurationM.setEnabled(false);
                }
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
            }
        }
    }

    //For Uploading Picture
    public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                               long arg3) {
        // TODO Auto-generated method stub

    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

    class InputFilterMinMax implements InputFilter {

        private int min, max;

        public InputFilterMinMax(int min, int max) {
            this.min = min;
            this.max = max;
        }

        public InputFilterMinMax(String min, String max) {
            this.min = Integer.parseInt(min);
            this.max = Integer.parseInt(max);
        }

        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            try {
                int input = Integer.parseInt(dest.toString() + source.toString());
                if (isInRange(min, max, input))
                    return null;
            } catch (NumberFormatException nfe) {
            }
            return "";
        }

        private boolean isInRange(int a, int b, int c) {
            return b > a ? c >= a && c <= b : c >= b && c <= a;
        }
    }

}


text:
Q: System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID {58968145-CF05-4341-995F-2EE093F6ABA3} failed I am running a c# application and I am using DSOFile dll. This DLL is referenced in the project. I am able to run the exe in my development machine.
But when I run the exe in another machine, I am getting

Unhandled Exception: System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID {58968145-CF05-4341-995F-2EE093F6ABA3} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Not sure why I am getting this. Have googled and set the Platform target to x86
But still I am getting this issue. Any help would be great.

A:
This is a summary of our conversation that took place beneath the question.

80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

That means COM object you are trying to instantiate is a class that is not COM registered.  COM uses the registry to maintain class registrations.
Try doing a regsvr32.exe DSOFile.dll from the command-line with admin rights on the target system.

I dont remember doing this in my Dev machine. This makes me wondering is there something else I am missing

Yes, try the following check:
Quick check
I recommend using Microsoft's free tool OleView (normally installed with Visual Studio) to check all things COM but in the event you don't have it, open up RegEdit and see if the following key exists:
HKCR\CLSID\{58968145-CF05-4341-995F-2EE093F6ABA3}

If it's not present on the target machine, then DSOFile is not registered.
If it is there, expand the above key and you should see a child key called InprocServer32.  The (Default) value for this key will be the path to the DLL, in this case DSOFile.dll.
More
If you want to use OleView, take a look in:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\
Actual location may vary based on version of Visual Studio or Windows SDKs installed I suspect.
Once running, look in Automation Objects for your class.

Failing that, look in All Objects.


text:
Q: In React, how do I find the first item in a list that matches some criteria? I'm using React 16.13.  How do I find the first item in a list?  Sounds simple, but I tried
let value = next(country.id for country in countries if country.code == this.props.countryCode)

and it results in the error
./src/components/Country.jsx
  Line 9:37:  Parsing error: Unexpected token, expected ","

   7 |                 <option key={country.id} value={country.id}>{country.name}</option>
   8 |             );
>  9 |         let value = next(country.id for country in countries if country.code == this.props.countryCode)
     |                                     ^
  10 |

Here is my component in its entirety.  "countries" is a list of objects that each have a "code" and "id" attribute.
class Country extends React.Component {
    render () {
        let countries = this.props.options;
        let optionItems = countries.map((country) =>
                <option key={country.id} value={country.id}>{country.name}</option>
            );
        let value = next(country.id for country in countries if country.code == this.props.countryCode)

        return (
          <div className="form-group">
                <label htmlFor={this.props.name}> {this.props.title} </label>
            <select
                      id = {this.props.name}
                      name={this.props.name}
                      value={value}
                      onChange={this.props.handleChange}
                      className="form-control">
                      <option value="" disabled>{this.props.placeholder}</option>
                      {optionItems}
            </select>
          </div>
        )
    }
}

A: const found = countries.find(country => country.code === this.props.countryCode)

A: let value = country.filter(con=>(country.code === this.props.countryCode));

you can access the value of the desired result country like this
value[0].id;

A: Issue
The error is because it is expecting a comma separated list of function arguments, not several expressions.
Solution
Use array::find to search through an array and return the first element matching a criteria/predicate, or undefined if no match is found. Since undefined can be returned you'll need to check the result first before accessing properties, like code.
let countries = this.props.options;
let optionItems = countries.map((country) =>
  <option key={country.id} value={country.id}>{country.name}</option>
);

const country = countries.find(country => country.code === this.props.countryCode);
const countryCode = country ? country.code : null;

let value = next(country.id, countryCode);


text:
Q: traverse linklist using reference not working I am trying to make a queue list and I am passing reference of link list and its not working and giving error.

In function 'void insertDataToQueue(Node**, int)':|
   request for member 'next' in '* temp', which is of pointer type 'Node* {aka node*}' (maybe you meant to use '->' ?)|

 void insertDataToQueue(Node **queueList, int burstTime){
    Node *newNode = new Node;
    newNode->burstTime = burstTime;
    newNode->next = NULL;

if(queueList == NULL){
    *queueList = newNode;
}
else{
    Node **temp = queueList;
    while(*temp != NULL)
        temp = *temp->next;
}
}

A: To iterate over whole list, just a simple pointer to Node is enough :
void insertDataToQueue(Node **queueList, int burstTime){
    Node *newNode = new Node;
    newNode->burstTime = burstTime;
    newNode->next = NULL;

    if(queueList == NULL) {
        *queueList = newNode;
    }
    else {
        Node *temp = *queueList;
        // Find last element, ie element who "next" field is NULL
        while(temp->next != NULL) {
            temp = temp->next;
        }
        // Make last element to point to new element
        temp->next = newNode;
    }
}

Now, without any link, I suppose (and I hope) is only for learning aspect. Because C++ as every container you need. For exemple, you have std::list or std::queue who are linked list. For production code, prefer using it instead of developping by yourself.

A: This
*temp->next;

is parsed as
*(temp->next);

because -> has higher precedence than *, if you want to first dereference and then access the member you can use brackets:
(*temp)->next;


text:
Q: asymptotic growth of entire functions with positive taylor coefficients I have an entire function $g(x)$ with taylor coefficients that go to zero at a ridiculously fast rate and I am trying to bound it with another entire function $f$ with similar properties but with the added claim that $f(x) \sim x^{1-\epsilon}$ so that I can say $g(x) = o(x)$.
I need the coefficients of $f$ to be positive though.
For example I was thinking of a function like $$f(x) = \sum_{n=0}^{\infty} \frac{x^n}{n!^{n!}}$$ or something similar which must grow slowly.
I don't know how to prove this though, and was wondering if there was some technique or if another function would work better.


text:
Q: Is there a way to arrange objects into a table (or grid) using Inkscape from comand line? I like the functionality Inkscape has to arrange items into a table (or grid). However, I would like to use it programmatically, i mean toward a script. Indeed, I have several plots in a unique .svg file, let's call it "combined.svg" and i would like something like this:
inkscape -z -f combined.svg --verb EditSelectAll --verb DialogArrange ROWS COLS SPACING_X SPACING_Y --verb savefile

Where ROWS, COLS, SPACING_X and SPACING_Y would be integer parameters.
However, for the best of my knowledge i am not able of passing arguments to verbs neither use it without graphical interface.
Is there any way to achieve my goal?

A: No, that's not possible currently with Inkscape 0.92.4.
You can, however, write an Inkscape extension or a script in a language of your choice that can do that, and that you can run from the command line.

A: I've follow @Moini suggestion and I wrote down my own script in order to arrange svg files into a grid of a given number of rows and columns. To achieve my goal, I've used this Python library svg_stack. I provide my script below. To use it download the library, add a new python file just in the library directory and copy my script. Using python2.7, install the library ( python2.7 setup.py install ) and use it as I explain in the following example:
To layout 4 svg files (f1,f2,f3 and f4) into a table of 2 rows and 2 cols and save it to ft.svg use:
  pyhon2.7 name_you_give_to_the_script --rows=2 --cols=2 f1.svg f2.svg f3.svg f4.svg > ft.svg

from svg_stack import *

def main():
    usage = '''%prog FILE1 [FILE2] [...] [options]

This will concatenate FILE1, FILE2, ... to a new svg file. Also, this will arrange
the provided elements into a table which given number of rows and columns.
The table will be populated by rows.

EXAMPLE

To layout 4 svg files (f1,f2,f3 and f4) into a table of 2 rows and 2 cols and save it to ft.svg use:
  %prog --rows=2 --cols=2 f1.svg f2.svg f3.svg f4.svg > ft.svg

'''

    parser = OptionParser(usage, version=VERSION)
    parser.add_option("--rows",type='int',
                      help='number of grid rows (required)')
    parser.add_option("--cols",type='int',
                      help='number of grid cols (required)')
    parser.add_option("--spacing_x",type='str', help='size of margin (in any units, px default)')
    parser.add_option("--spacing_y",type='str', default='0px', help='size of margin (in any units, px default)')
    (options, args) = parser.parse_args()
    fnames = args

    if options.spacing_x is not None:
        spacing_x = convert_to_pixels(*get_unit_attr(options.spacing_x))
    else:
        spacing_x = 0

    if options.spacing_y is not None:
        spacing_y = convert_to_pixels(*get_unit_attr(options.spacing_y))
    else:
        spacing_y = 0

    if options.rows is None:
        raise ValueError('You must provide the number of rows that you want in the table')

    if options.cols is None:
        raise ValueError('You must provide the number of cols that you want in the table')

    if len(fnames) != options.rows * options.cols:
        raise ValueError('You must supply as much files as it requires to populate the table')

    doc = Document()
    layout = VBoxLayout()
    for i in range(options.rows):
        layout_row = HBoxLayout()
        for j in range(options.cols):
            fname = fnames[i * options.cols + j]
            layout_row.addSVG(fname, alignment=AlignCenter)

        layout_row.setSpacing(spacing_x)
        layout.addLayout(layout_row)
        layout.setSpacing(spacing_y)

    if 0:
        fd = open('tmp.svg',mode='w')
    else:
        fd = sys.stdout

    doc.setLayout(layout)
    doc.save(fd)

if __name__=='__main__':
    main()

Pd: I know that there may be more elegant solutions out there but I wasn't able to find one as simple as I wanted.


text:
Q: Cannot run bash script via php possible permissions I have ffmpeg installed on a CentOS 7 machine running a standard LAMP stack. I can run ffmpeg fine by itself in a terminal, like so:
ffmpeg -i "rtsp://admin:password@10.0.0.152/play2.sdp" camera1.mp4

I have a php script more or less like the following:
<?php
$camerabash = shell_exec('ffmpeg -i "rtsp://admin:password@10.0.0.152/play2.sdp" camera1.mp4');
echo $camerabash;
?>

The following gives me an echoed result of "apache":
<?php
$camerabash = shell_exec('whoami');
echo $camerabash;
?>

I think I have a permissions problem, and I've explored a few options including editing the http.conf file, nothing seems to work.


text:
Q: How do I optimize a loop which can be fully strict I'm trying to write a brute-force solution to Project Euler Problem #145, and I cannot get my solution to run in less than about 1 minute 30 secs.
(I'm aware there are various short-cuts and even paper-and-pencil solutions; for the purpose of this question I'm not considering those).
In the best version I've come up with so far, profiling shows that the majority of the time is spent in foldDigits. This function need not be lazy at all, and to my mind ought to be optimized to a simple loop. As you can see I've attempted to make various bits of the program strict.
So my question is: without changing the overall algorithm, is there some way to bring the execution time of this program down to the sub-minute mark?
(Or if not, is there a way to see that the code of foldDigits is as optimized as possible?)
-- ghc -O3 -threaded Euler-145.hs && Euler-145.exe +RTS -N4

{-# LANGUAGE BangPatterns #-}

import Control.Parallel.Strategies

foldDigits :: (a -> Int -> a) -> a -> Int -> a
foldDigits f !acc !n
    | n < 10    = i
    | otherwise = foldDigits f i d
  where (d, m) = n `quotRem` 10
        !i     = f acc m

reverseNumber :: Int -> Int
reverseNumber !n
    = foldDigits accumulate 0 n
  where accumulate !v !d = v * 10 + d

allDigitsOdd :: Int -> Bool
allDigitsOdd n
    = foldDigits andOdd True n
  where andOdd !a d = a && isOdd d
        isOdd !x    = x `rem` 2 /= 0

isReversible :: Int -> Bool
isReversible n
    = notDivisibleByTen n && allDigitsOdd (n + rn)
  where rn                   = reverseNumber n
        notDivisibleByTen !x = x `rem` 10 /= 0

countRange acc start end
    | start > end = acc
    | otherwise   = countRange (acc + v) (start + 1) end
  where v = if isReversible start then 1 else 0

main
    = print $ sum $ parMap rseq cr ranges
  where max       = 1000000000
        qmax      = max `div` 4
        ranges    = [(1, qmax), (qmax, qmax * 2), (qmax * 2, qmax * 3), (qmax * 3, max)]
        cr (s, e) = countRange 0 s e

A: As it stands, the core that ghc-7.6.1 produces for foldDigits (with -O2) is
Rec {
$wfoldDigits_r2cK
  :: forall a_aha.
     (a_aha -> GHC.Types.Int -> a_aha)
     -> a_aha -> GHC.Prim.Int# -> a_aha
[GblId, Arity=3, Caf=NoCafRefs, Str=DmdType C(C(S))SL]
$wfoldDigits_r2cK =
  \ (@ a_aha)
    (w_s284 :: a_aha -> GHC.Types.Int -> a_aha)
    (w1_s285 :: a_aha)
    (ww_s288 :: GHC.Prim.Int#) ->
    case w1_s285 of acc_Xhi { __DEFAULT ->
    let {
      ds_sNo [Dmd=Just D(D(T)S)] :: (GHC.Types.Int, GHC.Types.Int)
      [LclId, Str=DmdType]
      ds_sNo =
        case GHC.Prim.quotRemInt# ww_s288 10
        of _ { (# ipv_aJA, ipv1_aJB #) ->
        (GHC.Types.I# ipv_aJA, GHC.Types.I# ipv1_aJB)
        } } in
    case w_s284 acc_Xhi (case ds_sNo of _ { (d_arS, m_Xsi) -> m_Xsi })
    of i_ahg { __DEFAULT ->
    case GHC.Prim.<# ww_s288 10 of _ {
      GHC.Types.False ->
        case ds_sNo of _ { (d_Xsi, m_Xs5) ->
        case d_Xsi of _ { GHC.Types.I# ww1_X28L ->
        $wfoldDigits_r2cK @ a_aha w_s284 i_ahg ww1_X28L
        }
        };
      GHC.Types.True -> i_ahg
    }
    }
    }
end Rec }

which, as you can see, re-boxes the result of the quotRem call. The problem is that no property of f is available here, and as a recursive function, foldDigits cannot be inlined.
With a manual worker-wrapper transform making the function argument static,
foldDigits :: (a -> Int -> a) -> a -> Int -> a
foldDigits f = go
  where
    go !acc 0 = acc
    go acc n = case n `quotRem` 10 of
                 (q,r) -> go (f acc r) q

foldDigits becomes inlinable, and you get specialised versions for your uses operating on unboxed data, but no top-level foldDigits, e.g.
Rec {
$wgo_r2di :: GHC.Prim.Int# -> GHC.Prim.Int# -> GHC.Prim.Int#
[GblId, Arity=2, Caf=NoCafRefs, Str=DmdType LL]
$wgo_r2di =
  \ (ww_s28F :: GHC.Prim.Int#) (ww1_s28J :: GHC.Prim.Int#) ->
    case ww1_s28J of ds_XJh {
      __DEFAULT ->
        case GHC.Prim.quotRemInt# ds_XJh 10
        of _ { (# ipv_aJK, ipv1_aJL #) ->
        $wgo_r2di (GHC.Prim.+# (GHC.Prim.*# ww_s28F 10) ipv1_aJL) ipv_aJK
        };
      0 -> ww_s28F
    }
end Rec }

and the effect on computation time is tangible, for the original, I got
$ ./eul145 +RTS -s -N2
608720
1,814,289,579,592 bytes allocated in the heap
     196,407,088 bytes copied during GC
          47,184 bytes maximum residency (2 sample(s))
          30,640 bytes maximum slop
               2 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0     1827331 colls, 1827331 par   23.77s   11.86s     0.0000s    0.0041s
  Gen  1         2 colls,     1 par    0.00s    0.00s     0.0001s    0.0001s

  Parallel GC work balance: 54.94% (serial 0%, perfect 100%)

  TASKS: 4 (1 bound, 3 peak workers (3 total), using -N2)

  SPARKS: 4 (3 converted, 0 overflowed, 0 dud, 0 GC'd, 1 fizzled)

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time  620.52s  (313.51s elapsed)
  GC      time   23.77s  ( 11.86s elapsed)
  EXIT    time    0.00s  (  0.00s elapsed)
  Total   time  644.29s  (325.37s elapsed)

  Alloc rate    2,923,834,808 bytes per MUT second

(I used -N2 since my i5 only has two physical cores), vs.
$ ./eul145 +RTS -s -N2
608720
  16,000,063,624 bytes allocated in the heap
         403,384 bytes copied during GC
          47,184 bytes maximum residency (2 sample(s))
          30,640 bytes maximum slop
               2 MB total memory in use (0 MB lost due to fragmentation)

                                    Tot time (elapsed)  Avg pause  Max pause
  Gen  0     15852 colls, 15852 par    0.34s    0.17s     0.0000s    0.0037s
  Gen  1         2 colls,     1 par    0.00s    0.00s     0.0001s    0.0001s

  Parallel GC work balance: 43.86% (serial 0%, perfect 100%)

  TASKS: 4 (1 bound, 3 peak workers (3 total), using -N2)

  SPARKS: 4 (3 converted, 0 overflowed, 0 dud, 0 GC'd, 1 fizzled)

  INIT    time    0.00s  (  0.00s elapsed)
  MUT     time  314.85s  (160.08s elapsed)
  GC      time    0.34s  (  0.17s elapsed)
  EXIT    time    0.00s  (  0.00s elapsed)
  Total   time  315.20s  (160.25s elapsed)

  Alloc rate    50,817,657 bytes per MUT second

  Productivity  99.9% of total user, 196.5% of total elapsed

with the modification. The running time roughly halved, and the allocations reduced 100-fold.


text:
Q: Does OS X 10.7 support TRIM (SSD)? With OS X 10.6 I had massive problems with an SSD – it became slower and slower with each day. At the end I replaced it with a classical hard disk and it was quite fast again.
Now I want to know if at least OS X 10.7 supports TRIM to prevent SSD performance decreasing over time?

A: From what I've seen, official TRIM support is limited to Apple-supplied SSDs, but Trim Enabler still works.  (Reference Discussion)

A: Hmm, OS X Lion says no TRIM support for my OCZ Vertex2.
Thankfully this SSD controller has good garbage collection routines. Didn't notice a slowdown on OS X Snow Leopard (10.6), so I'm not too worried.

A: Hi yes Lion does support TRIM, if you look at the link below you can see a post with evidence.
http://osxdaily.com/2011/02/25/mac-os-x-lion-supports-trim-for-ssds/


text:
Q: yum + what is the safety approach to remove all rpm's from i686 type from rhel 7.x version machines We want to remove the following rpm from all production machines servers , we have more the 152 servers machines ( rhel 7.6 ) , all Linux are x86_64 architecture,
yum  remove *.i686  -y

this yum command will capture the rpm from i686 type ( by use the "*" ) and remove them all
since we are using the "*" , I little worry if this approach is safety to remove the i686 rpm's  ,
my concern are

*

*dose yum command - yum  remove *.i686   removes also other rpm's from *.x86_64 type that are in dependency with the rpm from i686 ?

*what are the other option/s that maybe more safe to remove the rpm's fro  i686 type without using "*"

A: *

*Yes, it will — if an x86_64 RPM depends on an i686 RPM, it will be removed, same as any other dependency.

*The safest option is to leave these packages alone. However, you can instruct yum to remove a package as long as it doesn't affect any x86_64 package by running
 yum remove '*.i686' -x '*.x86_64'

and variants thereof.


text:
Q: JS/jQuery check if element is typable I would like to check if an element is able to be typed into, specifically document.activeElement so that I can use shift+key as keyboard shortcuts without obstructing user's abilities to type in whatever input may be focused upon.
How would I go about deciding whether an element is able to typed into?

A: Use isContentEditable property
$('my-element-selector').is('[contenteditable="true"]')

or
$('my-element-selector').get(0).isContentEditable

Or try this fiddle

<input id='inp1' type='text'>

function isEditable($element)
{
  return $element.is( "input:text:not(:disabled):not([readonly]), textarea:text:not(:disabled):not([readonly])" ) ;
}

console.log( isEditable( $('#el1') ) );
console.log( isEditable( $('#inp1') ) );

Updated the fiddle again to add support for more input ty
function isEditable($element)
{
  return $element.is( "input[type!='radio'][type!='checkbox'][type!='date']:not(:disabled):not([readonly]), textarea:text:not(:disabled):not([readonly])" ) ;
}

A: If you check document.activeElement.tagName you can decide whether the element is an input or it is a text area.
if it is input, check for $(document.activeElement).attr("type") which will give you the type of input. if it is not button, radio, checkbox etc, then it is an editable input field.
Also if $(document.activeElement).attr("contenteditable") is true then it will be an editable field.


text:
Q: Find input box of a specific type as well as its value Please take a look at this fiddle.
I can use the following to find an input box with a specific value:
$('input[value="'+findtext+'"]');

but is it possible to find an input box of a specific type as well? This one won't work in the example:
$('input[type="checkbox" value="'+findtext+'"]');

HTML:
<button class="check">AAA</button>

<input type="radio" value="AAA">This
<input type="checkbox" value="BBB">This

Script:
$('.check').click(function(){
   var findtext = $(this).text();console.log(findtext);
   $('input[type="checkbox" value="'+findtext+'"]').attr('checked', true);

});

A: Sounds like this will do the trick:  $('input[value="BBB"][type=checkbox]')
Online Demo
$('.check').click(function(){
   var findtext = $(this).text();console.log(findtext);
   $('input[value="' + findtext  + '"][type=checkbox]').attr('checked', true);
});

This is subject of multiple attribute selectors with JQuery in case you want to read more about it.


text:
Q: Spring - Accessing parameters of annotation in Advice I have the following annotation:
public @interface Log {
    int id() default 0;
}

Now, I want to access the id field in an advice method. For example, if I call foo, then it's id (1) should get printed.
@Log(id = 1)
public void foo() {}

So far, I've got this :
@Pointcut("@annotation(com.skyfall.aspects.Log)")
    public void logPointcut(com.skyfall.aspects.Log log) {}

@Before("logPointcut(log))")
public void logBefore(JoinPoint joinPoint, com.skyfall.aspects.Log log) {
    System.out.println(log.id());
    }

However, I an error saying "when using @annotation(annotationtype(annotation field)) annotation field must be bound"

A: Your code should be like this, because you are using the pointcut with its binding form format where you use just the parameter name and the type of the annotation is taken from the logBefore method:
@Pointcut("@annotation(log)")
public void logPointcut(com.skyfall.aspects.Log log) {}

@Before("logPointcut(log))")
public void logBefore(JoinPoint joinPoint, com.skyfall.aspects.Log log) {
    System.out.println(log.id());
}


text:
Q: Find $\det(\mathrm{I} - 2\mathrm{P})$ where $\mathrm{P}\mathrm{P} = \mathrm{P}$ is a projection matrix Let $\mathrm{P}$ be a well-defined $n\times n$ projection matrix and $\mathrm{I}$ be the identity matrix. What is the determinant of the following reflection matrix?
$$
\mathrm{R} = \mathrm{I} - 2\mathrm{P}
$$

Important: The projection matrix in my case is always defined as $\mathrm{P} = \mathrm{A}^\top(\mathrm{A}\mathrm{A}^\top)^{-1}\mathrm{A}$ where $\mathrm{A}$ is a full row-rank $m\times n$ matrix with $n > m$.

Attempt following comments
The determinant of $\mathrm{R}$ is the product of its eigenvalues
$$
\det(\mathrm{R}) = \prod_{i=1}^n \lambda_i.
$$
Any non-zero vector $v\in\mathbb{R}^n$ such that
$$
\mathrm{R}v = \lambda v
$$
is an eigenvector with eigenvalue $\lambda$. This can be written
$$
(\mathrm{R} - \lambda \mathrm{I}) v = 0
$$
which has a non-zero solution only if $\det((1-\lambda)\mathrm{I} - 2\mathrm{P}) = 0$. However I am not sure how to show this.

A: The eigenvalues of $P$ are $0$ and $1$, with the multiplicity of $1$ equal to the rank of $P$.  It follows that the eigenvalues of $I - 2 P$ are $1 - 2(0) = 1$ and $1 - 1(1) = -1$, with the multiplicity of $-1$ equal to the rank of $P$.
Because the determinant of a matrix is the product of its eigenvalues, we have
$$
\det(I - 2P) = 1^{n - \operatorname{rank}(P)} (-1)^{\operatorname{rank}(P)} = (-1)^{\operatorname{rank}(P)}.
$$

A: let $R=I-2P, \;P^2=P$
$det(PR)=det(P(I-2P))\\=det(P-2P^2)=det(P-2P)\\=det(-P)=det(P)det(R)$
now $det(-P)=det(-IP)\\=det(-I)det(P)=-det(P)$
thus:
$det(R)=(-1)^n$.


text:
Q: How to drop a table if it exists? The table name is Scores.
Is it correct to do the following?
IF EXISTS(SELECT *
          FROM   dbo.Scores)
  DROP TABLE dbo.Scores

A: Have seen so many that don't really work.
when a temp table is created it must be deleted from the tempdb!
The only code that works is:
IF OBJECT_ID('tempdb..#tempdbname') IS NOT NULL     --Remove dbo here
    DROP TABLE #tempdbname   -- Remoeve "tempdb.dbo"

A: IF EXISTS (SELECT NAME FROM SYS.OBJECTS WHERE object_id = OBJECT_ID(N'Scores') AND TYPE in (N'U'))
    DROP TABLE Scores
GO

A: SQL Server 2016 and above the best and simple one is
DROP TABLE IF EXISTS [TABLE NAME]
Ex:
DROP TABLE IF EXISTS dbo.Scores

if suppose the above one is not working then you can use the below one
IF OBJECT_ID('dbo.Scores', 'u') IS NOT NULL
DROP TABLE dbo.Scores;

A: From SQL Server 2016 you can use
DROP TABLE IF EXISTS dbo.Scores

Reference: DROP IF EXISTS - new thing in SQL Server 2016
It will be in SQL Azure Database soon.

A: In SQL Server 2016 (13.x) and above
DROP TABLE IF EXISTS dbo.Scores

In earlier versions
IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL
DROP TABLE dbo.Scores;

U is your table type

A: I use:
if exists (select *
           from sys.tables
           where name = 'tableName'
           and schema_id = schema_id('dbo'))
begin
    drop table dbo.tableName
end

A: Or:
if exists (select * from sys.objects where name = 'Scores' and type = 'u')
    drop table Scores

A: I hope this helps:
begin try drop table #tempTable end try
begin catch end catch

A: I wrote a little UDF that returns 1 if its argument is the name of an extant table, 0 otherwise:
CREATE FUNCTION [dbo].[Table_exists]
(
    @TableName VARCHAR(200)
)
    RETURNS BIT
AS
BEGIN
    If Exists(select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = @TableName)
        RETURN 1;

    RETURN 0;
END

GO

To delete table User if it exists, call it like so:
IF [dbo].[Table_exists]('User') = 1 Drop table [User]

A: Make sure to use cascade constraint at the end to automatically drop all objects that depend on the table (such as views and projections).
drop table if exists tableName cascade;

A: The ANSI SQL/cross-platform way is to use the INFORMATION_SCHEMA, which was specifically designed to query meta data about objects within SQL databases.
if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Scores' AND TABLE_SCHEMA = 'dbo')
    drop table dbo.Scores;

Most modern RDBMS servers provide, at least, basic INFORMATION_SCHEMA support, including: MySQL, Postgres, Oracle, IBM DB2, and Microsoft SQL Server 7.0 (and greater).

A:
Is it correct to do the following?
IF EXISTS(SELECT *
          FROM   dbo.Scores)
  DROP TABLE dbo.Scores

No.  That will drop the table only if it contains any rows (and will raise an error if the table does not exist).
Instead, for a permanent table you can use
IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL
  DROP TABLE dbo.Scores;

Or, for a temporary table you can use
IF OBJECT_ID('tempdb.dbo.#TempTableName', 'U') IS NOT NULL
  DROP TABLE #TempTableName;

SQL Server 2016+ has a better way, using DROP TABLE IF EXISTS …. See the answer by @Jovan.

A: Simple is that:
IF OBJECT_ID(dbo.TableName, 'U') IS NOT NULL
DROP TABLE dbo.TableName

where dbo.TableName is your desired table and 'U' is type of your table.

A: If you use long codes and want to write less for temporary table create this procedure:
CREATE PROCEDURE MF_DROP (@TEMP AS VARCHAR(100)) AS
    EXEC('IF OBJECT_ID(''TEMPDB.DBO.' + @TEMP + ''', ''U'') IS NOT NULL DROP TABLE ' + @TEMP)

In execution:
EXEC MF_DROP #A
CREATE TABLE #A (I INT) ....

A: A better visual and easy way, if you are using Visual Studio, just open from menu bar,

View -> SQL Server Object Explorer

it should open like shown here

Select and Right Click the Table you wish to delete, then delete. Such a screen should be displayed. Click Update Database to confirm.

This method is very safe as it gives you the feedback and will warn of any relations of the deleted table with other tables.


text:
Q: Points are not adding up in my score system I am currently working on a scoring system for my game application and for some reason points are not adding up. The goal is whenever the player guesses the correct answer, points are added. For each new player, the score is set to 0.
question#validate_answer:
def validate_answer
  @correct_answer = Answer.where(correct: true).map(&:text)
  @selected_answer = params[:answer]
  @player_score = Player.where(id: params[:id]).map(&:score)

  if @correct_answer.include? (@selected_answer)
    @player_score[0] += 1
    render :success
  else
    render :error
  end
end

Quesiton.rb
    class Question < ActiveRecord::Base
    belongs_to :category

    has_many :answers

    has_one :video_clue
     has_many :answers

    def correct_answer
    answers.find_by correct: true
    end

   end

Answer.rb
   class Answer < ActiveRecord::Base
   belongs_to :question

   end

Player.rb
 class Player < ActiveRecord::Base
has_secure_password

def admin?
    self.admin == 'admin'
end

end

Schema Tables for Answers and Players
create_table "answers", force: :cascade do |t|
t.integer  "question_id"
t.string   "text"
t.boolean  "correct"
t.datetime "created_at"
t.datetime "updated_at"
end

add_index "answers", ["question_id"], name: "index_answers_on_question_id",   using: :btree

create_table "players", force: :cascade do |t|
t.string   "user_name"
t.string   "password_digest"
t.integer  "score"
t.string   "role"
t.datetime "created_at",      null: false
t.datetime "updated_at",      null: false
end

A: I would restructure the code the like this:
def validate_answer
  @question = Question.find(params[:q_id])
  @correct_answer = Answer.find_by_question_id(params[:q_id]).text.downcase
  @selected_answer = params[:answer].downcase
  @player = Player.find(params[:id])

  if @selected_answer == @correct_answer
    @player.increment!(:score)
    render :success
  else
    render :error
  end
end

increment! automatically pings the @player object for the column specified. It saved the trouble of trying to convert it to an array and access the index which was sort of roundabout.
NOTE: Edited Answer per chat conversation.

A: just see how less lines of code are need to be done for that
def validate_answer
  #i think this is a bad approach to compare the text of the answer
  #with the text of the given answer
  #the better one would be to assing UUID to the answer or just use the regular ID
  # something like this params[:answer][:uuid]
  # or params[:answer][:id]

  # we need to find the answer related to the question, otherwise we
  # could throw in just random IDs and they are still saying "correct"
  given_answer = Questions.find(params[:question_id]).answers.find params[:answer][:id]
  # if we use UUID we dont need to give the question id, since then the ID can't be guessed

  if given_answer.correct?
    # current_user is a player.
    # current_user is a method from devise (u should use devise)
    current_user.award_points! given_answer
    render :success
  else
    ender :error
  end
end

class Player

  def award_points! answer
    # adding the points to the user
    # and save it

    current_user.award_points += answer.points
    current_user.save

    #better approach would be to save the question which was answered for the user
    # like has_many :answered_questions
    # so then u could also track which questions already been answered by the user and not awarding him twice
  end

end


text:
Q: Dynamic array of structure in C I am trying to create a dynamic array of structures using malloc(). I have looked at some other answers already on this forum, but I got lost in answers that weren't the same from one question to the next. Here's what I did so far:
//This is above main()

struct linesegs
{
float*X;
float*Y;
float*Z;
float*Q;
float*R;
float*S;
};

struct linesegs *LINE;

//Inside main() I have this:

LINE = malloc((facets*3)*sizeof(linesegs));

//Later on I access the struct like so:

LINE[variable].X = SomeFloatNumber
LINE[variable].Y = SomeFloatNumber
LINE[variable].Z = SomeFloatNumber
LINE[variable].Q = SomeFloatNumber
LINE[variable].R = SomeFloatNumber
LINE[variable].S = SomeFloatNumber

From what I have read the above should be very close to correct, but my compliler underlined the = in LINE = malloc((facets*3)*sizeof(linesegs)); and gives the following error:
A value of type "void*" cannot be assigned to an entity of type "linesegs"
The places I learned this from were not exactly clear what goes where, and in what order they should go. I tried moving stuff around and playing with the pointers to no avail. Hopefully this question will help others (and me) by providing one solid answer with no confusion =). Thanks in advance for help with this.

A: would this solve the error or warning?
LINE = (struct linesegs *)malloc((facets*3)*sizeof(struct linesegs));


text:
Q: Foreach array with Perl It seems my code cannot iterate over an array stored in a hash.
What did I miss ?
#!/usr/bin/env perl
use Data::Dumper;

my $data = {array   => ['a', 'b', 'c']};

my @array = $data->{array};
print Dumper(@array); # It looks like $data->{array} is an array

print "Ref: ".ref($data->{array})."\n"; # And this array is indeed an array

foreach ($data->{array}) { print "$_\n"; } # But this doesn't work
foreach (@array) { print "$_\n"; } # Neither this one

# But with a regular array it works...
my @myNames = ('Larry', 'Curly', 'Moe');
foreach (@myNames) { print "$_\n"; }

My output:
$VAR1 = [
          'a',
          'b',
          'c'
        ];
$VAR1 = 'a';
Ref: ARRAY
ARRAY(0x8002bcf8)
ARRAY(0x8002bcf8)
Larry
Curly
Moe

I am pretty confused with REF/SCALAR types. Sometime Perl takes values as references sometime not. In this case, because I get 'ARRAY' from the ref function, I guess $->{array} doesn't give me an array but a reference to the array.
I have also tried @$data->{array} without success.

A: $data->{array} is indeed an array reference.
To dereference it, use @{} on the reference
foreach (@{$data->{array}}) { print "$_\n"; }

Edit:
Or if you dont want to use {...} after @
my $arrayref = $data->{array};

foreach (@$arrayref ) { print "$_\n"; }


text:
Q: Function for moving arrays in C++ I am trying to make a function that will move the parts of an array (which is made of widgets) around a circle. It builds and runs but the icons do not appear. Can someone tell me why?
Here is the function in the .cpp file
    void setIconWidgetLocation(iconWidget *w, float arcSize)
{
    int outerRadius = 100;
    int innerRadius = 60;
    int radius = (outerRadius + innerRadius)/2;
    arcSize = 2.0 * M_PI/ 5;

    iconWidget *icon[5];

    QSizeF size = w->size();
    QPointF center(size.width(),size.height());
    center /= 2.0;

    //Loop for finding the circles and moving them
    for(int i = 0; i<5; i++)
    {
        icon[i] = new iconWidget;

        //Finding the Icon center on the circle
        double x = center.x() + radius * sin(arcSize * i);
        double y = center.y() + radius * cos(arcSize * i);

        x -= 10/2;
        y -= 10/2;

        //moves icons into place
        icon[i]->move(x,y);

    }
}

and here is the header file
#ifndef ZMENUWIDGET_H
#define ZMENUWIDGET_H
#include "iconwidget.h"

#include <QWidget>

class zMenuWidget : public QWidget
{
    Q_OBJECT

    iconWidget *icon[5];

public:
    explicit zMenuWidget(QWidget *parent = 0);

    void paintEvent(QPaintEvent *event);

    void resizeEvent(QResizeEvent *event);

signals:

public slots:

};

#endif // ZMENUWIDGET_H

here is the call of the setIconWidgetLocation.
#include "zmenuwidget.h"
#include <QPaintEvent>
#include <QResizeEvent>
#include <QPainter>
#include <QColor>
#include <QPainterPath>
#include <cmath>

setIconWidgetLocation(iconWidget *w, float arcSize);

zMenuWidget::zMenuWidget(QWidget *parent) :
    QWidget(parent)
{

}

A: You don't actually call the function.  What you have shown is a function declaration (aka prototype).  All it does is tell the compiler that your function exists and states how it is called.
Before I go there, you have a few things to iron out first.  Namely, the parameters don't make sense.  Your function creates and lays out icons for your menu.  So passing in an iconWidget is confusing.  Also, you pass arcSize but then calculate it inside the function.  I expect that this function should actually be a member of zMenuWidget.  Finally, it doesn't just set the locations, it also creates the icons, so the naming is misleading.
Let's address all these things in one hit:
void zMenuWidget::createAndLayoutIcons()
{
    int outerRadius = 100;
    int innerRadius = 60;
    int radius = (outerRadius + innerRadius)/2;
    double arcSize = 2.0 * M_PI/ 5;

    QSizeF size = w->size();
    QPointF center(size.width(),size.height());
    center /= 2.0;

    //Loop for finding the circles and moving them
    for(int i = 0; i<5; i++)
    {
        icon[i] = new iconWidget(this);

        //Finding the Icon center on the circle
        double x = center.x() + radius * sin(arcSize * i);
        double y = center.y() + radius * cos(arcSize * i);

        x -= 10/2;
        y -= 10/2;

        //moves icons into place
        icon[i]->move(x,y);
    }
}

Notice that I have removed the locally-defined icon array from this function, because it's defined in your zMenuWidget class.  That's the other hint that you needed to make your function a member of the class.
I also modified the icon creation part to pass the menu widget's pointer to your new icon widget (as its parent).  I assume your iconWidget accepts a parent pointer:
        icon[i] = new iconWidget(this);

Now in the constructor for zMenuWidget, you create your icons:
zMenuWidget::zMenuWidget( QWidget *parent)
    : QWidget(parent)
{
    createAndLayoutIcons(this);
}

That should get you moving in the right direction.


text:
Q: mean stack yo generator gives error when creating a new app I am using mac OSx yosemit and I have installed bitnami mean stack package.
when i want to create a new app using generator it gives an error about v8-debugger.
Here are steps;
 1. sudo npm install -g yo
 2. npm install -g generator-meanjs
 3. mkdir test & cd test/
 4. yo meanjs

this asks me some questions about app and then starts to install required packages. It end with following error
 > v8-profiler@5.2.12 install /Users/tahir/Developer/mean_stack/yo_app/node_modules/grunt-node-inspector/node_modules/node-inspector/node_modules/v8-profiler
> node-pre-gyp install --fallback-to-build

[v8-profiler] Success: "/Users/tahir/Developer/mean_stack/yo_app/node_modules/grunt-node-inspector/node_modules/node-inspector/node_modules/v8-profiler/build/profiler/v5.2.12/node-v14-darwin-x64/profiler.node" is installed via remote
npm ERR! Darwin 14.5.0
npm ERR! argv "/Applications/meanstack-3.0.4-2/nodejs/bin/.node.bin" "/Applications/meanstack-3.0.4-2/nodejs/bin/npm" "install"
npm ERR! node v0.12.7
npm ERR! npm  v2.11.2
npm ERR! code ELIFECYCLE

npm ERR! v8-debug@0.4.6 install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the v8-debug@0.4.6 install script 'node-pre-gyp install --fallback-to-build'.
npm ERR! This is most likely a problem with the v8-debug package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-pre-gyp install --fallback-to-build
npm ERR! You can get their info via:
npm ERR!     npm owner ls v8-debug
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/tahir/Developer/mean_stack/yo_app/npm-debug.log

I can't figure out what is problem I referred to some solutions like a discussion here https://github.com/node-inspector/node-inspector/issues/662 but unable to solve this issue.
Thanks for your help!


text:
Q: Trying to write an embedded sql in php. can't figure out this syntax error I've been sitting for some time behind the screen trying to fix this code. whenever i run it i get a syntax error indicating to the last line of the code. What i'm trying to do is write a web based database where i can add, update, delete, and retrieve information from the database.

    <title></title>

<?= $_POST["type"];?>
<?php $sel=$_POST["select"];?>
<?php if($_POST["type"]=="fm"){

    if($sel=="addnew"){

    try {
                $db = new PDO("mysql:dbname=university", "root", "");
                $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $rows=$db->query("INSERT INTO fminformationtable
                VALUES('$_POST[iden]','$_POST[lname]','$_POST[fname]','$_POST[office]','$_POST[ext]','$_POST[hphone]','$_POST[mobile]','$_POST[address]','$_POST[email]','$_POST[syear]','$_POST[tyear]','$_POST[ldegree]','$_POST[ofrom]','$_POST[dyear]','$_POST[rinterest]')");

            }
            catch (PDOException $ex) {
            ?>

Sorry there was an Error in Adding

            <?php
            }
            if($sel=="update"){

                try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                    $rows=$db->query("UPDATE fminformationtable SET
                     Office=`$_POST[office]`,
                     Extension=`$_POST[ext]`,
                     HomePhone=`$_POST[hphone]',
                     MobilePhone=`$_POST[mobile]`,
                     Adress=`$_POST[address]`,
                     Email=`$_POST[email]`,
                     StartingYear=`$_POST[syear]`,
                     TerminationYrear=`$_POST[tyear]`,
                     LatestDegree=`$_POST[ldegree]`,
                     ObtainedFrom=`$_POST[ofrome]`,
                     DegreeYear=`$_POST[dyear]`,
                     ResearchInterest=`$_POST[rinterest]`

                    ");

                    }

                catch (PDOException $ex) {

                }
        }
         if($sel=="delete"){
            try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $rows = $db->exec("DELETE FROM fminformationtable WHERE FM_ID = '$_POST[iden]'");

            }
            catch (PDOException $ex) {

                }
        }

        if($sel=="getinfo"){
                    try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $rows = $db->exec("SEEELECT * FROM fminformationtable WHERE FM_ID = '$_POST[iden]'");

                    }

            catch (PDOException $ex) {

                }

        }

    }
}
if($_POST["type"]=="ct"){
    if($sel=="addnew"){

    try {
        $db = new PDO("mysql:dbname=university", "root", "");
                $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $rows=$db->query("INSERT INTO coursetable
                VALUES('$_POST[cnum]','$_POST[ctitle]','$_POST[credits]','$_POST[semester]','$_POST[type]','$_POST[desc]','$_POST[outcomes]')");

    }
        catch (PDOException $ex) {

                }
}

                    if($sel=="update"){

                try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                    $rows=$db->query("UPDATE coursetable SET
                    CourseNumber=`$_POST[cnum]`,
                    CourseTitle=`$_POST[ctitle]`,
                    CreditNumb=`$_POST[credits]`,
                    SemesterOffered=`$_POST[semester]`,
                    CourseType=`$_POST[ctype]`,
                    CourseDescription=`$_POST[desc]`,
                    LearningOut=`$_POST[outcomes]`
                    ");

            }
            catch (PDOException $ex) {

                }
        }

         if($sel=="delete"){
            try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $rows = $db->exec("DELETE FROM coursetable WHERE CourseNumber = '$_POST[cnum]'");

            }
            catch (PDOException $ex) {

                }

            }

                if($sel=="getinfo"){
                    try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $rows = $db->exec("SEEELECT * FROM coursetable WHERE CourseNumber = '$_POST[cnum]'");

                    }

            catch (PDOException $ex) {
                }
        }

            }

            if($_POST["type"]=="ch"){

                if($sel=="addnew"){

                try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $rows=$db->query("INSERT INTO coursehistory
                VALUES('$_POST[cnum]','$_POST[year]','$_POST[semester]','$_POST[sec]','$_POST[inID]','$_POST[comments]' )");
            }
                catch (PDOException $ex) {
                }
            if($sel=="update"){

                try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $rows=$db->query("UPDATE coursetable SET
                    AcademicYear=`$_POST[year]`,
                    Semester=`$_POST[semester]`,
                    InstructorID=`$_POST[inID]`,
                    Section=`$_POST[sec]`,
                    Comments=`$_POST[comments]`
                    WHERE CourseNumber=`$_POST[cnum]`;");

                    }
                    catch (PDOException $ex) {

                }

            }
            if($sel=="delete"){
            try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $rows = $db->exec("DELETE FROM coursehistory WHERE CourseNumber = '$_POST[cnum]'");

            }
            catch (PDOException $ex) {

                }

            }
                if($_POST["type"]=="gs"){
                    if($sel=="addnew"){

                        try {
                        $db = new PDO("mysql:dbname=university", "root", "");
                        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                        $rows=$db->query("INSERT INTO gradtable
                        VALUES('$_POST[fmid]','$_POST[sid]','$_POST[sname]','$_POST[dyear]','$_POST[dsemester]','$_POST[status]','$_POST[option]','$_POST[title]','$_POST[mandyear]'
                        )");
                }
                catch (PDOException $ex) {

                }

                if($sel=="delete"){
            try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $rows = $db->exec("DELETE FROM gradtable WHERE StudentId = '$_POST[sid]'");

            }
            catch (PDOException $ex) {

                }

            }
                if($sel=="update"){

                try {
                    $db = new PDO("mysql:dbname=university", "root", "");
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                    $rows=$db->query("UPDATE gradtable SET
                    FMID=`$_POST[fmid]`,
                    StudentID=`$_POST[sid]`,
                    StudentName=`$_POST[sname]`,
                    DegreeStart=`$_POST[dyear]`,
                    DegreeSemester=`$_POST[dsemester]`,
                    Status=`$_POST[status]`,
                    Option=`$_POST[option]`,
                    Title=`$_POST[title]`,
                    Month_Year=`$_POST[mandyear]`
                    ");

            }
            catch (PDOException $ex) {

                }

?>

A: Your if($sel=="update"){ might be missing a closing brace.
EDIT: Actually, looking at your code further, it seems that you are missing quite a few closing braces.
I suggest you take 5 minutes away from the monitor to clear your head, come back and you'll see them all jump out at you.


text:
Q: Warning on dataproc while using partitionBy on a dataframe I am trying to write a dataframe contents to google cloud storage using a pyspark on dataproc. Though the write is successful, there are a lot of warning messages in the logs which I have pasted below. Is there some setting that I am missing that I need to while creating the cluster or in the pyspark program ? Or is this some google issue?
Note: Data written on the google storage by the dataframe is > 120 GB uncompressed. But I have noticed the same warnings even when I process data which is 1GB in size uncompressed. This is a simple dataframe with 50 columns that are read, some transformations are done and written to disk.
Dataframe Write statement is like below:
df.write.partitionBy("dt").format('csv').mode("overwrite").options(delimiter="|").save("gs://bucket/tbl/")

Warning statements in the Pyspark logs:
18/04/01 19:58:28 WARN org.apache.spark.scheduler.TaskSetManager: Lost task 182.0 in stage 3.0 (TID 68943, admg-tellrd-w-20.c.syw-analytics-repo-dev.internal, executor 219): org.apache.spark.SparkException: Task failed while writing rows
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$.org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask(FileFormatWriter.scala:272)
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1$$anonfun$apply$mcV$sp$1.apply(FileFormatWriter.scala:191)
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1$$anonfun$apply$mcV$sp$1.apply(FileFormatWriter.scala:190)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
        at org.apache.spark.scheduler.Task.run(Task.scala:108)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Error closing the output.
        at com.univocity.parsers.common.AbstractWriter.close(AbstractWriter.java:861)
        at org.apache.spark.sql.execution.datasources.csv.UnivocityGenerator.close(UnivocityGenerator.scala:86)
        at org.apache.spark.sql.execution.datasources.csv.CsvOutputWriter.close(CSVFileFormat.scala:141)
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$DynamicPartitionWriteTask.releaseResources(FileFormatWriter.scala:475)
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$DynamicPartitionWriteTask$$anonfun$execute$2.apply(FileFormatWriter.scala:450)
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$DynamicPartitionWriteTask$$anonfun$execute$2.apply(FileFormatWriter.scala:440)
        at scala.collection.Iterator$class.foreach(Iterator.scala:893)
        at org.apache.spark.sql.catalyst.util.AbstractScalaRowIterator.foreach(AbstractScalaRowIterator.scala:26)
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$DynamicPartitionWriteTask.execute(FileFormatWriter.scala:440)
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask$3.apply(FileFormatWriter.scala:258)
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask$3.apply(FileFormatWriter.scala:256)
        at org.apache.spark.util.Utils$.tryWithSafeFinallyAndFailureCallbacks(Utils.scala:1375)
        at org.apache.spark.sql.execution.datasources.FileFormatWriter$.org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask(FileFormatWriter.scala:261)
        ... 8 more
Caused by: java.io.IOException: com.google.api.client.googleapis.json.GoogleJsonResponseException: 410 Gone
{
  "code" : 500,
  "errors" : [ {
    "domain" : "global",
    "message" : "Backend Error",
    "reason" : "backendError"
  } ],
  "message" : "Backend Error"
}
        at com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel.waitForCompletionAndThrowIfUploadFailed(AbstractGoogleAsyncWriteChannel.java:432)
        at com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel.close(AbstractGoogleAsyncWriteChannel.java:287)
        at java.nio.channels.Channels$1.close(Channels.java:178)
        at java.io.FilterOutputStream.close(FilterOutputStream.java:159)
        at com.google.cloud.hadoop.fs.gcs.GoogleHadoopOutputStream.close(GoogleHadoopOutputStream.java:126)
        at org.apache.hadoop.fs.FSDataOutputStream$PositionCache.close(FSDataOutputStream.java:72)
        at org.apache.hadoop.fs.FSDataOutputStream.close(FSDataOutputStream.java:106)
        at sun.nio.cs.StreamEncoder.implClose(StreamEncoder.java:320)
        at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:149)
        at java.io.OutputStreamWriter.close(OutputStreamWriter.java:233)
        at com.univocity.parsers.common.AbstractWriter.close(AbstractWriter.java:857)
        ... 20 more
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 410 Gone
{
  "code" : 500,
  "errors" : [ {
    "domain" : "global",
    "message" : "Backend Error",
    "reason" : "backendError"
  } ],
  "message" : "Backend Error"
}
        at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
        at com.google.cloud.hadoop.util.AbstractGoogleAsyncWriteChannel$UploadOperation.call(AbstractGoogleAsyncWriteChannel.java:358)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        ... 3 more

A: I tried your code and it was indeed slow -- for me it took over 8 minutes.
I got a significant speedup (down to under 5 minutes) just by using Dataframes rather than RDDs to read the CSV files. This avoids shipping all the data between JVM <-> Python. Here's the code I used:
from pyspark.sql import *
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark import *

spark = SparkSession.builder.getOrCreate()
sc = spark.sparkContext

schema = schema = StructType([
  StructField("col1", StringType(), True),
  StructField("col2", StringType(), True),
  StructField("col3", StringType(), True),
  StructField("col4", StringType(), True),
  StructField("col5", StringType(), True)])

schema_df = spark.read.schema(schema).option("delimiter", "|").csv("gs://path/to/incremental_file.txt*")
schema_df.createOrReplaceTempView("df")

schema_df2 = spark.read.schema(schema).option("delimiter", "|").csv("gs://path/to/hist-file*.gz")
schema_df2.createOrReplaceTempView("df2")

union_fn = schema_df2.union(schema_df)
w = Window.partitionBy("col1","col2").orderBy(col("col4").desc())
union_result = union_fn.withColumn("row_num", row_number().over(w)).where(col("row_num") == 1).drop("row_num").drop("col4")
union_result.createOrReplaceTempView("merged_tbl")
schema_merged_tbl = spark.sql("""select col1,col2,col3,col5 as col6 from merged_tbl""")
schema_merged_tbl.write.partitionBy("col6").format('csv').mode("overwrite").options(delimiter='|',codec="org.apache.hadoop.io.compress.GzipCodec").save("hdfs_merge_path")

A: (This is not an answer to the question, but this didn't fit in a comment. It's related to thread on calling repartition(...) before write.partitionBy).
Without repartition(...), that's going to take forever on GCS. Under the hood, when you say write.partitionBy(...), spark's tasks will each serially write one file at a time for each partition. That's already slow on HDFS, but since GCS has higher latency, that's going to be even slower. If it's 500ms to create each file, writing 2300 partition files will take ~20 minutes per task.
If you shuffle the data, you'll introduce another ("reduce") stage of tasks that will end up with all the data for one partition. So instead of writing 2300*previous-stage-task files, you'll just write 2300 files. This is what you want, especially when you have more than a few partitions.
You might want to experiment with the number of partitions that repartition(...) makes (aka reducer tasks). By default it is 200, but you may want to raise that. Each reducer will end up with a subset of the 2300 output partitions, and will serially write each output file. Again, assuming writing one file takes 500ms, 2300/200 = 115 files = ~1 minute per task. If you have more reducers, you'll get more parallelism, so each task will take less time. But you should set the number of reducers based on the number of nodes in your cluster (e.g. 4x the number of vcores).
Also, you might want to raise spark.executor.cores to 4 (--properties spark.executor.cores=4), since this will be pretty IO bound.

A: This is not the answer to the question but the code flow for the existing requirement.
col1        col2        col3    col4       col5
asd234qsds  2014-01-02  23.99  2014-01-02  Y
2343fsdf55  2014-01-03  22.56  2014-01-03  Y
123fdfr555  2014-01-04  34.23  2014-01-04  N
2343fsdf5f  2014-01-05  45.33  2014-01-05  N
asd234qsds  2014-01-02  27.99  2014-01-07  Y

Please note: the first and the last row have the same keys, but during the Window function only the last row would be considered. My actual data has 51 columns and the Window function is on 9 columns. Im not sure if the compressed data is adding any overhead to this process.
lines1 = sc.textFile("gs://incrmental_file.txt*") -- uncompressed data 210KB
part1 = lines1.map(lambda l: l.split("|"))
df = part1.map(lambda c: Row(col1=c[0],col2=c[1],col3=c[2],col4=c[3], col5 =c[4]))
schema_df = spark.createDataFrame(df)
schema_df.createOrReplaceTempView("df")
#schema_incr_tbl = spark.sql("""select col1,col2,col3,col4,col5 from df""")

lines2 = sc.textFile("gs://hist_files.gz*") -- full year compressed data 38GiB
part2 = lines2.map(lambda l: l.split("|"))
df2 = part2.map(lambda c: Row(col1=c[0],col2=c[1],col3=c[2],col4=c[3], col5 =c[4]))
schema_df2 = spark.createDataFrame(df2)
schema_df2.createOrReplaceTempView("df2")

union_fn = schema_hist_tbl.union(schema_incr_tbl)
w = Window.partitionBy("col1","col2").orderBy(col("col4").desc())
union_result = union_fn.withColumn("row_num",
func.row_number().over(w)).where(col("row_num") == 1).drop("row_num").drop("col4")
union_result.createOrReplaceTempView("merged_tbl")
schema_merged_tbl = spark.sql("""select col1,col2,col3,col5,col5 as col6 merged_tbl""")

schema_merged_tbl.write.partitionBy("col6").format('csv').mode("overwrite").options(delimiter=delim,codec="org.apache.hadoop.io.compress.GzipCodec").save("hdfs_merge_path")


text:
Q: Running pmd using cmd? I'm Trying to run PMD using CMD
    pmd -d "C:\refactoring-toy-example" -f csv -R rulesets/java/unusedcode.xml

it return the result on the console but i need the result on a CSV file . how can I do this ?

A: You can redirect it, but the preferred way is to use the option "-reportfile":
pmd -d "C:\refactoring-toy-example" -f csv -R rulesets/java/unusedcode.xml ^
    -reportfile "C:\refactoring-toy-example\pmd-results.csv"

See https://pmd.github.io/latest/pmd_userdocs_cli_reference.html for the full documentation of the command line options.
The advantage of using the reportfile option over redirecting is, that the reportfile then only contains the report, but redirecting the output would also contain log statements during PMD's execution (especially if you redirect stdout+stderr).
Please note, that you are using a deprecated ruleset (unusedcode.xml). Consider having a look at the available rules and create your own ruleset.


text:
Q: Make Typescript require a certain set of strings in Interface. Then select that string via form Input In my project I need searchFilters.order_by to be explicitly one or the other, as defined by my interface. This works. The problem arises when I try and have the user select it via a HTML form select tool.
This gives me the error

"Type 'string' is not assignable to type '"date_created" | "date_updated"'."

interface ISearchFilters {
  primary: string,
  when: string,
  date: null|string,
  order_by: 'date_created'|'date_updated',
  sort: string,
}

JSX:
        Order By:
        <select onChange={(e)=>setSearchFilters({...searchFilters,order_by:e.target.value})}>
          <option value='date_created'>Created</option>
          <option value="date_updated">Updated</option>
        </select>

How do I have a user select the .order_by parameter with my TS definition like this? Changing its type to 'string' is not an option.

A: The type of e.target.value is loosely. If you can not change that, then you need to type assert it e.g.
 order_by: e.target.value as 'date_created' | 'date_updated'


text:
Q: What is the correct way to extend MySqlGrammar and bind to IOC in laravel I wanted to extend the MySqlGrammer to provide support for the MySql colum type 'set' while using the database in my workbench package.
Having searched around for other peoples attempts to do this I found some examples that appeared to do what i wanted:

*

*http://blog.stidges.com/post/extending-the-connection-class-in-laravel

*http://forumsarchive.laravel.io/viewtopic.php?pid=34937

*What is the MySQL datatype SET equivalent in Laravel Schema?
I tried copying the first two methods above, but both methods produce errors any time I try to migrate. The first method gives:
[Illuminate\Database\QueryException]
SQLSTATE[HY093]: Invalid parameter number (SQL: select * from information_schema.tables where table_schema = services_migrations and table_name = ?)

The second method gives:
[ErrorException]
Argument 1 passed to Illuminate\Database\Connection::__construct() must be an instance of PDO, array given, ...

The third method seemed at first glance to work just fine, it created the right columns in my database table, however when using table prefixes in my config this method failed to use the table prefixes and I had to manually prefix my table names to get it to work.
I am pretty sure that the overridden classes in the above examples are the right way to do it, the issues seems to be how to properly bind and override/extend laravel to inform it of the class changes. Currently I am attempting to do this in my service providers register() method, which seems to me to be the most obvious place to put this code.
For reference the code I am using looks like this:
file: workbench/iccle/quake3/src/Iccle/Quake3/Database/Schema/Grammars/MySqlGrammar.php
<?php
namespace Iccle\Quake3\Database\Schema\Grammars;

class MySqlGrammar extends \Illuminate\Database\Schema\Grammars\MySqlGrammar
{
    protected function typeSet(\Illuminate\Support\Fluent $column)
    {
        return "set('".implode("', '", $column->allowed)."')";
    }
}

file: workbench/iccle/quake3/src/Iccle/Quake3/Database/Schema/Blueprint.php
<?php namespace Iccle\Quake3\Database\Schema;

class Blueprint extends \Illuminate\Database\Schema\Blueprint
{
    public function set($column, array $allowed)
    {
        return $this->addColumn('set', $column, compact('allowed'));
    }
}

file: workbench/iccle/quake3/src/Iccle/Quake3/Database/Schema/Builder.php
<?php
namespace Iccle\Quake3\Database\Schema;

class Builder extends \Illuminate\Database\Schema\Builder
{
    protected function createBlueprint($table, Closure $callback = null)
    {
        return new \Iccle\Quake3\Database\Schema\Blueprint($table, $callback);
    }
}

file: workbench/iccle/quake3/src/Iccle/Quake3/Database/MySqlConnection.php
<?php namespace Iccle\Quake3\Database;

class MySqlConnection extends \Illuminate\Database\MySqlConnection
{
    protected function getDefaultSchemaGrammar()
    {
        return $this->withTablePrefix(new \Iccle\Quake3\Database\Schema\Grammars\MySqlGrammar);
    }

    public function getSchemaBuilder()
    {
        if (is_null($this->schemaGrammar)) { $this->useDefaultSchemaGrammar(); }

        return new \Iccle\Quake3\Database\Schema\Builder($this);
    }
}

File: workbench/iccle/quake3/src/Iccle/Quake3/Quake3ServiceProvider.php
<?php namespace Iccle\Quake3;

use \Illuminate\Support\ServiceProvider;

class Quake3ServiceProvider extends ServiceProvider {

    protected $defer = false;

    public function boot()
    {
        $this->package('iccle/quake3');

        require_once(__DIR__ . '/../../routes.php');
        require_once(__DIR__ . '/../../filters.php');
    }

    public function register()
    {
        $app = $this->app;

        //Method 1, causes exceptions during migrations
        // $this->app->singleton('db.connection.mysql', function($app, $parameters)
        // {
        //  list($connection, $database, $prefix, $config) = $parameters;
        //  return new \Iccle\Quake3\Database\MySqlConnection($connection, $database, $prefix, $config);
        // });

        //Method 2, doomed to failure because it does not pass enough parameters to \Illuminate\Database\Connection::__construct
        //$this->app->resolving('db', function($db) {
        //  $db->extend('mysql', function($config) {
        //      return new \Iccle\Quake3\Database\MySqlConnection($config);
        //  });
        //});
    }

    public function provides()
    {
        return array();
    }

}

My question in short is what is the recommended/correct way to inform laravel of my overridden database classes in my service provider, any help would be much appreciated.

A: Please take a look at my package written a while ago
https://github.com/rafis/schema-extended

A: I fell on the same error so other people might find this useful. Laravel has a special Builder for Mysql that is not the default builder. So in your code you need to specify this special Builder :
file: workbench/iccle/quake3/src/Iccle/Quake3/Database/Schema/Builder.php
<?php
namespace Iccle\Quake3\Database\Schema;

class Builder extends \Illuminate\Database\Schema\MySqlBuilder
{
    protected function createBlueprint($table, Closure $callback = null)
    {
        return new \Iccle\Quake3\Database\Schema\Blueprint($table, $callback);
    }
}

That should do the trick !
Xavier