text:
Q: using UITabBarController not in top level view i'm building app for cars ...
app first view is cars listed in table "UITableViewController", when user select a car "cell" the app navigates to "UITabBarController", because for each car there are a lot of infos and specification that need to be displayed in separate view, so i use here "UITabBarController"
so the tab bar controller is not in the top view level....
Question 1: is this correct usage of the UITabBarController? i'm afraid of getting rejected from apple app review ,i read in apple docs

"In general, use a tab bar to organize information at the app level. A
  tab bar is well-suited for use in the main app view because it's a
  good way to flatten your information hierarchy and provide access to
  several peer information categories or modes at one time."

http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/mobilehig/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW41
Question 2: are there any apps in the market that don't put the tab bar controller in the top view level! plz give me links to them......

A: *

*Yes, it's, your app will not get rejected.

*There are should be app using the tabbarcontroller like you are going to use, but I don't know them.

A: The key words here are "peer information categories". That means information which is related by a common theme, in this case a specific model of cars.
So a structure that had a tab for engine data, a tab for interior spec, a tab for fuel performance and so on would be perfectly fine.  All the tabs display data that relates to the same car.  What would make less sense is if you mixed things up by including a tab that wasn't related to the selected car.
Ideally you'd want to embed the UITabBarController in a UINavigationController so that the navigation bar would display the context (say the car name or something similar) and a back navigation button to provide access back to the table view.


text:
Q: How to change environment variables for VLC on macOS? Recently, I was working on a project when I cam upon the following instruction (one of the many here: https://github.com/alexa/alexa-avs-sample-app/wiki/Mac#3---install-dependencies) :
After you've installed VLC, set the following environment variables:
VLC_PATH: point this to the VLC libs folder. Sample Mac OS X location: /Applications/VLC.app/Contents/MacOS/lib
VLC_PLUGIN_PATH: point this to the VLC plugins folder. Sample Mac OS X location: /Applications/VLC.app/Contents/MacOS/plugins
How does one do the following? I am using High Sierra, macOS. My Shell is ZSH.

I moved this question from the apple Stackexchange as this is more related to a developer issue.

A: Ordinarily, I would take that to mean you need to edit your login script, e.g. $HOME/.profile and add the following near the bottom:
export VLC_PATH=/Applications/VLC.app/Contents/MacOS/lib
export VLC_PLUGIN_PATH=/Applications/VLC.app/Contents/MacOS/plugins

Once you have changed it, either log out and log in again, or start a new Terminal (closing all existing open Terminals) for it to take effect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Variable field in a constraint annotation I need to create a custom constraint annotation which can access the value of another field of my bean. I'll use this annotation to validate the field because it depends on the value of the other but the way I define it the compiler says "The value for annotation attribute" of my field "must be a constant expression".
I've defined it in this way:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=EqualsFieldValidator.class)
@Documented
public @interface EqualsField {
    public String field();

    String message() default "{com.myCom.annotations.EqualsField.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class EqualsFieldValidator implements ConstraintValidator<EqualsField, String>{

    private EqualsField equalsField;

    @Override
    public void initialize(EqualsField equalsField) {
        this.equalsField = equalsField;
    }

    @Override
    public boolean isValid(String thisField, ConstraintValidatorContext arg1) {
        //my validation
    }

}

and in my bean I want something like this:
public class MyBean{

     private String field1;

     @EqualsField(field=field1)
     private String field2;
}

Is there any way to define the annotation so the field value can be a variable?
Thanks

A: The easiest thing to do is take one step back: the constraint/validator you have written works on a field-level, but what you want to enforce is a cross-field dependency i.e. a class-level constraint.
Rewrite your constraint and validator to work at the class level (i.e. the annotation will go on the class, not on the field). That way you'll get access to the entire class. In your isValid(..) method, simply do a get on both the fields, compare, and return appropriately.

A: As the compiler said annotations must be constant (i.e. you can determine the value at compile time.) Now If I'm guessing correctly it looks like you are using this annotation to denote that the values of those fields should be equal when run through the equals field validator. One approach you could take is using reflection. Instead of trying to annotate with the value, annotate with the field name instead
public class MyBean{

     private String field1;

     @EqualsField("field1")
     private String field2;
}

Then in your validator you can read the name of the field and use reflection to access it
Object o = object.getClass().getDeclaredField(annotationValue).get(object);
o == object.(field with annotation) OR
o.equals(object.(field with annotation));

Depending on what you are trying to do you may need to add in logic based on the field type, but still the same general principle.

A: Check out this previous question, has multiple solutions for cross-field validation: Cross field validation with Hibernate Validator (JSR 303)


text:
Q: Two almost identical C++ program, one runs well but the other get runtime error Compare the following two pieces of code:
1.
#include <iostream>
using namespace std;
class B{
public:
    int val;
};
int main(){
    B *b;
    int t = 0;
    b->val = 1;
    cout << 123 << endl;
    return 0;
}

2.
#include <iostream>
using namespace std;
class B{
public:
    int val;
};
int main(){
    B *b;
    b->val = 1;
    cout << 123 << endl;
    return 0;
}

Both versions compile. Code #1 runs good but code #2 gets runtime error.
I'm compiling using C++11 and running a windows machine.
That really confuses me. Can anybody tell me the reason?

A: You are de-referencing an uninitialized pointer here
b->val = 1;

The location the pointer points to is undetermined: it could point anywhere.
Following this pointer is undefined behaviour (UB), which means anything can happen, which is what you are seeing.
What is really happening is that you are writing a value to a segment of memory that you shouldn't. There is no way of knowing what is located there, and the C++ standard can make no promises about possible outcomes. It just calls this UB. It is up to you to avoid these situations.

A: Both are wrong.  The b pointer is uninitialized, so you should not be accessing memory through it.
B *b;
b->val = 1;

So you got lucky when one of them crashed.
The other one you got unlucky, and it didn't crash.
Fixes
You can remove indirection...
B b;
b.val = 1;

Or you can allocate it...
std::unique_ptr<B> b(new B());
b->val = 1;

A: You need to initialize any pointer before using it.
What you see is so called undefined behavior.
#include <iostream>
using namespace std;
class B{
public:
    int val;
};
int main(){
    B *b = new B();
    int t = 0;
    b->val = 1;
    cout << 123 << endl;
    delete b;
    return 0;
}

should work as well as
#include <iostream>
using namespace std;
class B{
public:
    int val;
};
int main(){
    B b;
    int t = 0;
    b.val = 1;
    cout << 123 << endl;
    return 0;
}

A: The problem is that you are using an uninitialized pointer: B* b;. In C and C++, built-in types are not initialized upon creation: they just hold junk.
The solution to your problem is simple: do not use a pointer. B b; will create a class instance and call its constructor.

Code #1 runs good but code #2 gets runtime error.

In Standardese parlance, both code exhibit undefined behavior. This means that pretty much anything can happen and that comprises seemingly working (ie, there might be an error but there is no visible symptom).

A: b->val is pointing to an invalid memory location. Allocate memory for b before assigning b->val


text:
Q: curl: (35) error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure We are using tomcat 1.7 and jdk 1.6, we are getting the below ssdl error:

curl: (35) error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3
  alert handshake failure

do we have any solution for this , do we need to update the tomcat or jdk 1.6.

A: This error might be due to the 'https' in your link. This can be solved by following any one of the following suggestion.

*

*Add the website certificate in your library.(attached links might help)

*Use http instead of https in the link. Some links might not allow this in that case you have to use the first option.


text:
Q: How much current can a solder joint carry? I built a PCB to run some stepper motors. In the past I created some PCBs to turn on/off LED lights but that's the first time I will supply a motor. The current will be higher than my previous experiences and it is the first time I need to really think about the track widths therefore I want to make sure some points before going further. My stepper motor is rated 1.5A per phase but I will limit the current to 1A on the A4988 driver (If required I can lower this limit).

*

*As the worst case I assume the motors will be supplied with 2A (2 phases x 1A per phase)

*I tried to make the track width for each motor about 1.5 millimetres. I cannot measure them properly in the final product but when I check with a ruler I see each of them are thicker than 1 millimetre.

*My search on the web shows that 1 mm track width must be sufficient (if not I am OK to decrease the limit.

My concerns are mostly on the solder joints.

*

*The drivers have pins and I need to solder it onto the PCB. The gap between the pins and the copper on the PCB needs to be filled with solder.

*Also I have some small disconnected paths on the PCB. They are small enough to be filled with solder but as I want to be safe I want to connect this paths with jumper cables. However again I believe there will be some solder between copper tracks and the copper wire at some points.

How can I know that the solder joint will be able to handle about 2A? In my opinion the solder will be much thicker than the tracks, even though the conductivity of the solder is about 10% of copper I believe the thickness of the solder will compensate it. However as I am not experienced I just want to confirm this. Could you please give me some guidance?

A: If the trace/pad is sized correctly and you aren't shoving more current through the pin than the component designer intended (assuming they sized the pin appropriately for their part) you don't need to worry in most situations. The solder has much more cross sectional and contact area with the pad and pin than the trace cross section.
I wouldn't worry unless you are running in very hot ambient temperatures or running extremely high currents (50A? 100A? maybe not even then) and if you do, using silver solder increases conductivity by 2-4x which will probably get you out of it if you didn't bungle things too badly.


text:
Q: How to Get sharepoint Application Sign In Page URL Programmatically In SharePoint Application When Claims Based Authentication types are enabled, a URL for redirecting the user to the Sign In page is required.
I want to get that Which Login Page is set Either default or Custom and if it is custom i want to get the 'Custom Sign in Page' URL programmatically.

A: Read this, explains how it works:
        "http://blog.octavie.nl/index.php/2012/06/11/custom-sign-in-and-sign-out-page/"

A: You do not have to provide a URL if using Windows Authentication in claims mode.  The default login page is _login/default.aspx  If a custom login page is used, it will be listed in central admin.
A URL for redirecting the user to the Sign In page is required only when using a trusted identity provider.  In that case you can get the login page by setting the identity provider to a variable ex. $TIP = Get-SPTrustedIdentityTokenIssuer "YourTrustedIdentityProviderName" then running $TIP.ProviderUri
That will show the host that is being redirected to for login.

A: I know it's been a long time this post was answered but I was looking up how to get the custom sign in page Url programatically. This is not very documented so here's what I've found:

*

*Get a SPWebApplication object (in my case I used an SPSite.WebApplication property.)

*Find the WebApplication IisSetting that has FormsClaimsAuthentication

*Get the Claims Authentication Login Redirection Url

Here:
using (SPSite site = new SPSite("http://mysiteurl")
{
    foreach(KeyValuePair<SPUrlZone, SPIisSettings> zone in site.WebApplication.IisSettings)
    {
        if(zone.Value.FormsClaimsAuthenticationProvider != null)
        {
            string customSignInPageUrl = zone.Value.ClaimsAuthenticationRedirectionUrl;
        }
    }
}

This gave my the relative path to the custom Sign In page I've set in my central admin.
In my case I was coding my own FBA management solution and I wanted the admin to be able to go see the login page even when already logged in.


text:
Q: laravel определение местоположения по ip. Какие есть рускоязычные сервисы, классы, библиотеки? Какие есть сервисы для определения геоинформации?
пробовал maxmind, но не получилось руссифицировать.

A: В своих проектах решаю эту задачу с помощью такого сниппета.
Помещаете в любой класс статический метод, передаете ему IP пользователя.
public static function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
    $output = NULL;
    if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
      $ip = $_SERVER["REMOTE_ADDR"];
      if ($deep_detect) {
        if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
          $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
          $ip = $_SERVER['HTTP_CLIENT_IP'];
      }
    }
    $purpose    = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
    $support    = array("country", "countrycode", "state", "region", "city", "location", "address");
    $continents = array(
      "AF" => "Africa",
      "AN" => "Antarctica",
      "AS" => "Asia",
      "EU" => "Europe",
      "OC" => "Australia (Oceania)",
      "NA" => "North America",
      "SA" => "South America"
    );
    if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
      $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
      if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
        switch ($purpose) {
          case "location":
            $output = array(
              "city"           => @$ipdat->geoplugin_city,
              "state"          => @$ipdat->geoplugin_regionName,
              "country"        => @$ipdat->geoplugin_countryName,
              "country_code"   => @$ipdat->geoplugin_countryCode,
              "continent"      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
              "continent_code" => @$ipdat->geoplugin_continentCode
            );
            break;
          case "address":
            $address = array($ipdat->geoplugin_countryName);
            if (@strlen($ipdat->geoplugin_regionName) >= 1)
              $address[] = $ipdat->geoplugin_regionName;
            if (@strlen($ipdat->geoplugin_city) >= 1)
              $address[] = $ipdat->geoplugin_city;
            $output = implode(", ", array_reverse($address));
            break;
          case "city":
            $output = @$ipdat->geoplugin_city;
            break;
          case "state":
            $output = @$ipdat->geoplugin_regionName;
            break;
          case "region":
            $output = @$ipdat->geoplugin_regionName;
            break;
          case "country":
            $output = @$ipdat->geoplugin_countryName;
            break;
          case "countrycode":
            $output = @$ipdat->geoplugin_countryCode;
            break;
        }
      }
    }
    return $output;
  }


text:
Q: Update listView after updating dataBase? I have a listView of books ,I update listview by clicking on item and its work , but i have duplicate item , the old one and the new one.in my database i have just the new data. How can i also modify my listview? I'm using FireBase Database.
Update with source of my activity:
public class ListOfMyBookActivity extends AppCompatActivity  {

//The elements are initialized here

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

        listView = (ListView) findViewById(R.id.list_book);

        feedItems = new ArrayList<Book>();
        dataBD= FirebaseDatabase.getInstance();
        dataBaseD=FirebaseDatabase.getInstance();
        updateDB=FirebaseDatabase.getInstance();
        ref = dataBD.getReference("books");
        refdelete=dataBaseD.getReference("books");
        refUpdate=updateDB.getReference("books");
        auth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance().getReference("books");

            ref.orderByChild("date_creation").limitToLast(10).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    List<String> list = new ArrayList<String>();
                    for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {

                        Book valueBook = dataSnap.getValue(Book.class);
                        keyId = dataSnap.getKey();

                        String userBd = valueBook.getId_user();
                        if (userBd.equalsIgnoreCase(id_user)) {
                            String titreLivreToDisplay = valueBook.getNom_livre();
                            String descLivreToDisplay = valueBook.getDesc_livre();
                            String prixLivreToDisplay = valueBook.getPrix_livre();
                            String timeToDisplay = valueBook.getDate_creation();
                            String filePathToDiplay = valueBook.getChemin_image();
                            String villeToDisplay = valueBook.getVille_livre();
                            String typeAnnToDisplat = valueBook.getType_annonce_selected();
                            String bookid = valueBook.getId_book();

                            item = new Book();
                            item.setNom_livre(titreLivreToDisplay);
                            item.setDesc_livre(descLivreToDisplay);
                            item.setPrix_livre(prixLivreToDisplay);
                            item.setDate_creation(timeToDisplay);
                            item.setChemin_image(filePathToDiplay);
                            item.setVille_livre(villeToDisplay);
                            item.setType_annonce_selected(typeAnnToDisplat);
                            item.setId_book(bookid);
                            item.setKeyIdNode(keyId);

                            feedItems.add(item);

                        }

                        Collections.reverse(feedItems);

                        listAdapter = new MyBookListAdapter(ListOfMyBookActivity.this, feedItems);

                        listView.setAdapter(listAdapter);

                        listView.setOnItemClickListener(myClickListener);

                        listAdapter.notifyDataSetChanged();

                    }}

            });

    }

    public AdapterView.OnItemClickListener myClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                                final int position, long arg3) {
            deleteItem = position;
            // The AlertDialog is created programmatically
            AlertDialog.Builder alert = new AlertDialog.Builder(arg1.getContext());

            nameBookEdtDlg.setText(nom);
            descBookEdtDlg.setText(desc);
            prixBookEdtDlg.setText(prix);

                alert.setPositiveButton("Update ",
                        new DialogInterface.OnClickListener()

                {
                    public void onClick (DialogInterface dialog,
                    int whichButton){

                    Query query = refUpdate.orderByChild("id_book").equalTo(bookID);

                    query.addListenerForSingleValueEvent(new ValueEventListener() {

                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                            prixSt=prixBookEdtDlg.getText().toString();
                            descSt=descBookEdtDlg.getText().toString();
                            namSt=nameBookEdtDlg.getText().toString();

                            Map<String, Object> result = new HashMap<String, Object>();
                            result.put("nom_livre", namSt);
                            result.put("desc_livre", descSt);
                            result.put("prix_livre", prixSt);
                            result.put("date_creation", currentDateandTimeUpdate);
                            refUpdate.child(keyId).updateChildren(result);

                            listAdapter.notifyDataSetChanged();

                        } });

            AlertDialog alertDialog = alert.create();

                try{alertDialog.show();} } };}
                }

}

The Adapter :
public class MyBookListAdapter extends BaseAdapter {

    public MyBookListAdapter( ListOfMyBookActivity listMyBooks, List<Book> feedItemsBooks) {
        this.activity = listMyBooks;
        this.feedItemsBooks = feedItemsBooks;
    }
    @Override
    public int getCount() {
        return feedItemsBooks.size();
    }

    @Override
    public Object getItem(int location) {
        return feedItemsBooks.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {
        final int pos = position;

        if (inflater == null) {
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.feed_list_item, null);

        }
        storageDisplayImg = FirebaseStorage.getInstance();
        auth = FirebaseAuth.getInstance();
        FirebaseUser userConnect = auth.getCurrentUser();
        String id_user = userConnect.getUid();
        mFirebaseInstance = FirebaseDatabase.getInstance();
        mFirebaseDatabase = mFirebaseInstance.getReference("books");

        final ImageView profilePic = (ImageView) convertView.findViewById(R.id.book_picture_display_myBook);
        name = (TextView) convertView.findViewById(R.id.name_book_display_myBook);
        TextView timestamp = (TextView) convertView.findViewById(R.id.timestamp_myBook);
        statusMsg = (TextView) convertView.findViewById(R.id.desc_display_myBook);
        prix = (TextView) convertView.findViewById(R.id.prix_display_myBook);
        TextView ville = (TextView) convertView.findViewById(R.id.ville_display_myBook);
        TextView typeCat = (TextView) convertView.findViewById(R.id.type_ann_to_display_myBook);

        Book item = feedItemsBooks.get(position);

        idLivreListAdapter=item.getId_book();

        name.setText(item.getNom_livre());

        if (!TextUtils.isEmpty(item.getDate_creation())) {
            timestamp.setText(item.getDate_creation());
            timestamp.setVisibility(View.VISIBLE);
        } else {
            timestamp.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(item.getDesc_livre())) {
            statusMsg.setText(item.getDesc_livre());
            statusMsg.setVisibility(View.VISIBLE);
        } else {
            statusMsg.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(item.getType_annonce_selected())) {
            typeCat.setText(item.getType_annonce_selected());
            typeCat.setVisibility(View.VISIBLE);
        } else {
            typeCat.setVisibility(View.GONE);
        }

        if (item.getPrix_livre() != null) {
            prix.setText(item.getPrix_livre() + " DH");
            prix.setVisibility(View.VISIBLE);
        } else {
            prix.setVisibility(View.GONE);
        }

        if (item.getVille_livre() != null) {

            ville.setText(item.getVille_livre());
            ville.setVisibility(View.VISIBLE);
        } else {
            ville.setVisibility(View.GONE);
        }

        storageRef = storageDisplayImg.getReferenceFromUrl(item.getChemin_image());
        Log.e(" ", " storageRef " + storageRef.toString());

        if (item.getChemin_image() != null && id_user != null) {

            Glide.with(convertView.getContext())
                    .using(new FirebaseImageLoader())
                    .load(storageRef)
                    .into(profilePic);
            profilePic.setVisibility(View.VISIBLE);

        } else {
            profilePic.setVisibility(View.GONE);
        }

        return convertView;
    }

}

My question is not duplicated I tried the proposed solutions but it does not work.

A: Not sure if this if your problem, but most of that firebase code isn't all necessary...
Notice you call getNom_livre (and others) and then call setNom_livre (and others) with the exact same value?
You also make a new Book when you already have one.

Book valueBook = dataSnap.getValue(Book.class); // This is a Book
keyId = dataSnap.getKey();

String userBd = valueBook.getId_user();
if (userBd.equalsIgnoreCase(id_user)) {
    String titreLivreToDisplay = valueBook.getNom_livre();
    ...

    item = new Book(); // Why do you need a new one?
    item.setNom_livre(titreLivreToDisplay);
    ...

    feedItems.add(item);
}

First, you should move this before the firebase method. There is no need to recreate the adapter every data update.
listAdapter = new MyBookListAdapter(ListOfMyBookActivity.this, feedItems);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(myClickListener);

ref.orderByChild("date_creation")...

but i have duplicate item , the old one and the new one

You simply need to clear the adapter to remove old data and add the new stuff
ref.orderByChild("date_creation")
    .limitToLast(10)
    .addValueEventListener(new ValueEventListener() {
         @Override
         public void onDataChange(DataSnapshot dataSnapshot) {
             // Remove old data
             feedItems.clear();

             // Add new data
             for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {

                 Book valueBook = dataSnap.getValue(Book.class);
                 keyId = dataSnap.getKey();

                  String userBd = valueBook.getId_user();
                  if (userBd.equalsIgnoreCase(id_user)) {
                      valueBook.setKeyIdNode(keyId);
                      feedItems.add(valueBook);
                  }
             }
             Collections.reverse(feedItems);
             listAdapter.notifyDataSetChanged(); // Tell adapter of new data

A: Use feedItems.clear() before getting updated data from firebase.
Try this:
ref.orderByChild("date_creation").limitToLast(10).addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        feedItems.clear();

        .............
        ..................
    }
});

A: try
    feedItems.remove(position);
   // listView.invalidateViews();
     arrayAdapter.notifyDataSetChanged();

A: use this in your adapter
public void dataSetChanged(ArrayList<Movie>list)
    {
        this.list=list;
        this.notifyDataSetChanged();
    }

and use it like this
upadte your list data and after that use below line
customListViewAdapter.dataSetChanged(movieList);

A: use this for update your list
notifyDataSetChanged()


text:
Q: KeyError: 'id' when may2One relationship 0d00 14 I got a dropdown which is a many2One field, the issue is when creating a new record and the related field is empty I got this error:
Traceback:
Error: KeyError: 'id'
    at F.__getitem__ (https://xxxx-14-de431-2580878.dev.odoo.com/web/static/src/js/core/py_utils.js:36:19)
    at F.__getattr__ (https://xxxx-14-de431-2580878.dev.odoo.com/web/static/src/js/core/py_utils.js:41:21)
    at F.__getattribute__ (https://xxxx-14-de431-2580878.dev.odoo.com/web/static/lib/py.js/lib/py.js:755:29)
    at Object.py.PY_getAttr (https://xxxx-14-de431-2580878.dev.odoo.com/web/static/lib/py.js/lib/py.js:526:30)
    at Object.py.evaluate (https://xxxx-14-de431-2580878.dev.odoo.com/web/static/lib/py.js/lib/py.js:1443:23)
    at Object.py.evaluate (https://xxxx-14-de431-2580878.dev.odoo.com/web/static/lib/py.js/lib/py.js:1415:38)
    at Object.py.evaluate (https://xxxxx-14-de431-2580878.dev.odoo.com/web/static/lib/py.js/lib/py.js:1427:37)
    at Object.py.eval (https://xxxxx-14-de431-2580878.dev.odoo.com/web/static/lib/py.js/lib/py.js:1471:19)
    at https://xxxx-14-de431-2580878.dev.odoo.com/web/static/src/js/core/py_utils.js:156:42
    at Function._.each._.forEach

To elaborate more I got a Team model which is related to a sale_order_detail model, Teams are related to a SO, and you can set teams by SO and assign a team o a SOD.
the problem is when creating a new record and click on the dropdown raises the error, I think it might be because the list is empty, I've been trying to set a default empty value without any luck.
This is the field:
team_id = fields.Many2one('rw.team', string="Team")

A: Check rw.team is exist or not!


text:
Q: d3.js color range and lighter color range I would like to have two color ranges, the second one must consist off the same colors, but lighter.
rangeLength=10
color = d3.scale.linear().domain([1,rangeLength]).range(['red', 'blue']);
colorLigher= d3.scale.linear().domain([1,rangeLength]).range(['red'.lighter(10), 'blue'.lighter(10)]);

Obviously doesn't work, as 'red' is a string.
Thanks in advance

A: You can use the brighter() function (see the documentation):
length=10
color = d3.scale.linear().domain([1,length]).range(['red', 'blue']);
colorLighter= d3.scale.linear().domain([1,length])
      .range([d3.rgb('red').brighter(), d3.rgb('blue').brighter()]);


text:
Q: Handlebars Templates and Browserify with TypeScript I'm in the process of porting a project to TypeScript.  The project combines Handlebars and Browserify with hbsfy to handle templates.  This means I have JavaScript code like this:
var photosTemplate = require('./views/photos.hbs');

Which requires in a template file called "photos.hbs" from a views folder which looks a little like this:
{{#each this}}
    {{title}}
{{/each}}

There's a gulpfile that runs as part of the build step to convert the template into a function that can be used.  This means that in my consuming file I can write code like this which uses the function template:
var newHtml = photosTemplate([{title: "test title 1"}, {title: "test title 2"}]);

The question is, how can this be made to work for TypeScript?  I've switched my var for an import and moved to using the --module commonjs compiler flag:
import photosTemplate = require('./views/photos.hbs');

At this point I encounter the error:

error TS2307: Cannot find external module './views/photos.hbs'.

Fair enough you might think.  So I created a photos.hbs.d.ts to sit alongside that looks like this:
interface photos {
    (context: any, options?: any): string;
}

export = photos;

This is a simple interface that illustrates how the photos template is being used.  However, with this in place the compiler yields the error:

error TS2304: Cannot find name 'photosTemplate'.

There's a similar question here: https://stackoverflow.com/a/23957928/761388  I think the problem is my photos.hbs.d.ts file but I'm not sure what's wrong with it.  I feel like I'm missing something very simple in the definition to do with external modules.  But for the life of me I can't work out what it is...

A: This worked for me...
photos.hbs.d.ts
declare function photos (context: any, options?: any): string;

export = photos;

Using it:
import photosTemplate = require('./views/photos.hbs');

photosTemplate("");

The reason being you want to actually call the function, not just define a signature.
You could also do:
interface Photos {
    (context: any, options?: any): string;
}

declare var photos: Photos;

export = photos;


text:
Q: Server error when sending mail with mailgun on amazon ec2 I have Laravel app with a mailgun account for handling emails.
My app is on amazon instance.
When sending mail on local all works great, but when deploy it gives me 'server error' what makes me think that I should do something on my amazon instance.
Any help with this will be great!
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=2525
MAIL_USERNAME=username
MAIL_PASSWORD=password
MAIL_ENCRYPTION=null

The error that I am getting is :
Connection could not be established with host smtp.mailtgun.org
[php_network_getaddresses: getaddrinfo failed: Name or service not
known #0]

running on Ubuntu


text:
Q: ADO.Net - Why isn't the insert happening? I went through MSDN pages to learn ADO.Net using Commands. I am able to read using the sample code posted there.
But when I tried to use the modification code below, the insert is not happening. I am not ale to figure out why. Can someone please tell me what is wrong with this code?
string connectionString = "A_VALID_CONNECTION_STRING";
string commandText =
"INSERT INTO Contacts (FullName, Mobile) VALUES ('Pierce Brosnan', '1800-007')";

SqlConnection connection = new SqlConnection(connectionString);

try
{
  connection.Open();
  SqlCommand command = new SqlCommand(commandText, connection);
  Console.WriteLine(command.ExecuteNonQuery());
  connection.Close();
}
catch (Exception ex)
{
  Console.WriteLine(ex.Message);
}

Edit

*

*No exception is thrown.

*The ExecuteNonQuery() which is supposed to return the no. of rows affected is returning 1.

*Environment: Visual C# 2010 Express | SQL Server 2008 Express | Windows 7 Ultimate 32-bit.
Update

*

*Previously I was using a MDF file present in the project. It was, I guess, automatically attached to the SQL server instance each time the project ran. This is when I had the problem. The connection string had some info about attaching a database file.

*I removed the SQL Server 2008 Express that I installed along with Visual C# 2010 Express. Also removed the MDF file from the project.

*I Separately downloaded and installed SQL Server 2008 Express along with Management Studio Express.

*Created a new database in management studio.

*Used a different type of connection string to use the database in the server.
Now INSERT is working!
P.S. I guess I should have mentioned that I had an attach database file scenario. Really sorry for that.

A: My suspicion is that you had the following scenario:

*

*Database.mdf file was present in the project with the table structure created in it

*Your connection string looked something like this Server=.\SQLExpress;AttachDbFilename=database.mdf;Database=dbname; Trusted_Connection=Yes;, i.e. loading the database in the connection string.

What was happening was, when you built/ran your project, your application was compiled and the database.mdf file was copied along with it to ApplicationProjectFolder\bin\Debug, so that when the application was run, the file database.mdf was present. This means that everytime you ran your project, the "empty" database.mdf file was copied from ApplicationProjectFolder\database.mdf to ApplicationProjectFolder\bin\Debug\database.mdf, hence the data "disappearing". Also, the file database.mdf probably had "Copy Always" set on its properties in the project.
So, the "INSERT" was working, it was just being "reset" everytime you ran your application.


text:
Q: Newman run overfilling cache memory I have a problem with overfilling cache memory, using long newman runs. I run collection which adds some data to my database in live mode. It shouldnt stop but when its working about 2 hours, cache memory is filled and my computer stops working properly.
My computer has 8 GB RAM but its not enough.

Durning run, free cache memory is dropping. Old data (which is useless for me) is kept and released too slow which causes overfilling cache memory.
I am not a root and cant use this command:
 # sync; echo 1 > /proc/sys/vm/drop_caches
Have can I cope with this and dont keep this data in cache?
Thanks for any kind of help.


text:
Q: How to change emphasis on confirm javascript buttons? I have the following JavaScript:
var leave_page_confirm = true;

function save_data_check() {
    var msg;
    if (leave_page_confirm === true) {
        $('.input-right').each(function() {
            if (this.value) {
                msg = 'You have unsaved data on this page.';
                return false;
            }
        });
    }
    return msg;
}

window.onbeforeunload = save_data_check;

This confirm box displays when you have unsaved data in a form on my pages.
However, when it appears the emphasis (default button) is "Leave This Page" I would like the emphasis to be on "Stay on This Page" despite quite a bit of Googling, I can't seem to find any code that changes the emphasis of the buttons on a confirm alert.
Is there any way to accomplish this?

A: You might want to refer to this question:
How to personalize alert buttons - window.confirm() and window.alert()
Basically, you can't. But you can make your own modals for this kind of thing and have full control over what it looks like and which buttons are emphasized.

A: You just can't do this.
Here's the docs https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
BTW, you can try to find out another way to say users about unsaved data. It might be a UI solution, some outlines, messages etc.


text:
Q: Emacs: check for no-window-system in .emacs is it possible, to check if emacs is running in --no-window-system (-nw) mode within the dot-emacs file (.emacs)? I would like to enable/include certain extension only if emacs is in window mode (/or not).
Kind regards,
mefiX

A: Put the code you want to run when emacs executes in a windowed environment inside a when block and use the display-graphic-p predicate i.e.
(when (display-graphic-p)
  (do something)
  (do-another-thing))

or reverse

A: The variable window-system is nil if the selected frame is on a text-only terminal.


text:
Q: Check FME license with Python I am wondering if there is possible to check If there is a free FME license with python. I will my python code run the FME workbench, but first check if one is available.  This is how I will avoid some issues with python later.

A: You clould execute lmutil.exe from python. Use the subprocess module. The article http://fmepedia.safe.com/articles/How_To/Check-who-is-using-FME-floating-licenses
describes how to query the status of a license server with lmutil.exe.


text:
Q: Filter Map by key set Is there a shortcut to filter a Map keeping only the entries where the key is contained in a given Set?
Here is some example code
scala> val map = Map("1"->1, "2"->2, "3"->3)
map: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)

scala> map.filterKeys(Set("1","2").contains)
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2)

I am searching for something shorter than this.

A: Sorry, not a direct answer to your question, but if you know which keys you want to remove (instead of which ones you want to keep), you could do this:
map -- Set("3")

A: A tangential tip, in case you are going to follow the PredicateW idea in @oxbow_lakes' answer:
In functional programming, instead of defining ad hoc functions, we aim for more generalized and composable abstractions. For this particular case, Applicative fits the bill.
Set themselves are functions, and the Applicative instance for [B]Function1[A, B] lets us lift functions to context. In other words, you can lift functions of type (Boolean, Boolean) => Boolean (such as ||, && etc.) to (A => Boolean, A => Boolean) => (A => Boolean). (Here you can find a great explanation on this concept of lifting.)
However the data structure Set itself has an Applicative instance available, which will be  favored over [B]Applicative[A => B] instance. To prevent that, we will have to explicitly tell the compiler to treat the given set as a function. We define a following enrichment for that:
scala> implicit def setAsFunction[A](set: Set[A]) = new {
     |   def f: A => Boolean = set
     | }
setAsFunction: [A](set: Set[A])java.lang.Object{def f: A => Boolean}

scala> Set(3, 4, 2).f
res144: Int => Boolean = Set(3, 4, 2)

And now put this Applicative goodness into use.
scala> val map = Map("1" -> 1, "2" -> 2, "3" -> 3)
map: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)

scala> map filterKeys ((Set("1", "2").f |@| Set("2", "3").f)(_ && _))
res150: scala.collection.immutable.Map[java.lang.String,Int] = Map(2 -> 2)

scala> map filterKeys ((Set("1", "2").f |@| Set("2", "3").f)(_ || _))
res151: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)

scala> map filterKeys (Set("2", "3").f map (!_))
res152: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1)

Note: All of the above requires Scalaz.

A: Answering the Question
You can take advantage of the fact that a Set[A] is a predicate; i.e. A => Boolean
map filterKeys set

Here it is at work:
scala> val map = Map("1" -> 1, "2" -> 2, "3" -> 3)
map: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)

scala> val set = Set("1", "2")
set: scala.collection.immutable.Set[java.lang.String] = Set(1, 2)

scala> map filterKeys set
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2)

Or if you prefer:
scala> map filterKeys Set("1", "2")
res1: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2)

Predicates
It's actually really useful to have some wrapper around a predicate. Like so:
scala> class PredicateW[A](self: A => Boolean) {
   | def and(other: A => Boolean): A => Boolean = a => self(a) && other(a)
   | def or(other: A => Boolean): A => Boolean = a => self(a) || other(a)
   | def unary_! : A => Boolean = a => !self(a)
   | }
defined class PredicateW

And an implicit conversion:
scala> implicit def Predicate_Is_PredicateW[A](p: A => Boolean) = new PredicateW(p)
Predicate_Is_PredicateW: [A](p: A => Boolean)PredicateW[A]

And then you can use it:
scala> map filterKeys (Set("1", "2") and Set("2", "3"))
res2: scala.collection.immutable.Map[java.lang.String,Int] = Map(2 -> 2)

scala> map filterKeys (Set("1", "2") or Set("2", "3"))
res3: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)

scala> map filterKeys !Set("2", "3")
res4: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1)

This can be extended to xor, nand etc etc and if you include symbolic unicode can make for amazingly readable code:
val mustReport = trades filter (uncoveredShort ∨ exceedsDollarMax)

val european = {
  val Europe = (_ : Market).exchange.country.region == Region.EU
  trades filter (_.market ∈: Europe)
}


text:
Q: iis two domain with ssl cert error browsing webpage I have iis 10.0 which host two domains ssl cert, say 1 is www.abc.com and the another is www.dfg.com, both domain are pointing to the same iis. So I can access webpage like https://www.rgx.com/calculation.aspx and
https://www.dfg.com/calculation.aspx both. The problem is that for most page, both domain work properply, but for some webpage in one domain e.g dfg.com https://www.dfg.com/questions.aspx, it cannot be loaded, in firefox, it returns
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
Please contact the website owners to inform them of this problem.

So what is the reason that some page cannot be accessed in one domain but can in another domain?

A: Do you have an error code? This error seems to only appear in Firefox, try the following in Firefox to see if it resolves the issue on your end:

*

*Open about:preferences#privacy in the browser.

*Scroll down to the Certificates section and click on "View certificates".

*Make sure the Authorities tab is selected.

*Locate Avast certificates and use the delete option to remove them.

*Use the import button to import the certificates from C:\ProgramData\AVAST Software\Avast\wscert.dat.


text:
Q: How to Sort objects by 2 fields Java The file I am trying to read looks like this:
1995     Pokemon    Ikue Ôtani
1940     Tom and Jerry    William Hanna
1995     Pokemon    voice actor2
1940     Tom and Jerry    voice actor3
2000     Cartoon      voice actor

It has around 20k rows. I already got the reading the file and storing the data in an object.
        in = new BufferedReader(new FileReader(cartoonsFile));

        ArrayList<String> voiceActors = new ArrayList<>();
        ArrayList<Cartoon> cartoons = new ArrayList<>();

        //read each line
        String line = in.readLine();
        while (line != null) {
            String[] columns = line.split("\\t");
            String year = columns[0];
            String cartoon = columns[1];
            String voiceActor = columns[2];

            //make new object and store data

            Cartoon c = new Cartoon(Integer.parseInt(columns[0]),
                                    columns[1], columns[2]));
            cartoons.add(c); //add to the array list

Object
public class Cartoon {
  private int year;
  private String title;
  private String voiceActor;

  public Cartoon(int year, String title, String voiceActor) {
    this.year = year;
    this.title = title;
    this.voiceActor = voiceActor;
  }
};

I would like to read the file in threads and sort by year. Can anyone provide sample code on how can multithread and merge sort be implemented together?
The output that I'd like to get
1940     Tom and Jerry         William Hanna
                               voice actor2
                               voice actor3
                               voice actor4
                               voice actor5

1995     Pokemon               Ikue Ôtani
                               voice actor2

         A Cartoon             voice actor1
                               voice actor2
                               voice actor3

2000     Cartoon               voice actor

A: Try this.
List<CartoonYear> readAndSortByYear(String inFile) throws IOException {
    return Files.readAllLines(Paths.get(inFile))
        .parallelStream()
        .map(line -> line.split("\\t"))
        .map(columns -> new CartoonYear(Integer.parseInt(columns[0]), columns[1], columns[2]))
        .sorted(Comparator.comparing(CartoonYear::getYear))
        .collect(Collectors.toList());
}

A: Sticking with your data structure (just renaming it from the rather peculiar CartoonYear to Cartoon), and also sticking with the good approach of using Java streams by @saka1029 (instead of manually implementing a merge sort algorithm), you could do something like this:
package org.acme;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Cartoon {
  private int year;
  private String title;
  private String voiceActor;

  public Cartoon(int year, String title, String voiceActor) {
    this.year = year;
    this.title = title;
    this.voiceActor = voiceActor;
  }

  public static Map<String, List<Cartoon>> readAndGroupByYearAndTitle(String inFile) throws IOException {
    return Files.readAllLines(Paths.get(inFile))
      .parallelStream()
      .map(line -> line.split("\\t"))
      .map(columns -> new Cartoon(Integer.parseInt(columns[0]), columns[1], columns[2]))
      .collect(Collectors.groupingBy(cartoon -> String.format("%4d %s", cartoon.year, cartoon.title)));
  }

  public static void main(String[] args) throws IOException {
    Map<String, List<Cartoon>> cartoonsGrouped = readAndGroupByYearAndTitle(args[0]);
    cartoonsGrouped.keySet()
      .parallelStream()
      .sorted()
      .forEachOrdered(group -> {
        boolean firstElement = true;
        for (Cartoon cartoonYear : cartoonsGrouped.get(group)) {
          if (firstElement) {
            System.out.printf("%4d  %-25s  %s%n", cartoonYear.year, cartoonYear.title, cartoonYear.voiceActor);
            firstElement = false;
          }
          else
            System.out.printf("%4s  %-25s  %s%n", "", "", cartoonYear.voiceActor);
        }
      });
  }
}

This was just quick & dirty, not code I am proud of. Your requirement to only print year and title once per group does not make the code nicer with the if-else either. But assuming you have an input file like this:
1995    Pokemon Ikue Ôtani
1940    Tom and Jerry   William Hanna
11  Sample  foo
1995    Pokemon voice actor2
1940    Tom and Jerry   voice actor3
2000    Cartoon voice actor
11  Sample  bar

you will get output like this:
  11  Sample                     foo
                                 bar
1940  Tom and Jerry              William Hanna
                                 voice actor3
1995  Pokemon                    Ikue Ôtani
                                 voice actor2
2000  Cartoon                    voice actor


text:
Q: outputted HTML file linking back to the java program In my Java program, I have to output an HTML file with buttons such as sending or displaying specific emails, which is saved in this java program (will run on a server). How do I link this HTML file so that when the button is clicked, it actually calls a method in the java program (such as the send email method) and affects some fields, such as the list that stores the emails? If there is not a way to do this, how can I achieve what I want to do? Thank you.
This is the code I have for GUI, but I do not want GUI. I want to turn all these codes into an outputted HTML file. So basically, in place of these codes, I need to output an HTML file that does exactly the same thing as this GUI does. The reason I need to output a webpage is that when the program is launched onto the server, GUI is not that handy. I believe the program will always be running and in the main I have a timeTask that runs this routine once a day.
public void createEmailPanel(String name, final Email email) {
    final JPanel emailPanel = new JPanel();
    emailPanel.setLayout(null);
    emailPanel.setSize(900, 50);
    panel.add(emailPanel);

    String emails = "";
    for(String a : email.getList()) {
        emails = emails + a + " ";
    }

    JLabel labelName = new JLabel(emails);
    labelName.setLocation(0, 0);
    labelName.setSize(700, 30);
    emailPanel.add(labelName);

    JButton display = new JButton("Display Email");
    display.setLocation(0, 50);
    display.setSize(200, 30);
    display.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JEditorPane HtmlPane= new JEditorPane();
            boolean fail = false;
            try {
                File temp = File.createTempFile("temp", ".html");
                BufferedWriter out = new BufferedWriter(new FileWriter(temp));
                out.write(email.getBody());
                out.close();

                HtmlPane.setContentType("text/html");
                HtmlPane.setEditable(false);
                try {
                    HtmlPane.setPage(temp.toURI().toURL());
                } catch (MalformedURLException a) {
                    fail = true;
                    JPanel p = new JPanel();
                    p.setSize(500, 200);
                    p.setLayout(null);

                    JLabel labelName = new JLabel("Error displaying emails");
                    labelName.setLocation(0, 0);
                    labelName.setSize(700, 30);
                    p.add(labelName);

                    JFrame f = new JFrame();
                    f.setSize(500, 200);
                    f.add(p);
                    f.setVisible(true);
                }
                JScrollPane jsp=new JScrollPane(HtmlPane);
                JFrame f = new JFrame();
                f.setSize(800, 500);
                f.add(jsp);
                f.setVisible(true);
                temp.delete();
            } catch (IOException e1) {
                if(fail) {
                    JPanel p = new JPanel();
                    p.setSize(500, 200);
                    p.setLayout(null);

                    JLabel labelName = new JLabel("Error displaying emails");
                    labelName.setLocation(0, 0);
                    labelName.setSize(700, 30);
                    p.add(labelName);

                    JFrame f = new JFrame();
                    f.setSize(500, 200);
                    f.add(p);
                    f.setVisible(true);
                }
            }

        }
    });
    emailPanel.add(display);

    JButton sendRecipient = new JButton("Send Email to Recipients");
    sendRecipient.setLocation(440, 50);
    sendRecipient.setSize(200, 30);
    sendRecipient.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            email.sendEmailToRecipients();
            queue.remove(email);
            panel.remove(emailPanel);
            JPanel pane = new JPanel();
            pane.setSize(900, 50);
            panel.add(pane);
            JLabel labe = new JLabel("Email sent to recipients.");
            labe.setSize(900, 50);
            labe.setHorizontalAlignment(0);
            pane.add(labe);
            frame.validate();
            frame.repaint();
        }
    });
    emailPanel.add(sendRecipient);

email is an Email object which has a method of sendEmailRecipient that uses JavaMail. Also, the body of the email is an HTML as well, maybe irrelevant here.


text:
Q: String formatting has precision in Go? I came across this line in the book 'The Go Programming Languague' on page 112.
fmt.Printf("#%-5d %9.9s %.55s\n", item.Number, item.User.Login, item.Title)
What do %9.9s and %.55s mean?

A: From go doc fmt:

Width is specified by an optional decimal number immediately preceding the verb. If absent, the width is whatever is necessary to represent the value. ....
  For strings, byte slices and byte arrays, however, precision limits the length of the input to be formatted (not the size of the output), truncating if necessary.

Thus, %.9.9s means minimal width 9 runes with input truncated at 9, and thus exactly length 9.  Similar %.55s means no minimal width but input truncated at 55 which means output is at most 55 runes.


text:
Q: search queries in nodejs and mongodb and populated data i have a web app that's written in nodejs and mongodb, i have the following two models
   var TeacherSchema = new Schema({
       school_id:[{type: Schema.Types.ObjectId, ref: 'School'}],
       name: String,
       subjects: [{type: Schema.Types.ObjectId, ref: 'Subject'}],
       });

 var SubjectSchema = new Schema({
     title : String,
     school_id:[{type: Schema.Types.ObjectId, ref: 'School'}]
     });

i wrote an api that searches throw the teacher or subjects
 router.get("/field-teacher-subject", function (req, res) {
var   school_id= req.query.schoolId;
Subject.find(school_id:'school_id,function (err, subjects) {
    if (err) {
        console.log(err);
        res.json({status: "error", message: err.message});
    } else {
        var sub_array=[];
        for(var q in subjects){
            sub_array.push(subjects[q]._id);
        }
        Teacher.find({subjects:{$in :sub_array }},{first_name:true, father_name:true, last_name : true, subjects:true}).populate('subjects')
            .exec(function(tech) {
                console.log("hello: ");
                var subjeto = [];
                if(tech){
                    for(var p in tech){
                        subjeto.push(tech[p].subjects);
                    }
                }
                res.json({status: "success", message: "subjects returned",
            items: tech});
            }).catch(function(err){
                if(err){
                    res.json({status:"error",
                      message:"error occurred"+err.message});
                    return;
                }
            });
    }
}).limit(parseInt(req.query.max));
});

THIS RETURNS null when i search for a name,
what is the best way to solve this

A: Hard to know what you are asking but your code has few errors. Let's clean up your code, shall we?
router.get("/field-teacher-subject", function (req, res) {
    // get subjects
    Subject
        .find({ school_id: req.query.schoolId })    // 1st argument is an object
        .limit(parseInt(req.query.max))             // should go before
        .exec(function (err, subjects) {            // use .exec()
            if (err) {
                console.log(err);
                return res.json({ status: "error", message: err.message });
            }
            // get subject IDs
            var sub_array = subjects.map(function (subject) { return subject._id; });
            // get teachers assigned to subjects
            Teacher
                .find({ subjects: { $in: sub_array }})
                .select('first_name father_name last_name subjects')
                .populate('subjects')
                .exec(function(err, teachers) {     // 1st argument is an error
                    if (err) {
                        console.log(err);
                        return res.json({status: "error", message: err.message });
                    }
                    var subjeto = teachers.map(function (teacher) { return teacher.subjects; });

                    res.json({status: "success", message: "subjects returned", items: teachers  });
                });
    });
});

Useful links:

*

*See 3rd example in doc on how to use .limit() and .exec().

*.map()

*You tried to use .exec() like .then() and .catch() in your second query


text:
Q: No indent in res.cls I am writing a resume using res.cls.
I would like to write a non-indented paragraph under a section heading but can't figure out how to override the heavily indented margins used for columns under sections. I have tried \flushleft and a few other things but that nothing has worked. Anyone have any suggestions?
A minimal working example illustrating the undesired indentation:
\documentclass{res}
\usepackage{lipsum}% just to generate text for the example

\begin{document}

\section{Test Section}
\lipsum[4]

\end{document}

A: As Alan Munn suggests in his comment, you should consider using another document class (res.cls is very old, and poorly documented). That being said, according to the comments on res.cls, you can solve your problem using the \newsectionwidth{<length>} command which controls the amount that the section titles go in the left margin; a little example:
\documentclass{res}
\usepackage{lipsum}% just to generate text for the example

\newsectionwidth{0cm}

\begin{document}

\section{Test Section One One}
\lipsum[4]

\end{document}

The above solution moves the section title to the right; now that I reread the question, perhaps the desired effect is to leave the title as it is and move the block of text to the left; if this is the case, \parshape will do the job:
\documentclass{res}
\usepackage{lipsum}% just to generate text for the example

\begin{document}

\section{Test Section One}
\lipsum[4]

\section{Test Section Two}
\parshape 1 -\sectionwidth \resumewidth
\lipsum[4]

\section{Test Section Three}
\lipsum[4]

\end{document}


text:
Q: Is there a way to limit the number of requests sent to browser for a long running process to 1 in a Flask Application? I am trying to make a web application out of a deep learning model which processes large files to output segmented files. Naturally, it takes approximately 30 minutes to process these files. I have noticed that before completing one task, it proceeds on to restart the process. I have read that this might be because if a webpage is unresponsive for long, the browser makes another request and therefore the application proceeds to start another run, while the previous one is still going on. Is there a way to limit this? Or is there a way to deal with time consuming process in Flask? Please mention exact details of how to do so?

A: Just start a thread to process the file in the background, and redirect the user to a loading page, that refreshes automatically:
#!/usr/bin/python3
import os, uuid
from threading import Thread
from flask import Flask, redirect, make_response
from time import sleep # For debugging

UPLOAD = './uploads'

if not os.path.isdir(UPLOAD):
    os.mkdir(UPLOAD)

def worker(Id):
    folder = os.path.join(UPLOAD, Id)
    sleep(10) # Processing the files
    with open(os.path.join(folder, 'isdone.txt'), 'wt') as o:
        o.write('yes')
        o.close()

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return '''
<form action="/doit" method="POST">
<input type="submit" value="Do it!" />
</form>
'''

@app.route('/loading/<Id>', methods=['GET'])
def loading(Id):
    folder = os.path.join(UPLOAD, Id)
    if not os.path.isdir(folder):
        return 'Error: wrong Id'
    with open(os.path.join(folder, 'isdone.txt'), 'rt') as o:
        isdone = o.read().strip()
        o.close()
    if isdone == 'yes':
        return 'Done!'
    else:
        res = make_response('Loading...')
        res.headers['refresh'] = '3' # Refresh the page every 3 s
        return res

@app.route('/doit', methods=['POST'])
def doit():
    rnd = uuid.uuid4().hex
    folder = os.path.join(UPLOAD, rnd)
    os.mkdir(folder)
    with open(os.path.join(folder, 'isdone.txt'), 'wt') as o:
        o.write('no')
        o.close()
    # Upload the files...
    # Recomanded to create an anther subdirectory
    # on {folder}, to don't override the 'isdone.txt'
    Thread(target=worker, args=(rnd,)).start()
    return redirect(f'/loading/{rnd}')

app.run('0.0.0.0', 8080)


text:
Q: How to change java source in intellij I have an intelliJ project which was working just fine untill I accidentally created a maven pom for it by right clicking on the project folder. I'm not sure exactly what the option I clicked was called (it wasn't the one I was trying to click). ctrl-z did nothing, so I deleted the pom. Now I'm stuck with a project that will only compile with java 1.5.
I tried adding the pom again with proprties set as shown in this question. I also tried going into Project settings where I can clearly see the Project language level set to SDK default (8).

A: Go to File -> Project Structure -> Project and choose your desired language version in "Project Language Level" dropdown menu.


text:
Q: Checking DataFrame column value for match in list I have the following list:
list = ['abc', 'ace', 'aei']

And I have DataFrame:
df = pd.DataFrame({"A": ['abc','abd','abe','acd','ace','aci'], "B": ""})

I want write a function that will, for each value in df['A'], check for any match in the list. If a match exists, add "match" for that value in df['B']. So far the for loops I've tried don't seem to be working. For example:
for el in df['A']:
    if el in list:
        df['B'] = "match"
    else:
        pass

This populates every row of df['B'] with "match". Other efforts have not populated df['B'] when there is a match.
Thanks!

A: import pandas as pd

lst = ['abc', 'ace', 'aei']

dct = {"A": ['abc','abd','abe','acd','ace','aci'], "B": ""}

if len(list(set(lst) & set(dct['A']))) != 0:
    dct['B'] = 'match'

print (dct)

Output:
{'A': ['abc', 'abd', 'abe', 'acd', 'ace', 'aci'], 'B': 'match'}

If you still wish to use pandas:
import numpy as np
import pandas as pd

lst = ['abc', 'ace', 'aei']

dct = {"A": ['abc','abd','abe','acd','ace','aci'], "B": ""}

df['B'] = np.where(df['A'].isin(lst), 'match', '')

For partial matches:
lst = ['abc']

dct = {"A": ['abcdef','abd','abe','acd','ace','aci'], "B": ""}

if len([v for v in lst if v in " ".join(dct['A'])]) != 0:
    dct['B'] = 'match'

Output:
{'A': ['abcdef', 'abd', 'abe', 'acd', 'ace', 'aci'], 'B': 'match'}

OP request:
lst = ['abc', 'ace', 'aei']

dct = {"A": ['abcdef','aei','abe','acd','ace','aci'], "B": []}

for test in lst:
    for val in dct['A']:
        if test in val:
            dct['B'].append('match')
        else:
            dct['B'].append('nomatch')

print (dct)

Output:
{'A': ['abcdef', 'aei', 'abe', 'acd', 'ace', 'aci'], 'B': ['match', 'nomatch', 'nomatch', 'nomatch', 'nomatch', 'nomatch', 'nomatch', 'nomatch', 'nomatch', 'nomatch', 'match', 'nomatch', 'nomatch', 'match', 'nomatch', 'nomatch', 'nomatch', 'nomatch']}


text:
Q: Updating expiration with replace / put has no effect on local node I'm using Infinispan 6.0.2's cache and all my cache entries have an expiration date which may change during it's life time. I'm updating the infinispan lifespan with the Cache.replace method:
    manager.begin();
    Data current = cache.get(token);
    Data copy = new Data(current);
    update(copy);
    validTokens.replace(token, copy, copy.getLifespan(), TimeUnit.MILLISECONDS);
    manager.commit();

After observing expiration didn't happen as expected I dumped the cache's internal data structure and found it's local meta data isn't updated across all cache instances in the same way. State on both caches after initial put:
[{
        "entry" : {
            "key" : "2c90c80f-dcfc-4ab9-b1c5-ad7f253923b3",
            "value" : {
                [...]
            },
            "metadata" : {
                "version" : {
                    "topologyId" : 2,
                    "version" : 1
                },
                "lifespan" : 86400000,
                "maxIdle" : 86400000
            },
            "created" : false,
            "lastUsed" : 1458213367042,
            "expired" : false,
            "null" : false,
            "valid" : false,
            "loaded" : false,
            "removed" : false,
            "changed" : false,
            "evicted" : true
        },
        "hash" : 718741768,
        "null" : false,
        "valid" : false,
        "loaded" : false,
        "created" : false,
        "removed" : false,
        "changed" : false,
        "evicted" : true,
        "expired" : false
    }
]

After replacing the entry on the node initiating the replacement:
[{
        "entry" : {
            "key" : "2c90c80f-dcfc-4ab9-b1c5-ad7f253923b3",
            "value" : {
                [...]
            },
            "metadata" : {
                "version" : {
                    "topologyId" : 2,
                    "version" : 2
                },
                "lifespan" : 86400000,
                "maxIdle" : 86400000
            },
            "created" : false,
            "lastUsed" : 1458213394345,
            "expired" : false,
            "null" : false,
            "valid" : false,
            "loaded" : false,
            "removed" : false,
            "changed" : false,
            "evicted" : true
        },
        "hash" : 718741768,
        "null" : false,
        "valid" : false,
        "loaded" : false,
        "created" : false,
        "removed" : false,
        "changed" : false,
        "evicted" : true,
        "expired" : false
    }
]

On the second cache is actually changed:
[{
        "entry" : {
            "key" : "2c90c80f-dcfc-4ab9-b1c5-ad7f253923b3",
            "value" : {
                [...]
            },
            "metadata" : {
                "version" : {
                    "topologyId" : 2,
                    "version" : 2
                },
                "lifespan" : 57314,
                "maxIdle" : 57314
            },
            "created" : false,
            "lastUsed" : 1458213394349,
            "expired" : false,
            "null" : false,
            "loaded" : false,
            "valid" : false,
            "changed" : false,
            "removed" : false,
            "evicted" : true
        },
        "hash" : 1057353610,
        "null" : false,
        "loaded" : false,
        "valid" : false,
        "created" : false,
        "changed" : false,
        "removed" : false,
        "evicted" : true,
        "expired" : false
    }
]

Expiration consequently only happens on the second cache.
Cache configuration used:
builder
        .clustering().cacheMode(CacheMode.REPL_SYNC)
        .transaction().transactionMode(TransactionMode.TRANSACTIONAL)
        .lockingMode(LockingMode.OPTIMISTIC).locking().isolationLevel(IsolationLevel.REPEATABLE_READ)
        .writeSkewCheck(true).versioning().enable()
        .scheme(VersioningScheme.SIMPLE)
        .expiration().enableReaper().wakeUpInterval(1, TimeUnit.MINUTES);


text:
Q: Azure Connect-AzAccount in runbook with managed identity fails I am trying to execute a runbook in an automation account within azure.
I have set a managed identity following the instructions here, then i issue the following in my runbook:
Connect-AzAccount -Identity
Set-AzContext -Subscription Subscription1

As instructed here
But i get the following error:
Set-AzContext : Please provide a valid tenant or a valid subscription.
 At line:134 char:1
 + Set-AzContext -Tenant $tenantId -Subscription $subscriptionId

I pass the tenantId and subscriptionId through as parameters, and have written them out to confirm they are correct.
Can anyone see where I am going wrong?
Update
I have added the owner role to the system assigned managed identity and now it seems to get the connection ok with Dilly B's suggestion below:
$null = Disable-AzContextAutosave -Scope Process # Ensures you do not inherit an AzContext in your runbook

$AzureContext = (Connect-AzAccount -Identity -AccountId $managedIdentity).context  # Connect to Azure with user-assigned managed identity

$connectionResult = Set-AzContext -Subscription $subscriptionId -DefaultProfile $AzureContext

however when i do:
$virtualMachine = Get-AzVM -ResourceGroupName $resourceGroupName -Name $virtualMachineName

I now get the following error:
Get-AzVM : The client '****************' with object id '*****************' does
 not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/******************/resourceGroups/***************/providers/Microsoft.Compute/virtualMachines/************' or the scope is invalid. If access was recently granted, please refresh your credentials.
 ErrorCode: AuthorizationFailed
 ErrorMessage: The client '******************' with object id '*****************************'
 does not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/******************/resourceGroups/**************/providers/Microsoft.Compute/virtualMachines/**************' or the scope is invalid.

A: Please find the sample code below. Hope this helps!
$subscription = "000000-0000-0000-0000-000000000"
$identity = "000000-0000-0000-0000-000000000"

$null = Disable-AzContextAutosave -Scope Process # Ensures you do not inherit an AzContext in your runbook

$AzureContext = (Connect-AzAccount -Identity -AccountId $identity).context  # Connect to Azure with user-assigned managed identity

$connectionResult = Set-AzContext -Subscription $subscription -DefaultProfile $AzureContext

A: Make sure you have up-to-date modules for Az.Accounts (2.10.2), Az.Resources (6.3.0), Az.Automation (1.8.0).
https://learn.microsoft.com/en-us/azure/automation/automation-update-azure-modules


text:
Q: Delete an excel sheet using Apache POI I have to delete a sheet from the Excel file.
Here's my code snippet :
FileInputStream fileStream = new FileInputStream(destFile);
POIFSFileSystem fsPoi = new POIFSFileSystem(fileStream);

HSSFWorkbook workbook = new HSSFWorkbook(fsPoi);

int index = 0;

HSSFSheet sheet = workbook.getSheet("Setup");
if(sheet != null)   {
    index = workbook.getSheetIndex(sheet);
    workbook.removeSheetAt(index);
}
return destFile;

After this I'm getting exactly the same workbook which I passed, without the removal of the sheet "Setup"
Help me resolve this. Any help would be appreciated

A: private void removeOtherSheets(String sheetName, XSSFWorkbook book) {
        for(int i=book.getNumberOfSheets()-1;i>=0;i--){
            XSSFSheet tmpSheet =book.getSheetAt(i);
            if(!tmpSheet.getSheetName().equals(sheetName)){
                book.removeSheetAt(i);
            }
        }
}

A: After editing your workbook, you need to write it again. Try this:-
FileOutputStream output = new FileOutputStream(destFile);
workbook.write(output);
output.close();

Edit:- After writing it back, you can return your destFile.

A: Delete a sheet using Apache POI
//Open file
  FileInputStream inputStream = new FileInputStream(new File(filePath));
  XSSFWorkbook workBook = new XSSFWorkbook(inputStream);

//Delete Sheet
  workBook.removeSheetAt(resultWorkbook.getSheetIndex("SheetToBeDeleted"));

//Save the file
  FileOutputStream outFile =new FileOutputStream(new File(filePath));
  workBook.write(filePath);
  outFile.close();


text:
Q: How to make inner shadow in SwiftUI? How can I use Inner Shadow on a Rectangle()?
        Rectangle()
        .foregroundColor(.green)
        .frame(width: 400, height: 300)

I can only manage to do an Outer Shadow using .shadow

I'm looking for something like this

A: For this problem, I built a modifier for the View protocol and a extension, like below
View+innerShadow.swift
import SwiftUI

extension View {
    func innerShadow(color: Color, radius: CGFloat = 0.1) -> some View {
        modifier(InnerShadow(color: color, radius: min(max(0, radius), 1)))
    }
}

private struct InnerShadow: ViewModifier {
    var color: Color = .gray
    var radius: CGFloat = 0.1

    private var colors: [Color] {
        [color.opacity(0.75), color.opacity(0.0), .clear]
    }

    func body(content: Content) -> some View {
        GeometryReader { geo in
            content
                .overlay(LinearGradient(gradient: Gradient(colors: self.colors), startPoint: .top, endPoint: .bottom)
                    .frame(height: self.radius * self.minSide(geo)),
                         alignment: .top)
                .overlay(LinearGradient(gradient: Gradient(colors: self.colors), startPoint: .bottom, endPoint: .top)
                    .frame(height: self.radius * self.minSide(geo)),
                         alignment: .bottom)
                .overlay(LinearGradient(gradient: Gradient(colors: self.colors), startPoint: .leading, endPoint: .trailing)
                    .frame(width: self.radius * self.minSide(geo)),
                         alignment: .leading)
                .overlay(LinearGradient(gradient: Gradient(colors: self.colors), startPoint: .trailing, endPoint: .leading)
                    .frame(width: self.radius * self.minSide(geo)),
                         alignment: .trailing)
        }
    }

    func minSide(_ geo: GeometryProxy) -> CGFloat {
        CGFloat(3) * min(geo.size.width, geo.size.height) / 2
    }
}

And, for the inner shadow, you just need to add .innerShadow(color:radius)
ContentView.swift
import SwiftUI

struct ContentView: View {

    var body: some View {
        Rectangle()
            .foregroundColor(.green)
            .frame(width: 400, height: 300)
            .innerShadow(color: Color.black.opacity(0.3), radius: 0.05)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: If you want to add shadow only to any specific side.
private struct InnerShadow: ViewModifier {
    var color: Color = .gray
    var topToBottomRadius = 0.0
    var bottomToTopRadius = 0.0
    var leadingToTrailingRadius = 0.0
    var trailingToLeadingRadius = 0.0
    private var colors: [Color] {
        [color.opacity(0.75), color.opacity(0.0), .clear]
    }
    func body(content: Content) -> some View {
        GeometryReader { geo in
            content
                .overlay(LinearGradient(gradient: Gradient(colors: self.colors), startPoint: .top, endPoint: .bottom)
                    .frame(height: self.topToBottomRadius * self.minSide(geo)),
                         alignment: .top)
                .overlay(LinearGradient(gradient: Gradient(colors: self.colors), startPoint: .bottom, endPoint: .top)
                    .frame(height: self.bottomToTopRadius * self.minSide(geo)),
                         alignment: .bottom)
                .overlay(LinearGradient(gradient: Gradient(colors: self.colors), startPoint: .leading, endPoint: .trailing)
                    .frame(width: self.leadingToTrailingRadius * self.minSide(geo)),
                         alignment: .leading)
                .overlay(LinearGradient(gradient: Gradient(colors: self.colors), startPoint: .trailing, endPoint: .leading)
                    .frame(width: self.trailingToLeadingRadius * self.minSide(geo)),
                         alignment: .trailing)
        }
    }
    func minSide(_ geo: GeometryProxy) -> CGFloat {
        CGFloat(3) * min(geo.size.width, geo.size.height) / 2
    }
    }
    extension View {
    func innerShadow(color: Color, topRadius: CGFloat = 0.0, bottomRadius: CGFloat = 0.0, leftRadius: CGFloat = 0.0, rightRadius: CGFloat = 0.0) -> some View {
        modifier(InnerShadow(color: color, topToBottomRadius: min(max(0, topRadius), 1), bottomToTopRadius: min(max(0, bottomRadius), 1), leadingToTrailingRadius: min(max(0, leftRadius), 1), trailingToLeadingRadius:min(max(0, rightRadius), 1)))
    }
}


text:
Q: Codimension of a vector subspace Let be $X$ a vector space. Let $X_0 \subseteq X$ a vector subspace of $X$.
Suppose for a moment that $dim(X)=n$
Show: If $dim (X/X_0)=1$ then exists a linear functional $f:X\to \mathbb{R}$ such that $Kerf=X_0$
Of course is easy to think that if $dim (X/X_0)=1$ then exists a bijection $\ $$g:X/X_0 \to \mathbb{R}$ (linear?). We can use the quotient map and we are done.
Can someone show me an explicit functional g with that properties?
My idea is to think about a function which sends $[x] \to 0$ if $x \in X_0$ for all $y \in X$, and otherwise $[x] \to a$, for all $a \in \mathbb{R}$ because all vectors that are not in $X_0$ should be of the form $ax$.
However I don't how to prove it is linear and even more a bijection.
Thank you very much.

A: Example: $X=\mathbb R_{n-1}[x]$ (polynomials with degré $\leq n-1$.   and  $X_0=x\mathbb R_{n-1}[x]={P \in X/ P(0)=0\}$.
if $\dim (X/X_0)=1$ let $a \in X \backslash X_0$, then $X=\mathbb R a \oplus X_0$. if  $x \in X$  there exist a unique  \lambda_x \in \mathbb R$  and $x_0 \in X_0$ such that $x=\lambda a + x_0$. Put $\phi(x)=\lambda_x$, then $\phi$ is linear map from $X$ to $\mathbb R$  and $\ker \phi= X_0$   so   $$X/X_0 \sim \mathbb R a  \sim  \mathbb R$$

A: Take a basis $\{v_1,v_2,\dots,v_{n-1}\}$ of $X_0$ and complete it to a basis of $X$ by simply taking a vector $v_n\in X$, $v_n\notin X_0$. Define
$$
f(v_i)=\begin{cases}
0 & 1\le i<n\\
1 & i=n
\end{cases}
$$
This is a linear functional with the requested properties.


text:
Q: Flutter in Chrome can't GET url (due to missing headers?) I am trying
http.get(url, headers:{"myHeader": "foo"});

But the Java servlet receives the request with HTTP method OPTIONS instead of GET (?!) and the Chrome network shows "Failed to load response data".  Could it be that setting an explicit header overrides some default headers (like Accept Connection Referer) which are confusing things and if so can I tell Dart to add a header without losing these default headers? Thanks!
Added a pic from Chrome Network to show the missing headers

A: The problem is that as per the CORS protocol the java servlet defaults to not accepting requests from your flutter client. So the fix needs to be applied to the java servlet (and or the web server).
I had to do the same thing with a PHP script running on an Apache web server. I added these two lines to an .htaccess file in the directory containing the script:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "myHeader"

And these two lines to very top of the PHP code:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: myHeader");

I think it's only necessary to update the .htaccess file OR the PHP script, but at this point I'm just relieved to have finally gotten it running.
Not sure what web server you are running on, but for your servlet you should be able to just enter
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Headers", "myHeader");

And that should work.
Note that if it does, you will need to go back later and tighten up the origin value. "*" is a wildcard that allows anyone in. You will (most likely) want to restrict that. I haven't figured that bit out yet. I'll post again when I do.

A: Putting this as another answer because I know what I'm talking about now, and it will confuse things if I replace the first answer, or just make it too long if I add this.
The answer to the question "Could it be that setting an explicit header overrides some default headers (like Accept Connection Referer)?" is, definitely, no.
I've put together three files so you can prove this to yourself. Sorry, the key one is in PHP rather than Java Applet because that's what I'm using. But it is very very simple so if you aren't able to run PHP on your server you can probably rewrite it in Java farily easily. All it does is echo the url, body and headers within a json response, so that you can see what the server sees when you send it something.
.htaccess
#Header set Access-Control-Allow-Origin "*"
#Header set Access-Control-Allow-Methods "POST, GET, PUT, PATCH, DELETE"
#Header set Access-Control-Allow-Headers "From"

These three lines, commented out, just remove the # to enable them, are what you need to "fix". They can either be in this file (in this format) OR in the file below (in that format), commented out, just remove the // to enable them . You only need them in one place or the other, but you do need them somewhere. When you run the Flutter app below with both commented out, it will fail. When you run it with either enabled, it will succeed. And you will be able to see that your server is seeing all your headers, including your custom ones.
echo.php
<?php
//header("Access-Control-Allow-Origin: *");
//header("Access-Control-Allow-Methods: POST, GET, PUT, PATCH, DELETE");
//header("Access-Control-Allow-Headers: From");
//header('Content-type: text/javascript');
echo json_encode(
    (object) array(
        'HTTP_ORIGIN' => $_SERVER['HTTP_ORIGIN'],
        'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'],
        'url' => $_SERVER['PATH_INFO'],
        '$body' => json_decode(file_get_contents('php://input')),
        'headers' => getallheaders(),
    ),
    JSON_PRETTY_PRINT
);
?>

main.dart
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; // add http: ^0.12.1 to dependencies: in the pubspec.yaml file
class User {
  String alpha;
  String bravo;
  User({this.alpha, this.bravo});
  Map<String, dynamic> toMap() => {'alpha': alpha, 'bravo': bravo};
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  void _handleOnPressed() async {
    final String url = 'http://<REPLACE.THIS.WITH.YOUR.DOMAIN.NAME>/api/v1/echo.php/12345';
    final String body = jsonEncode(User(alpha: 'a1', bravo: 'b2').toMap());
    final Map<String, String> headers = {HttpHeaders.fromHeader: 'R Reid'};
    http.Response response = await http.post(url, body: body, headers: headers);
    print('response.statusCode: ${response.statusCode}');
    print('response.body: ${response.body}');
  }
  @override
  Widget build(BuildContext context) => MaterialApp(home: Scaffold(body: RaisedButton(onPressed: _handleOnPressed)));
}

i.e. you have to explicitly allow any 'non-default' headers you want to send in either your applet or in an access control file on your web server.
Note that you will get different results when you run this as the Dart/Flutter app, from a browser address bar, or from something like Postman. Obviously the results you get in your app are the key ones.
Note also that you don't require the Allow-Methods entry if you are just doing GET or POST. But you do need it for the others.
Finally note that once you get everything working, you should tighten up the Allow Origin Access Control. As above (with an asterisk) it is allowing everyone in. The value you get when echoing the origin when connecting via your app will show you what to put in there to restrict it to just your app.


text:
Q: How to import source directory as a database in enterprise architect? I have a source directory of a java open-source software. I want to import that directory as database in Enterprise Architect. In that way class files are converted to tables while maintaining the associations. So that, I can apply different SQL quires to that database to extract code metrics and relationships among tables. I know, it can be done, because many previous students at my university has done that, however, those students aren't reachbale.

A: So, I have found the solution and its very simple. You can not create database of the source code from inside of Enterprise architect. However, you can import Enterprise Architect project file as an database source in SQL server. All the code files will be converted to tables while retaining the associations as Primary and Foreign keys. I have created a short video tutorial how to do that, also the following steps can be followed.

*

*Import source directory as any of template (class diagram) in Enterprise Architect.

*Open MS SQL server management studio and create a new (local) database.

*Import the EA project file (.eapx) as data into that newly created database as
Microsoft Access (Microsoft Jet Database Engine).

*Set database destination as SQL Server Native Client 11.0.

*Select desired tables when asked which tables to import, and finish.


text:
Q: EpPlus Sum Calculation returns a different result I am trying to use SUM() to calculate and retrieve values with EpPlus for verification. However, Excel is showing 586,615.99, While EpPlus seems to show 586,615.86 (Cell "S6123") Am I missing something?
The first line of code works great, the second, not so much. Both numbers match in Excel. Attached, please find an example spreadsheet with the problem. Below is the code used to retrieve the results. Thank you.
using (ExcelPackage excel = new ExcelPackage(fi))
    {
    excel.Workbook.CalcMode = ExcelCalcMode.Automatic;
    excel.Workbook.Calculate();
    decimal dSummaryTotal ;
    decimal dDetailsTotal ;

    //Correct
    dSummaryTotal = Convert.ToDecimal(excel.Workbook.Worksheets[2].Cells["C29"].Text); //586,615.99
    //InCorrect
    dDetailsTotal = Convert.ToDecimal(excel.Workbook.Worksheets[3].Cells["S6123"].Text); // 586,615.86
    }

Sample Spreadsheet


text:
Q: Command failed due to signal: Segmentation fault: 11 after upgrade to Xcode 8 and Swift 3 I've seen a few of these around stackoverflow but none of them solve my problem. I've tried deleting the Derived data, retyping the function, and doing a clean. The only thing that works is commenting out the code but I need the code for my app. The error didn't occur until I updated to Xcode 8 and my code to Swift 3.
1.  While emitting IR SIL function @_TFFC13RLA_Volunteer8TeamsTVC18addBarButtonTappedFT6senderCSo15UIBarButtonItem_T_U0_FCSo13UIAlertActionT_ for expression at [/Volumes/.../Developer/RLA/RLA-Volunteer/RLA Volunteer/TeamsTVC.swift:91:89 - line:109:9] RangeText="{ (action) in
            if let team = alertController.textFields?[0].text {
                if team.characters.count == 0 {
                    let errorAlertController = UIAlertController(title: "Add a team", message: nil, preferredStyle: .alert)
                    self.present(errorAlertController, animated: true, completion: nil)
                    return
                }
                let teamItem = Team(teamName: team)
                let teamsRef = self.ref.child("teams")
                teamsRef.child(team.lowercased()).setValue(teamItem.toDictionary, withCompletionBlock: { (error, success) -> Void in
                    if error != nil {
                        print("Error: \(error!.localizedDescription)")
                    }
                    else {
                        print("Data saved!")
                    }
                })
            }
        }"

The entire function looks like this:
  @IBAction func addBarButtonTapped(sender: UIBarButtonItem) {
        // add teams to list
        let alertController = UIAlertController(title: "Add Team", message: nil, preferredStyle: .alert)
        alertController.addTextField { (textField) in
            textField.placeholder = "Team"
        }
        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        alertController.addAction(UIAlertAction(title: "Add", style: .default, handler: { (action) in
            if let team = alertController.textFields?[0].text {
                if team.characters.count == 0 {
                    let errorAlertController = UIAlertController(title: "Add a team", message: nil, preferredStyle: .alert)
                    self.present(errorAlertController, animated: true, completion: nil)
                    return
                }
                let teamItem = Team(teamName: team)
                let teamsRef = self.ref.child("teams")
                teamsRef.child(team.lowercased()).setValue(teamItem.toDictionary, withCompletionBlock: { (error, success) -> Void in
                    if error != nil {
                        print("Error: \(error!.localizedDescription)")
                    }
                    else {
                        print("Data saved!")
                    }
                })
            }
        }))
        present(alertController, animated: true, completion: nil)
    }

A: For teamItem.toDictionary, try putting teamItem.toDictionary as Any.


text:
Q: Manipulated Underlying Apps or Android OS My initial question dealt with building a translucent view that allowed manipulation of a view below it.  Bluefalcon did an excellent job answering this and helped me understand view mechanics a little better:
How can I interact with elements behind a translucent Android app?
I'm still unsure of how to manipulate an underlying view that is not part of my app.  The effect I'm trying to achieve is like the Screen Filter App:
https://play.google.com/store/apps/details?id=com.haxor&hl=en
In this app, once started, it seems a "filter" view is placed on top of everything but you can still interact with whatever is running under it.  The app store, email, home screen etc.
I currently have getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); in my app's onCreate method.  This seems to get close.  If I swipe on my app nothing updates, but when i back out of the app the home screen updates as if i swiped.
Any help will be greatly appreciated!


text:
Q: Odd Tools and Techniques for System Administrators There's been a lot of questions centering on Software Tools for System Administrators. But I would like to know about any odd physical tools or techniques that you've used; Something that you never expected to be useful, but ended up saving the day.
I'll go first:

A Camera Phone.
An application server had a major power issue that borked the RAID. Many of the disks were offline. Before I took the plunge and forced disks back online, I took a picture of the RAID BIOS screen with my camera phone. Having the exact layout of the RAID stored safely in my pocket, I was able to reset the RAID, and reboot the server.

What odd tools/techniques have you used?


text:
Q: Por que usar short? O tipo short corresponde a um inteiro de 16 bits - é literalmente açúcar sintático para o tipo Int16.
Os processadores atuais são todos 64 bits, mesmo nas máquinas mais low-end. Algumas máquinas antigas ainda têm processadores com arquiteturas de 32 bits.
Até onde entendo (e me corrijam se eu estiver enganado), é mais rápido trabalhar com um inteiro do tamanho da arquitetura do processador na maioria dos casos, devido as otimizações da CPU. I.e.: se eu estiver a somar inteiros de 16 bits, os registros da CPU recebem e tratam blocos de 32 ou 64 bits de qualquer forma, e depois ainda há o trabalho de se zerar todos os bits além do décimo sexto no resultado (supondo não haver tratamento de estouro).
Então, em que situações eu deveria usar o tipo short, e por que?

A: Não que fique mais lento, pois a CPU mesmo sendo de 64 bits, ainda possui instruções para lidar com tipos numéricos menores do que o nativo.
O char do .Net por exemplo, possui 16 bits, o que equivale a um short/ushort.
A vantagem real que vejo em usar os tipos inteiros menores, seria para economizar memória no caso da necessidade de um array com milhões de itens na memória... ou até mesmo bilhões.
Fora isso, é mais pratico usar o tipo int mesmo.

A: O tipo short garante no mínimo 16 bits -- não chega a ser um sinônimo para int16_t.
Só vejo uso para ele quando você precisa interagir com um valor ou estrutura que também seja short, como alguma tabela de hardware, driver de dispositivo ou API de baixo nível. Por exemplo, numa conexão TCP/IP a porta é unsigned short (http://www.gta.ufrj.br/ensino/eel878/sockets/sockaddr_inman.html)
Também acontece muito ao lidar-se com dados vindos da rede, normalmente em conjunção com htons(). Quando se lida com rede, o melhor é usar os tipos de tamanho garantido, tipo int16_t ou uint16_t, que garantem o tamanho exato em bits.

A:
Até onde entendo (e me corrijam se eu estiver enganado), é mais rápido trabalhar com um inteiro do tamanho da arquitetura do processador na maioria dos casos, devido as otimizações da CPU.

Realmente, definir variáveis do tipo short ou char é meio que um desperdício, já que essas variáveis vão viver em um registrador onde cabem bem mais bits. Em geral, se usa short ou char para dados armazenados na memória, onde o tamanho do registrador não importa. O tempo que se gasta para transferir um short da memória pra um registrador é o mesmo tempo que se gasta para ler um int, mas o vetor de shorts vai gastar metade do espaço que o vetor de int.

A: Em geral não há porque usar um short em aplicações, especialmente em .NET.
Um caso para usar é se você tiver um volume muito grande de dados numéricos dentro da faixa que cabe em um short (-32768 à 32767). Repito, em um volume muito grande, diminuir de 4 para 2 bytes pode dar alguma vantagem. Mas note que esse volume precisa realmente ser muito grande mesmo. É muito raro ser necessário. E mesmo que o volume seja grande também precisa ter a necessidade (não ter memória suficiente para usar um int). Senão, é micro-otimização que não vale o esforço.
Se você não sabe como será usado na prática pode ser interessante usar. Bibliotecas costumam usar, porque pode ser que alguém vá usar aquele objeto que tem um número em grande quantidade, você não tem controle sobre isso.
Outro ponto é que essa otimização de uso da memória é válida quando praticamente só vai usar dados short nas suas estruturadas de dados. Se a informação estiver em estruturas mais complexas, onde o campo do tipo short for apenas uma parte do consumo de memória, principalmente se a estrutura for de um tipo de referência (objetos alocados no heap), o ganho certamente não ajudará muito no consumo de memória.
Dependendo da plataforma e a implementação do JITter pode até ter uma piora na performance usando short. Costuma haver um ganho quando o tamanho do dados equivale ao tamanho da palavra do processador. Mas não tente se valer de uma informação sobre implementação, ela pode mudar sem aviso. Se tem um volume muito grande dados que precisam ser manipulados de forma intensa o mais comum é que tenha algum ganho principalmente pela capacidade de guardar mais elementos (o dobro) em cache usando um short do que um int.
Você pode ter perdas, em alguns casos, também por ter que fazer conversões desnecessárias. Boa parte do .NET está melhor preparado para trabalhar com int. Mas o oposto pode tornar o short mais interessante. Se você sabe que vai usar muitos métodos que primariamente trabalham com short o seu uso pode evitar as conversões, mas são raros métodos.
Um caso típico para evitar conversões é quando se está trabalhando com interoperabilidade com código externo que espere um short, principalmente com código C/C++, gerenciado ou não. Interoperabilidade é o caso principal para o qual o short foi criado no .NET.
Documentação.

A: A resposta do Maniero já dá uma excelente visão geral, apenas gostaria de complementar a seguinte parte:

O mais comum se tem um volume muito grande dados que precisam ser manipulados de forma intensa é que tenha algum ganho mais pela capacidade de guardar mais elementos em cache usando um short do que um int.

De um modo geral, a influência de um bom uso da cache na performance de um sistema é algo pra não ser subestimado. Muitas vezes se presta muita atenção à performance local (fazer o cast) e se esquece a performance global (num cache miss, diversos ciclos são desperdiçados - mais do que o overhead de uma instrução extra ou duas, dependendo do caso).
Nada disso contradiz a resposta mencionada: somente se o volume de dados for grande é que há vantagem (embora talvez discorde no que seria "muito" grande). Além disso, é bastante diferente você ter, por exemplo, um array de objetos:
class MeuObjeto {
    Foo foo;
    Bar bar;
    Baz baz;
    short s;
}
MeuObjeto[] array = new MeuObjeto[10000];

Ou um array de shorts:
short[] array = new short[10000];

No primeiro caso, a economia de espaço é mínima - ainda que os objetos estejam em posições contíguas de memória (dependendo do caso, podem não estar) - e isso se o alinhamento da memória não eliminar essa diferença de espaço. O uso de short em vez de int não vai ter um impacto significativo nas cache  misses, de modo que o overhead das operações de cast não terá nenhuma contrapartida positiva.
Já no segundo caso, a história é outra: vai demorar duas vezes mais para você ter um cache miss se você estiver acessando esses elementos sequencialmente, comparado com um array de int. Mesmo para acessos aleatórios, a chance do dado que você quer já estar na cache é duas vezes maior. De modo que, ainda que cada operação individual seja um pouquinho menos eficiente, os ciclos que você "economiza" evitando os misses pode compensar - tornando a operação completa mais rápida.
(Em todo caso, continua valendo o conselho de evitar otimizações prematuras / micro otimizações)