text:
Q: How to make Spring Data Elasticsearch work with java.time.LocalDateTime for date I am using Spring Data support for Elasticsearch. Here is the timestamp field mapping:
@Field(type = FieldType.Date, index = FieldIndex.not_analyzed, store = true,
        format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern ="yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
private LocalDateTime timestamp;

This results in mapping of the field in Elasticsearch as follows:
"timestamp":{"type":"date","store":true,"format":"yyyy-MM-dd'T'HH:mm:ss.SSSZZ"}

When I use java.util.Date instead everything works fine. However, when I switch to java.time.LocalDateTime as above the document sent to Elasticsearch causes an exception. Here is the document (timestamp field only for brevity):
"timestamp": {
    "hour":7, "minute":56, "second":9, "nano":147000000, "year":2017, "month":"FEBRUARY",
    "dayOfMonth":13, "dayOfWeek":"MONDAY", "dayOfYear":44, "monthValue":2, "chronology": {
        "id":"ISO", "calendarType": "iso8601"
    }
}

And the exception:
MapperParsingException[failed to parse [timestamp]]; nested: IllegalArgumentException[unknown property [hour]];
(...)
Caused by: java.lang.IllegalArgumentException: unknown property [hour]

It looks like the pattern is being ignored here when jsonizing the document. Any possible tips? Or perhaps you might know how to use the "built-in" _timestamp field with Spring Data?

A: I was experiencing the similar issue: 'Z' in the date value is treated as a character, so the date parse failed. My solution is using custom pattern to make sure the conversion correct:
@Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
private LocalDateTime dateField;

And if we don't want to repeat the pattern on different fields again and again, we can try to centralize to the conversion logic. Spring Data Elastic Search provide the custom conversion feature, check here for the example.
Basically we can write a converter from String to LocalDateTime, and put the date pattern over there.

A: Check https://github.com/spring-projects/spring-data-elasticsearch/wiki/Custom-ObjectMapper to add JavaTimeModule to your ObjectMapper.
@Configuration
public class ElasticSearchConfiguration {

  @Bean
  public ElasticsearchTemplate elasticsearchTemplate(Client client) {
    return new ElasticsearchTemplate(client, new CustomEntityMapper());
  }

  public static class CustomEntityMapper implements EntityMapper {

    private final ObjectMapper objectMapper;

    public CustomEntityMapper() {
      objectMapper = new ObjectMapper();
      objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
      objectMapper.registerModule(new CustomGeoModule());
      objectMapper.registerModule(new JavaTimeModule());
    }

    @Override
    public String mapToString(Object object) throws IOException {
      return objectMapper.writeValueAsString(object);
    }

    @Override
    public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
      return objectMapper.readValue(source, clazz);
    }
  }
}


text:
Q: parse JSON with GSON returns null Here is my Json :
[
{
"canaldsc":"PHARMA",
"cadenadsc":null,
"formatodsc":"DEL AHORRO",
"estadodsc":null,
"ciudaddsc":"VALLE DE MEXICO",
"regiondsc":"CENTRO SUR",
"proyectotiendaid":null,
"proyectoid":"79",
"planid":"54",
"proyectodsc":"Concurso",
"vigencia":"0000-00-00",
"activo":"1",
"usuarioproyectotiendaid":"65280",
"proyecto":null,
"fechainicio":"2014-03-24",
"lunes":"7",
"martes":"7",
"miercoles":"7",
"jueves":"7",
"viernes":"7",
"sabado":"7",
"domingo":"7"
},
{
"canaldsc":"PHARMA",
"cadenadsc":null,
"formatodsc":"DEL AHORRO",
"estadodsc":null,
"ciudaddsc":"VALLE DE MEXICO",
"regiondsc":"CENTRO SUR",
"proyectotiendaid":null,
"proyectoid":"79",
"planid":"54",
"proyectodsc":"Concurso",
"vigencia":"0000-00-00",
"activo":"1",
"usuarioproyectotiendaid":"65284",
"proyecto":null,
"fechainicio":"2014-03-24",
"lunes":"7",
"martes":"7",
"miercoles":"7",
"jueves":"7",
"viernes":"7",
"sabado":"7",
"domingo":"7"
}
]

In reality, there is more than 2 objects, but I cut it to simplify
My Model Class :
public class PdvResult {
public PdvResult() {
}

public String canaldsc;
public String cadenadsc;
public String formatodsc;
public String estadodsc;
public String ciudaddsc;
public String regiondsc;
public String proyectotiendaid;
public String proyectoid;
public String planid;
public String proyectodsc;
public String vigencia;
public String activo;
public String usuarioproyectotiendaid;
public String proyecto;
public String fechainicio;
public String lunes;
public String martes;
public String miercoles;
public String jueves;
public String viernes;
public String sabado;
public String domingo;
}

It should be corresponds in the names so that the mapping can happen.
In my Java, I use
List<PdvResult> pdvs = (List<PdvResult>)gson.fromJson(reader, new TypeToken<PdvResult>() {}.getType());

but pdvs return null.
What's wrong with my code????

A: Change the line where you parse the JSON, use this:
List<PdvResult> pdvs = gson.fromJson(reader, new TypeToken<List<PdvResult>>() {}.getType());

You are using TypeToken<PdvResult>, and you have to use TypeToken<List<PdvResult>>, otherwise you're trying to parse your JSON into a PdvResult object, while you actually have an array of PdvResult objects!

A: The best way of checking the type of returned JSON object is explained below:

*

*Start form Object class
Object result= gson.fromJson(reader,Object.class);
System.out.println(result.getClass().getName());

*It will return java.lang.ArrayList

*Do the same operation of ArrayList
System.out.println(((ArrayList)result).size());
System.out.println(((ArrayList)result).get(0).getClass().getName());

*Now it will print the name of class stored in ArrayList

*Repeat the same operation till leaf nodes

*Finally form the resultant JSON object as expected by inspecting object and class type

redpajama_set_name: RedPajamaStackExchange


text:
Q: Diagonalizable vs Normal If I have real valued matrix $A$, are these two notions of being Diagonalizable and being Normal equivalent?

A: A real matrix is diagonalizable (over $\mathbb{C}$) by a unitary matrix if and only if it is normal.
But there are non-normal matrices that can be diagonalized by non-unitary matrices. For instance
$$\left[\begin{array}{cc}0 & 1\\2 & 1\end{array}\right] = PDP^{-1}$$
where
$$P = \left[\begin{array}{cc} -1 & 1\\ 1& 2\end{array}\right]$$
 and
$$D=\left[\begin{array}{cc} -1 &0\\0 & 2\end{array}\right].$$


text:
Q: Restrictive relative clause or non-restrictive relative clause? I am wondering whether to use a restrictive relative clause such as:
"Multicopters belong to a family of aircraft called rotorcraft , which also includes helicopters, and although they appear to be similar, a multicopter's design is mechanically much simpler."
or non-restrictive relative clause:
"Multicopters belong to a family of aircraft called rotorcraft that also includes helicopters, and although they appear to be similar, a multicopter's design is mechanically much simpler."
I am leaning toward the latter because the second half of the complete sentence relies on the inclusion of the statement "also includes helicopters" for its meaning.  However, the first part of the sentence ("multicopters belong to a family of rotorcraft") makes sense by itself (i.e. it could be a complete sentence), and the second part of the sentence is really another statement attached with "and".  So I'm not sure.
Would it be better as two separate sentences:
"Multicopters belong to a family of aircraft called rotorcraft, which also includes helicopters; although they appear to be similar, a multicopter's design is mechanically much simpler."
Side-note:  Now I'm going crazy, wondering whether it should be "include" or "includes".  This is why it takes me so long to write anything. sigh

A: 1- Keep you last formulation, it is the best (no ambiguity, two ideas and two sentences) :
"Multicopters belong to a family of aircraft called rotorcraft, which also includes helicopters; although they appear to be similar, a multicopter's design is mechanically much simpler."
2- Too bad for the pseudo-purists forbidding to mix Latin and Greek roots, as if English were not already a mixture of these two languages, and many more ; by the way, a motor-car is an "automobile" in The States (and in France), and craft is neither Latin nor Greek.


text:
Q: Cant read sqlite database in listview android Activity type is "fixed tabs + swipe". I need read data from DB sqlite in my Listvew, which located in fragment xml file (not in main xml). L use my old code from some program, there is a method for creating listview:
public void createList(){
    db = new DB(this);
    db.open();
    String[] from = new String[] {DB.COLUMN_NAME, DB.COLUMN_TIME  };
    int[] to = new int[] { R.id.tvTextName, R.id.tvText_time};
    scAdapter = new SimpleCursorAdapter(this, R.layout.item, null, from, to, 0);
    lvData = (ListView) findViewById(R.id.lvData);
    lvData.setAdapter(scAdapter);
    getSupportLoaderManager().initLoader(0, null, this);
}

In simple activity code works ok, but i don't know how to use that code in fragment activity. I try call that method in main class but that code:
lvData = (ListView) findViewById(R.id.lvData);
    lvData.setAdapter(scAdapter);

i put in fragment class. Program working, but list view is empty. DB is not empty. There is main parts of code:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener, LoaderCallbacks<Cursor> {

    //*****ОСНОВНЫЕ ПЕРЕМЕННЫЕ*****

    private static String TAG = "MainActivity";
    private static final int CM_DELETE_ID = 1;
    private static final int RESET_STOPWATCH = 2;
    static ListView lvData;
    static DB db;
    static SimpleCursorAdapter scAdapter;
    static Context ctx;
    static String[] from = new String[] {DB.COLUMN_NAME, DB.COLUMN_TIME  };
    static int[] to = new int[] { R.id.tvTextName, R.id.tvText_time};

    SectionsPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager
        .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }
        ctx = this;
        createList();
    }

    public void createList(){
        db = new DB(this);
        db.open();
        scAdapter = new SimpleCursorAdapter(this, R.layout.item, null, from, to, 0);Log.d(TAG, "1");
        getSupportLoaderManager().initLoader(0, null, this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            if(position == 0){
                Fragment fragment = new DummySectionFragment();
                Bundle args = new Bundle();
                args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
                fragment.setArguments(args);
                //getSupportLoaderManager().initLoader(0, null, this);
                return fragment;
            }

            if (position == 1)
            {
                Fragment fragment2 = new DummySectionFragment2();
                Bundle args = new Bundle();
                args.putInt(DummySectionFragment2.ARG_SECTION_NUMBER, position + 2);
                fragment2.setArguments(args);
                return fragment2;
            }
            return null;

        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            }
            return null;
        }

    }
    public static class DummySectionFragment extends Fragment{
        public static final String ARG_SECTION_NUMBER = "section_number";
        public DummySectionFragment() {
        }

        static View v;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.activity_tracker,
                    container, false);
            v = inflater.inflate(R.layout.activity_tracker, container, false);
            lvData = (ListView) v.findViewById(R.id.lvData);Log.d(TAG, "2");
            lvData.setAdapter(scAdapter);Log.d(TAG, "3");
            return rootView;
        }
    }

    public static class DummySectionFragment2 extends Fragment {
            //code page 2
        }
    }

    //Класс по управлению БД
    static class MyCursorLoader extends CursorLoader {

        DB db;

        public MyCursorLoader(Context context, DB db) {
            super(context);
            this.db = db;
        }

        @Override
        public Cursor loadInBackground() {
            Cursor cursor = db.getAllData();
            return cursor;
        }

    }

    }

}

A: I have setup a similar application reading database details into a fragment containing a ListView. I have done this through JSON parsing.
Take a look at the following:
public static class EventFragment extends ListFragment {

        ArrayList<HashMap<String, String>> eventsList;
        private String url_all_events = "//url of the location of your database";

        //used a Progressbar to prompt the user that the data is downloading until it downloads.
        private ProgressDialog pDialog;

        JSONParser jParser = new JSONParser();

        // JSON Node names
        private static final String CONNECTION_STATUS = "success";
        private static final String TABLE_EVENT = "Event";
        private static final String pid = "pid";
        private static final String COL_GROUP = "Group";
        private static final String COL_NAME = "Event_Name";
        private static final String COL_DESC = "Event_Desc";
        private static final String COL_DATE = "Event_Date";
        private static final String COL_TIME = "Event_Time";

        JSONArray Events = null;

        public static final String ARG_SECTION_NUMBER = "section_number";

        public EventFragment() {
        }

        public void onStart() {
            super.onStart();

            eventsList = new ArrayList<HashMap<String, String>>();
            new LoadAllEvents().execute();

            // selecting single ListView item
            ListView lv = getListView();

            // Lauching the Event details screen on selecting a single event
            lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // getting values from selected ListItem
                    String ID = ((TextView) view.findViewById(R.id.pid))
                            .getText().toString();

                    Intent intent = new Intent(view.getContext(),
                            EventDetails.class);
                    intent.putExtra(pid, ID);
                    view.getContext().startActivity(intent);
                }
            });
        }

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_events,
                    container, false);

            return rootView;
        }

        class LoadAllEvents extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(getActivity());
                pDialog.setMessage("Just a moment...");
                pDialog.setIndeterminate(true);
                pDialog.setCancelable(true);
                pDialog.show();
            }

            protected String doInBackground(String... args) {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest(url_all_events,
                        "GET", params);

                try {
                    // Checking for SUCCESS TAG
                    int success = json.getInt(CONNECTION_STATUS);

                    if (success == 1) {
                        // products found
                        // Getting Array of Products
                        Events = json.getJSONArray(TABLE_EVENT);
                        // looping through All Contacts
                        for (int i = 0; i < Events.length(); i++) {
                            JSONObject evt = Events.getJSONObject(i);

                            // Storing each json item in variable
                            id = evt.getString(pid);
                            group = evt.getString(COL_GROUP);
                            name = evt.getString(COL_NAME);
                            desc = evt.getString(COL_DESC);
                            date = evt.getString(COL_DATE);
                            time = evt.getString(COL_TIME);

                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            map.put(pid, id);
                            map.put(COL_GROUP, group);
                            map.put(COL_NAME, name);
                            map.put(COL_DESC, desc);
                            map.put(COL_DATE, date);
                            map.put(COL_TIME, time);

                            // adding HashList to ArrayList
                            eventsList.add(map);
                        }
                    } else {
                        // Options are not available or server is down.
                        // Dismiss the loading dialog and display an alert
                        // onPostExecute
                        pDialog.dismiss();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;
            }

            protected void onPostExecute(String file_url) {
                // dismiss the dialog after getting all products
                pDialog.dismiss();
                // updating UI from Background Thread
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        ListAdapter adapter = new SimpleAdapter(getActivity(),
                                eventsList, R.layout.list_item, new String[] {
                                        pid, COL_GROUP, COL_NAME, COL_DATE, COL_TIME },
                                new int[] { R.id.pid, R.id.group, R.id.name, R.id.header,
                                        R.id.title2 });

                        setListAdapter(adapter);
                    }
                });

            }

        }
    }

For the JSON Parser, I used the following class:
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

And finally, this is the xml file for the fragment layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- Main ListView
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Here I have used a Custom Listview so please note that the way I implemented it, may be a little bit complicated.
Hope this helps :)


text:
Q: Where can I get macOS Catalina Beta version? I have a MacBook Pro which came with macOS Mojave pre-installed. I have heard that macOS Catalina is releasing this fall.
I want to use the beta version of it. Where can I get it?

A: Public beta for macOS Catalina is now released by Apple. The same is available to download from Apple Beta Software Program website.
You can find handy guides for installing public betas here:

*

*Guide for Public Betas
To download the macOS Catalina installer, select macOS tab on top of the page and under Get Started section click on enroll your Mac link.

A: If you're not on the Apple Developer Program and you want to test the beta OS, you'll have to wait until the public beta is available.
For macOS and iOS beta versions, the public beta dates have not been announced yet.  You can go to the Apple Beta Signup.  The production release date of Catalina hasn't been announced.


text:
Q: Compare query outputs Query 1:
select name,trans from sids s where apt='KAUS';

Query 2:
SELECT id,transition_id from std_sid_leg where data_supplier='E' and airport='KAUS';

Values of name is same that of id and trans with transition_id.Result set 1 is subset of result set 2.Both the tables have common columns as apt=airport
If query alone couldnt work please provide any script.
I need to compare the outputs of these 2 queries and print the data differences.
Thank you.

A: You're looking for a combined left+right join.
This is called an full outer join (as opposed to a left/right outer join).
By selecting only the rows where join columns are null you'll get the mismatches; this is called an anti-join.
The full outer-anti-join looks like this:
select s.*, ssl.*
from sids s
outer join std_sid_leg ssl on (s.name = ssl.id and s.trans = ssl.transition_id)
where (s.name is null and s.trans is null)
   or (ssl.id is null and ssl.transition_id is null)


text:
Q: system.Net.WebRequest - powershell - and 'The operation has timed out' I need to ask a lot of url`s with powershell and check status code
$Request = $null
$Request= [system.Net.WebRequest]::Create($Url)
$Request.Timeout = 100
$Request.AllowAutoRedirect = $true

 try {

       $Response = $Request.GetResponse()

     } catch [System.Net.WebException] {

       $someexception   = $_.Exception.Message
     }

     $http_status      =  [int]$res.StatusCode

    if ([int]$Response.StatusCode.value__ -ne 200) #если не 200 - алерт
    {
        $state       = 'ERROR'

    }
        else
    {
        $state = 'OK'

    }

$Request.Close

Any way i am trying to use it on server - its ok via manual test, but if i run a lot of scripts (in M$ SCOM for monitoring)  - SOME of them will fail with The operation has timed out
If i will check problem url - it is ok
Why it can time out in case lot of scripts in one time?how to debug it? Its is even http 200 from server logs ..

A: [System.Net.ServicePointManager]::DefaultConnectionLimit = 1024 before the request creation solved the problem.

A: The timeout property that you're setting to 100 is in milliseconds.
That's pretty short. Might want to set it to a few seconds.
It happens because the server side took longer than that amount of time to actually send the data. It may have sent a 200 response but the entire request did not complete in the time allotted. Definitely possible if you're sending a lot of requests at once.


text:
Q: Rotating and moving 2D-objects on mouse drag I wanted to recreate a game (tangram) where you can rotate and move the pieces.
The game can be found on this website: https://de.mathigon.org/tangram
I have found scripts for rotating and moving the object (a png-file) but when I add the two scripts togehter the object moves randomly around. As programme I use Unity.
The script for moving:
using UnityEngine;
using System.Collections;

public class DragDropScript : MonoBehaviour {
private Vector3 screenPoint;
     private Vector3 offset;

     void OnMouseDown()
     {
         Debug.Log("mouse down");
         screenPoint = Camera.main.WorldToScreenPoint(transform.position);
         offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
     }

     void OnMouseDrag()
     {
         Debug.Log("mouse drag");
         Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
         Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
         transform.position = curPosition;

    }
}

And the script for rotating
using UnityEngine;
     using System.Collections;

     public class ObjectRotator : MonoBehaviour
     {

         private float _sensitivity;
         private Vector3 _mouseReference;
         private Vector3 _mouseOffset;
         private Vector3 _rotation;
         private bool _isRotating;

         void Start ()
         {
             _sensitivity = 0.4f;
             _rotation = Vector3.zero;
         }

         void Update()
         {
             if(_isRotating)
             {
                 // offset
                 _mouseOffset = (Input.mousePosition - _mouseReference);

                 // apply rotation
                 _rotation.z = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity;

                 // rotate
                 transform.Rotate(_rotation);

                 // store mouse
                 _mouseReference = Input.mousePosition;
             }
         }

         void OnMouseDown()
         {
             // rotating flag
             _isRotating = true;

             // store mouse
             _mouseReference = Input.mousePosition;
         }

         void OnMouseUp()
         {
             // rotating flag
             _isRotating = false;
         }

     }

So far I struggle with Unity. In my bachelor-thesis I got a HoloLens2 and could use the MRTK which really helped developing a application. Thank you in advanced.
At the end the game should be built as WebGL.

A: The random result is probably due to trying to move and rotate the object at the same time. An easy fix for this would be to move on left mouse button and rotate with right click, or vice versa. You can use Input.GetMouseButton to check if a button is pressed and insert checks in the script to only move OR rotate.
More complicated solutions would involve some kind of "widget" that is dragged, that way you can have different widgets for drag and rotate.
I would also recommend learning a bit of geometry and trigonometry to be able to understand the posted scripts. Copying scripts of the internet will only get you so far.


text:
Q: Identifying an element across pageloads I'm not the sure title of this question is the best, but hopefully this explanation will do a good job of making clear what I'm trying to do. It's 4AM, so plesae forgive and confusion I pass on to you.
Basically what I would like to do is identify if an element that has been selected by the user shows up again on any page of the site. What this is used for is to implement "don't show me again" notices without having to maintain a huge database on the server side for which user hid what notice, and also allow dynamically generated notices to be created.
Giving every notice a unique identifier manually would make dynamic notices impossible, and so a dynamic solution is needed.
The idea I have is to generate a hash of the notice, using something simple to turn the text of the notice into a tidy little hash that can be efficiently stored in localStorage without taking up massive amounts of memory if a large number of notifications are used (or if those notifications contain a lot of text).
Obviously, things like MD5 and SHA-1 are immediate candidates, since they are widely used and there are many example implementations in JavaScript to make up for the fact that such functions are not native.
But they seem kind of overkill to me. Every implementation I have seen defines at least a dozen helper functions to get the job done, and I don't like having code I don't understand being used. Besides, I don't need cryptographic strength, I just need a quick and simple hash.
I've come up with the following:
function hash(str) {
    var l = str.length, i, out = 0;
    for( i=0; i<l; i++) out = (out<<1)^str.charCodeAt(i);
    return out;
}

After some testing with a handful of values, this seems to generate reasonably good hashes. It's clearly consistent: the same input will produce the same output.
What I really would like to know is this: is this a usable hash function? By that I mean, am I at high risk of collisions by using this hash function?

After it being pointed out that << does not rotate, merely shift and discard overflow, the function is now:
function hash(str) {
    var l = str.length, i, out = 0;
    for( i=0; i<l; i++) out = ((out<<1)|(out&0x80000000?1:0))^str.charCodeAt(i);
    return out;
}

This basically implements bit rotation since I don't think there's a built-in operator for that.

A: I tested a few samples and it appears not to be very good, because strings longer than 32 chars with the same ending give the same results.
console.log(hash('Hello world. Lorem ipsum dolor sit amet, consectetur adipiscing elit.'));
console.log(hash('Something entirely different. Lorem ipsum dolor sit amet, consectetur adipiscing elit.'));

For me this yields 721528210 in both cases.
I think this is because you keep destroying bytes by shifting them with <<, while at the same time, the XOR ^ is pairwise. Any letter will change the current 32 bytes, but those will all have been destroyed 32 characters later.


text:
Q: SelectedIndexChanged event without autopostback is true In my application I have used list box as multiselect mode. I need to Fire SelectedIndexChanged event for list box without using
autopostback(AutoPostBack=True)
in c#. How can I do that?

A: Take your List Box into update panel, see below:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:ListBox ID="ListBox1" SelectionMode="Multiple" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" AutoPostBack="true" runat="server">
                <asp:ListItem Text="text 1" Value="0"></asp:ListItem>
                <asp:ListItem Text="text 2" Value="1"></asp:ListItem>
                <asp:ListItem Text="text 3" Value="2"></asp:ListItem>
                <asp:ListItem Text="text 4" Value="3"></asp:ListItem>
                <asp:ListItem Text="text 5" Value="4"></asp:ListItem>
            </asp:ListBox>
        </ContentTemplate>
    </asp:UpdatePanel>


text:
Q: Filter the data for particular 15 days of all years in django I am trying to print the data for particular 15 days of every year.
For example to get the Employee's details who has birthdays with in 15 days.
today = datetime.now()
start_day = today.day
start_month = today.month
end_day = today + timedelta(days=15)
end_date = end_day.day
end_month = end_day.month
user_dob_obj = UserProfile.objects.filter(Q(date_of_birth__month__gte=start_month, date_of_birth__day__gte=start_day) &
         Q(date_of_birth__month__lte=end_month, date_of_birth__day__lte=end_date))

A: Update
Sorry I misunderstood your question. You can use if statement to check if the month is the same 15 days later. Then use the or logical operation to make sure birthdays in current and next month are filtered.
today = datetime.now()
end_date = today + timedelta(days=15)
if today.month == end_date.month:
    user_dob_obj = user_dob_obj.filter(date_of_birth__month=today.month, date_of_birth__day__gte=today.day, date_of_birth__day__lte=end_date.day)
else:
    user_dob_obj = queryset.filter(Q(date_of_birth__month=today.month, date_of_birth__day__gte=today.day) | Q(date_of_birth__month=end_date.month, date_of_birth__day__lte=end_date.day))


text:
Q: Why does setting color on a material with hex string and THREE.Color object produces different results? When I set the color on the material as a Hex String, the mesh is rendered with a color close to what I expect. But when I set it with an instance of THREE.Color(sameHexString), the mesh has a different color.
I have a simplified code that reproduces this:
https://codesandbox.io/s/mystifying-wind-qhp99?file=/src/App.js
With linear on the <Canvas> both meshes are rendered with same color, but a different color than the previous 2.

A: The link to the discussion that @prisoner849 commented described the exact problem. Thanks @prisoner849.
Converting the Color instance solved this problem. For more details follow the discussion.
new THREE.Color(hexString).convertSRGBToLinear()


text:
Q: Audit logging nhibernate could you provide some samples for audit loggin using NHibernate (ASP.Net+C# codd, not java code)

A: Event Listeners are better for audit info than Interceptors. Here's a great example from Ayende's blog.

A: I've most often seen this done with interceptors. There are plenty of blog postings to be found through Google about implementing interceptors for auditing, like this one.


text:
Q: How to encode 8 4bit values into an Int32 and then get those back? How can I put 8 4bit (0..15 or 0..F if you like hex ;) ) values into an Int32 (int) in C# and get those back? I need these for a game that I am writing or more specifically, editor for it (which will feature vertex manipulation like in Notch's failed 0x10c) and since there's already some legacy code and few levels built, I really can't break the format so I can use Int64 and encode 8 8bit values using BitConverter class ;).
I'm not very good at bitwise ops and those who tried to explain these to me so far have failed so yeah. Need help.

A: The main idea is to use left << shift and | to encode and & and right >> shift to decode. Suppose the values are organized as array:
 byte[] data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

 int result = data
   .Select((value, i) => value << (4 * i))
   .Aggregate((x, y) => x | y); // or just .Sum() - Jeppe Stig Nielsen's idea

Edit: for loop implementation:
 int result = 0;

 for (int i = 0; i < data.Length; ++i)
   result |= data[i] << (4 * i);

To retrieve the index-th value (index is in [0..7] range)
 byte item = (byte) ((result >> (index * 4)) & 0xF);

A: If you don't want to think about bitwise operations, you can set up a BitVector32, like this:
var bv = new BitVector32();
var sections = new BitVector32.Section[8];

// Create 8 4-bit sections
sections[0] = BitVector32.CreateSection(15);
for (var i = 1; i < 8; ++i)
{
    sections[i] = BitVector32.CreateSection(15, sections[i - 1]);
}

// Initialize the sections. Values will be 0F, 0D, 0B, ... ,01
for (var i = 0; i < 8; ++i)
{
    bv[sections[i]] = 15 - i*2;
}

// and output results
for (var i = 0; i < 8; ++i)
{
    Console.WriteLine("{0,2}: {1:X2}", i, bv[sections[i]]);
}
Console.WriteLine("bv value = {0:X4}", bv.Data);

After comment
The questions of "conciseness" and performance are somewhat more involved than the comment would suggest. In a working program, the part of this code that sets up the sections could be done once, at program startup. For example:
BitVector32.Section value1 = BitVector32.CreateSection(15);
BitVector32.Section value2 = BitVector32.CreateSection(15, value1);
BitVector32.Section value3 = BitVector32.CreateSection(15, value2);
// set up others here

Then, when you want to access individual values:
BitVector32 bv = new BitVector32(someValue);

// get one value
int myValue = bv[value2];

// set one value
bv[value3] = 42;

Which is more concise than:
int myValue = (someValue >> 4) & 0x0f;
someValue = (someValue & 0xfffff0ff) | (42 << 8);

Performance is an open question. It's quite possible that the JIT compiler can generate inline code for those section operations.


text:
Q: How to pass tcl array to perl command line argument I want to call the perl script from tcl in which i want to send tcl array to perl command line argument and how to use inside in perl script
Thanks,

A: Given the Tcl array
array set ary {foo 11 bar 12 baz 13}

You can pass it to perl like this:
exec perl script.pl {*}[array get ary]

And in perl, you can say
my %hash = @ARGV;

Demonstrating (from a shell prompt):
$ echo '
  array set ary {foo "11 22" bar 12 baz 13}
  puts [exec perl -MData::Dump=dd -e {my %hash = @ARGV; dd \%hash} {*}[array get ary]]
' | tclsh

{ bar => 12, baz => 13, foo => "11 22" }

A: tcl :
set ax(0) 5
set ax(1) 6
set values ""

set names [array names ax]

  foreach xc $names {
    lappend values $ax($xc)
  }

exec perl path_to_perl_script.pl $names $values

perl:
 my @ar1 = split(" ", $ARGV[0]);
 my @ar2 = split(" ", $ARGV[1]);

 my %hash = ();
 my $length = @ar1;

   for (my $i=0; $i < $length; $i++) {
    $hash{$ar1[$i]} = $ar2[$i];
   }

   foreach my $x (keys %hash) {
    print " $hash{$x}\n";
   }

output:
6
5


text:
Q: Style applied for select option in Firefox browser alone? I have select option in my form like below,
<select>
<option class="hdng">Number</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option class="hdng">Alphabets</option>
<option>a</option>
<option>b</option>
<option>c</option>
</select>

in my style i applied style heading,
.hdng
{
font-weight: bold;
padding-top: 10px;
}

Above style is applied in Firefox browser alone. Remaining browsers the style doesn't supported.
Is there any fix for that?

A: It fails for me in Chrome 16 also, consider using optgroups which tend to have better styling support & are semantically correct for what your trying to do.
<select>
<optgroup label="Number">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</optgroup>
<optgroup label="Alphabets">
   <option>a</option>
   <option>b</option>
   <option>c</option>
</optgroup>
</select>

http://jsfiddle.net/sVKjv/1/


text:
Q: OpenCv: change position of putText() I made a deep learning program that uses the webcam to recognize a persons emotion, race and gender. The text shows a persons characteristics is inside of each other. How can I move them underneath each other?

The code
while cap.isOpened():
    ret, frame = cap.read()

    result = DeepFace.analyze(frame,  actions=['emotion', "race", "gender"], enforce_detection=False)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray,1.1,4)

    for(x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (50, 50, 50), 2)
    font = cv2.FONT_HERSHEY_DUPLEX

    cv2.putText(frame,
               result['dominant_emotion'],
               (50, 50),
               font, 1,
               (220, 220, 220),
               2,
               cv2.LINE_4)

    cv2.putText(frame,
               result['gender'],
               (40, 50),
               font, 1,
               (220, 220, 220),
               2,
               cv2.LINE_4)

    cv2.putText(frame,
               result['dominant_race'],
               (30, 50),
               font, 1,
               (220, 220, 220),
               2,
               cv2.LINE_4)

    cv2.imshow('Facial rec.', frame)

    if cv2.waitKey(2) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows

A: Change y - second value in (50,50), (40,50), (30,50)  - ie. (50,50), (50,80), (50,110)

Minimal working code
import cv2

cap = cv2.VideoCapture(0)

while cap.isOpened():
    ret, frame = cap.read()

    result = {'dominant_emotion': 'hello', "gender": 'world', "dominant_race": 'of python'}

    font = cv2.FONT_HERSHEY_DUPLEX

    cv2.putText(frame,
               result['dominant_emotion'],
               (50, 50),
               font, 1,
               (220, 220, 220),
               2,
               cv2.LINE_4)

    cv2.putText(frame,
               result['gender'],
               (50, 80),
               font, 1,
               (220, 220, 220),
               2,
               cv2.LINE_4)

    cv2.putText(frame,
               result['dominant_race'],
               (50, 110),
               font, 1,
               (220, 220, 220),
               2,
               cv2.LINE_4)

    cv2.imshow('Facial rec.', frame)

    if cv2.waitKey(2) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Result:

EDIT:
cv2 has also getTextSize() to calculate text height and use it to set position for next line.
(width, height), baseline = cv2.getTextSize(text, font, font_scale, font_thickness)

import cv2

cap = cv2.VideoCapture(0)

while cap.isOpened():
    ret, frame = cap.read()

    result = {'dominant_emotion': 'hello', "gender": 'world', "dominant_race": 'of python'}

    font = cv2.FONT_HERSHEY_DUPLEX
    font_scale = 1
    font_thickness = 2

    x = 50
    y = 50

    for text in result.values():
        cv2.putText(frame,
                   text,
                   (x, y),
                   font, font_scale,
                   (220, 220, 220),
                   font_thickness,
                   cv2.LINE_4)

        (width, height), baseline = cv2.getTextSize(text, font, font_scale, font_thickness)
        y += (height + 10)  # +10 margin

    cv2.imshow('Facial rec.', frame)

    if cv2.waitKey(2) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


text:
Q: jquery to vanilla js; each loop of html tags So this is my current jquery code, which I would like in vanilla js.
var elems = [];

$("*").not('script, style, iframe').each(function() {
    elems.push($(this)[0]);
});

the closest alternative I found was
document.getElementsByTagName("*")
but that still has iframe, style, and script tags, which I don't want in my array.
Also, I can't just remove them by their tag name specifically, as they might have an id or a class associated with them.

A: One option would be to use a CSS selector along with the .querySelectorAll() method.
Since CSS has a :not() pseudo-class, you could use that to negate the script, style, and iframe elements.
var elements = document.querySelectorAll('*:not(script):not(style):not(iframe');

In the snippet above, elements would be a NodeList containing a collection of the selected elements.


text:
Q: Problem with logistic curve fit using scipy.optimize.curve_fit When I use "fx(vv)" (polynomial), the line on the chart is ok. But when I try to use "fL(vv)", the output line is a horizontal at height of the midpoint of data (x0). Any help is very welcome!
from scipy.optimize import curve_fit
from math import log, e, pi
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

df = pd.read_excel(r'caminho/arquivo.xlsx')
y_data = df['Rating']
x_data = df['P']

#x_data = np.array(x_data)
#y_data = np.array(y_data)

#------------------------ Logística 1PL (Rasch) -----------------------------------
def fL1(x, a, L, x0):
    return L/(1+e**(-a*(x-x0)))
ppL1, covL1 = curve_fit(fL1, x_data, y_data)
print(f'Parâmetros da regressão: {ppL1}')

def fL(x):
    a = ppL1[0]; L = ppL1[1]; x0 = ppL1[2]
    return L/(1+e**(-a*(x-x0)))

# ------------------------- Polinômio ---------------------------
def func2(x, p0, p1, p2, p3, p4, p5, p6, p7, p8):
    return p0 + p1 * x + p2 * x ** 2 + p3 * x ** 3 + p4 * x ** 4 + p5 * x ** 5 + p6 * x ** 6 + p7 * x ** 7 + p8 * x ** 8
pp2, cov2 = curve_fit(func2, x_data, y_data)

def fx(x):
    return pp2[0] + pp2[1]*x + pp2[2]*x**2 + pp2[3]*x**3 + pp2[4]*x**4 + pp2[5]*x**5 + pp2[6]*x**6 + pp2[7]*x**7 + pp2[8]*x**8

modelo = []; x_linha = []; n_range = 100
for ww in range(n_range):
    vv = min(x_data) + (max(x_data)*ww - min(x_data)*ww) / n_range
    modelo.append(fx(vv))
    x_linha.append(vv)

plt.plot(x_linha, modelo, 'red', alpha=0.5)
plt.scatter(x_data, y_data)
plt.tight_layout()
plt.show()


text:
Q: PHP - Fill the arrays in a sequential manner until reaching a maximum length I need to extract data from a text file formatted in a such way, using PHP:
BEGIN
#1
#2
#3
#4
#5
#6
1       2015-05-31  2001-11-24  'Name Surname'      ID_1        0
2       2011-04-01  ?           ?                   ID_2        1
2       2013-02-24  ?           ?                   ID_3        1
2       2014-02-28  ?           'Name Surname'      ID_4        2
END

The informations are organized with the logic of an array like the following:
Array ( [#1] => 1 [#2] => 2015-05-31 [#3] => 2001-11-24 [#4] => 'Name Surname' [#5] => ID_1 [#6] => 0 )
Array ( [#1] => 2 [#2] => 2011-04-01 [#3] => ?           [#4] => ?             [#5] => ID_2 [#6] => 1 )
Array ( [#1] => 2 [#2] => 2013-02-24 [#3] => ?           [#4] => ?             [#5] => ID_3 [#6] => 1 )
Array ( [#1] => 2 [#2] => 2014-02-28 [#3] => ?           [#4] => 'Name Surname' [#5] => ID_4 [#6] => 2 )

I was searching a way to obtain that output. I'm using this code:
<?php
    //ini_set('max_execution_time', 300); //300 seconds = 5 minutes

    function startsWith($str, $char){
        return $str[0] === $char;
    }

    $txt_path = "./test.txt";
    $txt_data = @file_get_contents($txt_path) or die("Could not access file: $txt_path");
    //echo $txt_data;

    $loop_pattern = "/BEGIN(.*?)END/s";
    preg_match_all($loop_pattern, $txt_data, $matches);
    $loops = $matches[0];
    //print_r($loops);
    $loops_count = count($loops);
    //echo $loops_count; // number of loops into the file
    foreach ($loops as $key => $value) {
        $value = trim($value);
        $pattern = array("/[[:blank:]]+/", "/BEGIN(.*)/", "/END(.*)/");
        $replacement = array(" ", "", "");
        $value = preg_replace($pattern, $replacement, $value);
        //print_r($value);
        //echo "

";
        $value_array = explode("\n", $value);
        $value_array_clean = array_filter($value_array, 'strlen');
        $value_array_clean_reindex = array_values($value_array_clean);
        //print_r($value_array_clean_reindex);
        //echo "

";
        $keys = array();
        $values = array();
        foreach ($value_array_clean_reindex as $key => $value) {
            $value = trim($value);
            if ( startsWith($value, "#") ) {
                array_push($keys, $value);
                $keys_count = count($keys);
            } else {
                array_push($values, $value);
                $values_count = count($values);

                $loop_dic = array();
                foreach ($values as $key => $value) {
                    $value = trim($value);
                    preg_match_all("/'(?:.|[^'])*'|\S+/", $value, $matches);
                    //print_r($matches[0]);
                    $loop_dic = array_combine($keys, $matches[0]);
                }

                print_r($loop_dic);
                echo "

";
            }
        }
    }
?>

And it gives me the wanted output:
Array ( [#1] => 1 [#2] => 2015-05-31 [#3] => 2001-11-24 [#4] => 'Name Surname' [#5] => ID_1 [#6] => 0 )
Array ( [#1] => 2 [#2] => 2011-04-01 [#3] => ? [#4] => ? [#5] => ID_2 [#6] => 1 )
Array ( [#1] => 2 [#2] => 2013-02-24 [#3] => ? [#4] => ? [#5] => ID_3 [#6] => 1 )
Array ( [#1] => 2 [#2] => 2014-02-28 [#3] => ? [#4] => 'Name Surname' [#5] => ID_4 [#6] => 2 )

But sometime occurs a problem at level of the command:
$loop_dic = array_combine($keys, $matches[0]);

I understood that, in the original text file, with very long lines, these are broken, generating a new line; instead of:
2       2014-02-28  ?           'Name Surname'      ID_4        2

the line is broken like this:
2       2014-02-28  ?           'Name Surname'
ID_4        2

So, when I explode the string by \n, it occurs an error in the length of the two arrays that then I combine.
I would ask you an alternative to solve this issue, obtaining arrays of equal length, also if a break occurs in the original file.
Seaching on the web, I found array_fill; maybe, if I know (by count) the number of keys in its array for each loop ([#1],...,[#6]), could be possible to loop and fill arrays for values, adding them sequentially until the max lenght of each array for the values.
Thank you for your attention and help.
EDIT #1
Thanks to @fusion3k for his solution!
Checking the behaviour with some input files it shows two other problems:
1)  Analyzing some errors, I discovered that sometime the input file uses double quotes (instead of single quotes), and there are blocks of text in multiple lines between semicolon too, like the following:
;This is some text
in multiline with "double
quotes" too
;

that need to be considered as a single value for a given key, for which the value needs to be inline, like the @fusion3k code do, replacing \n with  (a space). I'm trying to merge the @fusion3k's working code with the one elaborated to solve this behaviour. The file structure could be like this one:
BEGIN
#1
#2
#3
#4
#5
#6
1       2015-05-31  2001-11-24  "Name Surname"      ID_1        0
2       2011-04-01  ?           ?                   ID_2        1
2       2013-02-24  ?           ?                   ID_3        1
2       2014-02-28  ?           "Name Surname"      ID_4        2
;This is some text
in multiline with "double
quotes" too
;
2016-01-22  ?           "Name Surname"      ID_5        2
END

which should generate something like the above working code, but considering the presence of different text block delimitators, like semicolon (;), single quotes (') or, like in some other files, double quotes ("), to delimit a block of text that must be considered as single value for a key, like in this array relative to the above text file content:
Array ( [#1] => Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 2 [4] => This is some text in multiline with "double quotes" too ) [#2] => Array ( [0] => 2015-05-31 [1] => 2011-04-01 [2] => 2013-02-24 [3] => 2014-02-28 [4] => 2016-01-22 ) [#3] => Array ( [0] => 2001-11-24 [1] => ? [2] => ? [3] => ? [4] => ? ) [#4] => Array ( [0] => Name Surname [1] => ? [2] => ? [3] => Name Surname [4] => Name Surname ) [#5] => Array ( [0] => ID_1 [1] => ID_2 [2] => ID_3 [3] => ID_4 [4] => ID_5 ) [#6] => Array ( [0] => 0 [1] => 1 [2] => 1 [3] => 2 [4] => 2 ) )

I worked on a simple string, to find a "working" regular expression that considers (semicolon) AND (single quotes OR double quotes). For now I haven't found files which uses all the three delimitators to delimit block of text, but it seems to be possible to find semicolon+single_quotes OR semicolon+double_quotes OR only single_quotes OR only double_quotes; would be good find a solution with all the three types of delimitators in the same text file...:
$string = 'something here
;and there
;
oh, "that\'s all!"';
$string = str_replace( "\n", " ", $string );
$origin = array("/[[:blank:]]+/", "/\"/", "/;/");
$replacement = array(" ", "\" ", "; ");
$string = preg_replace($origin, $replacement, $string);
$pattern = '/([;"])\s+/';
print_r(array_filter(preg_split( $pattern, $string ), 'strlen'));

This the output (as wanted):
Array ( [0] => something here [1] => and there [2] => oh, [3] => that's all! )

Note the text block between semicolons: it starts always in a new line, with a semicolon at the beginning, and it finishes with a semicolon in a new line, after which starts another newline.
I don't know if it could be written in a better and fastest way... I tried then to merge it with the @fusion3k's code, working on the above text file content, but without success. I tried an if/elseif/else construct like this one:
if ( preg_match('/;(.*?);|\'(.*?)\'/', $value, $matches) ) {// semicolon with single quotes in the $value string
    $value = str_replace( "\n", " ", $value );
    $origin = array("/[[:blank:]]+/", "/'/", "/;/");
    $replacement = array(" ", "' ", "; ");
    $value = preg_replace($origin, $replacement, $value);
    $pattern = '/'.str_repeat( "([;'])\s+", count( $keys ) ).'/';
    print_r(array_filter(preg_split( $pattern, $value ), 'strlen')); // I would have an array of values of the same length of the array for the keys
    echo "

";
} elseif ( preg_match('/;(.*?);|"(.*?)"/', $value, $matches) ) {// semicolon with double quotes in the $value string
    $value = str_replace( "\n", " ", $value );
    $origin = array("/[[:blank:]]+/", "/\"/", "/;/");
    $replacement = array(" ", "\" ", "; ");
    $value = preg_replace($origin, $replacement, $value);
    $pattern = '/'.str_repeat( "([;\"])\s+", count( $keys ) ).'/';
    print_r(array_filter(preg_split( $pattern, $value ), 'strlen')); // I would have an array of values of the same length of the array for the keys
    echo "

";
} else {// neither single quotes (or double quotes) nor semicolon in the $value string
    $pattern = '/'.str_repeat( "(\S+)\s+", count( $keys ) ).'/';
    preg_match_all( $pattern, $value, $matches );
    //print_r($matches);
    //echo "

";
    $loop_dic = array_combine( $keys, array_slice( $matches, 1 ) );
    print_r( $loop_dic ); // this is good...maybe in a better way?
    echo "

";
}

The only working code is the last else, which uses the @fusion3k's code.
2)  The second behaviour (probably already solved), happens when the file is very big. The command:
$loop_pattern = "/BEGIN(.*?)END/s";
preg_match_all($loop_pattern, $txt_data, $matches);
$loops = $matches[0];
//print_r($loops);
$loops_count = count($loops);
//echo $loops_count; // number of loops into the file

does not take all the loops in the files (big file).
Probably the answer is here, I think. So, setting:
ini_set('max_execution_time', 300); // 300 seconds = 5 minutes
ini_set("pcre.backtrack_limit", "100000000"); // default 100k = "100000"

seems to solve it, but I don't know if it's the only way: indeed, if the file is big (17MB or up), there is a little not responding time of the browser (I'm testing on Firefox up to date), before the page has finished loading... Would be good to parse the whole file in blocks until its full size, maybe, but how to do it?
Thank you very much for your attention and help

A: To resolve your problem, common approach is to count retrieved matches and — if they are less than keys — continue the loop without re-init $loop_dic.
I propose you an inverted approach: instead of exploding the string by line, replace newlines with spaces before retrieving values: your string structure is solid enough to allow this approach, and you know the field number, so this approach should work.
The code outside main foreach loop doesn't change. In the same way, the code to retrieve text wrapped by BEGIN ... END is untouched:
foreach( $loops as $key => $value )
{
    $value = trim( $value );
    $pattern = array( "/[[:blank:]]+/", "/BEGIN(.*)/", "/END(.*)/" );
    $replacement = array( " ", "", "" );
    $value = preg_replace( $pattern, $replacement, $value );

To retrieve the keys, we use a preg_match_all(), then we delete relative lines with preg_replace():
    preg_match_all( '/^#\d+/m', $value, $matches );
    $keys = $matches[0];

    $value = preg_replace( '/^#\d+\s*/m', '', $value );

Now, in $value we have only data lines. We replace all newlines with spaces:
    $value = str_replace( "\n", " ", $value );

Then, we construct a row pattern by repeating field pattern for keys number and we retrieve all rows by preg_match_all():
    $pattern = '/'.str_repeat( "('[^']+'|\S+)\s+", count( $keys ) ).'/';
    preg_match_all( $pattern, $value, $matches );

At the end, we use array_slice() to delete global matches, we combine it with $keys and we have desired result. The foreach loop can be closed:
    $values = array_combine( $keys, array_slice( $matches, 1 ) );
}

ideone demo
The main difference between mine $values and your $loop_dic is that in $values main array you have the columns, but if you prefer an array by rows you can easily transform it.
I have tested the code with many different "broken lines", and it works. I suggest you to carefully test it with different strings to see if it works fine in any circumstance.


text:
Q: Are all the heroes summoned by the Horn of Valere ta'veren? Artie Hawkwing is said to be the most powerful ta'veren ever, but what about Brigitte and the others Heroes of the Horn? Do you have to be ta'veren to be bound to the Horn?

A: No.
This has been addressed a few times in interviews, which can be found here:

*

*
Yellowbeard: I did get to ask a question Terez put me up to.
Brandon Sanderson: His answer was no, Heroes of the Horn are not always ta'veren at all in their lifetimes when spun out. Sometimes, they even live normal lives and don't do anything extraordinary, like they sometimes spend their lives as farmers, etc.
 -- TGS Signing Report (paraphrased)

*
Matoyak: Heroes of the Horn, are they corrective mechanisms by themselves, or are they corrective mechanisms by virtue of being ta'veren?
Brandon Sanderson: Heroes are not always ta'veren. So, yes, they are corrective mechanisms by themselves.
-- TGS Signing Report (paraphrased)

It should be noted that the property of being ta'veren is something a person can have in one particular lifetime, and it won't necessarily be preserved when that person is reborn and spun out again by the Wheel. It's possible that some of the Heroes were ta'veren in some lifetimes and not in others.

A: It seems pretty clear that being ta'veren is not a requirement. Brigitte gets a lot of page-time and I don't believe that it's stated or implied anywhere that she's ta'veren.


text:
Q: Suddenly having problems installing packages Ever since I started using LaTeX, I've used the Package Manager that came with MiKTeX to install new packages.
Tonight, I went to install a package multiple times and was told that I couldn't connect to the server. Thinking the server might be down, I tried to connect to a couple of other servers. Every time, I got an error saying "Permission Denied". Does anyone know what's going wrong here? I've never had an issue here before, and I'm not really sure what's happening now.
Also, let me know if you need some other information to help me out... but if you do, please be specific, because I'm not really very savvy with the more technical stuff.


text:
Q: How to show contents of List in ComboBox using Caliburn.micro? I'm having trouble simply showing the contents of my List in the ComboBox using Caliburn.micros BindableCollection. I get three blank options, but when I chose one of them I get the correct value back so I know it's working. Obviously I would also like to see what it is I'm choosing.
I've tried creating a local string and having it = myList[i] in a for loop. I've even created a random string and tried binding it to my TextBlock using the same naming convention, but I just can't get it to work. I won't add that here since it doesn't work. Hopefully one of you can nudge me in the right direction. I'm new to Caliburn, MVVM, binding, etc....
    public List<string> languages = new List<string> {"ENGLISH", "SPANISH", "CHINESE"};

    public BindableCollection<string> Language { get; set; }

    public SettingsViewModel()
    {
        Language = new BindableCollection<string>();

        for (int i = 0; i < languages.Count; i++)
        {
            Language.Add(languages[i]);
        }
    }

//XAML Code\
            <ComboBox ItemsSource="{Binding Language}">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding LanguageOptions}" />
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

A: The problem lies in the following line.
<TextBlock Text="{Binding LanguageOptions}" />

The property Language is  BindableCollection of string. It doesn't have a sub-property called LanguageOptions.
You could instead use the following
<ComboBox ItemsSource="{Binding Language}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
</ComboBox>

Or to make it even more simpler, you could avoid the ItemTemplate. For example,
<ComboBox ItemsSource="{Binding Language}"/>

That would help you fix the Combo Box.


text:
Q: PowerShell Jobs, writing to a file Having some problems getting a Start-Job script block to output to a file. The following three lines of code work without any problem:
$about_name = "C:\0\ps_about_name.txt"
$about = get-help about_* | select Name,Synopsis
if (-not (Test-
Path $about_name)) { ($about | select Name | sort Name | Out-String).replace("[Aa]bout_", "") > $about_name }

The file is created in C:\0\
But I need to do a lot of collections like this, so I naturally looked at stacking them in parallel as separate jobs. I followed online examples and so put the last line in the above as a script block invoked by Start-Job:
Start-Job { if (-not (Test-Path $about_name)) { { ($about | select Name | sort Name | Out-String).replace("[Aa]bout_", "") > $about_name } }
The Job is created, goes to status Running, and then to status Completed, but no file is created. Without Start-Job, all works, with Start-Job, nothing... I've tried a lot of variations on this but cannot get it to create the file. Can someone advise what I am doing wrong in this please?

A: IMO, the simplest way to get around this problem by use of the $using scope modifier.
$about_name = "C:\0\ps_about_name.txt"
$about = get-help about_* | select Name,Synopsis
$sb = { if (-not (Test-Path $using:about_name)) {
          $using:about.Name -replace '^about_' | Sort-Object > $using:about_name
        }
      }
Start-Job -Scriptblock $sb

Explanation:
$using allows you to access local variables in a remote command. This is particularly useful when running Start-Job and Invoke-Command. The syntax is $using:localvariable.
This particular problem is a variable scope issue. Start-Job creates a background job with its own scope. When using -Scriptblock parameter, you are working within that scope. It does not know about variables defined in your current scope/session. Therefore, you must use a technique that will define the variable within the scope, pass in the variable's value, or access the local scope from the script block. You can read more about scopes at About_Scopes.
As an aside, character sets [] are not supported in the .NET .Replace() method. You need to switch to -replace to utilize those. I updated the code to perform the replace using -replace case-insensitively.

HCM's perfectly fine solution uses a technique that passes the value into the job's script block. By defining a parameter within the script block, you can pass a value into that parameter by use of -ArgumentList.

Another option is to just define your variables within the Start-Job script block.
$sb = { $about_name = "C:\0\ps_about_name.txt"
        $about = get-help about_* | select Name,Synopsis
        if (-not (Test-Path $about_name)) {
          $about.Name -replace '^about_' | Sort-Object > $about_name
        }
      }
Start-Job -Scriptblock $sb

A: You've got to send your parameters to your job.
This does not work:
$file = "C:\temp\_mytest.txt"
start-job {"_" | out-file $file}

While this does:
$file = "C:\temp\_mytest.txt"
start-job -ArgumentList $file -scriptblock {
    Param($file)
    "_" | out-file $file
}


text:
Q: Get correct image from Wikidata I use the following query:
SELECT DISTINCT  (SAMPLE(?image)as ?image) ?item ?itemLabel ?itemDescription (SAMPLE(?DR) AS ?DRSample) (SAMPLE(?article) AS ?articleSample)
WHERE{ ?article  schema:about       ?item ; schema:inLanguage  "en" ; schema:isPartOf    <https://en.wikipedia.org/>
    FILTER ( ?item = <//www.wikidata.org/entity/Q303> )
    OPTIONAL { ?item  wdt:P569  ?DR }
    OPTIONAL { ?item  wdt:P570  ?RIP }
    OPTIONAL { ?item  wdt:P18  ?image }
    SERVICE wikibase:label { bd:serviceParam wikibase:language  "en"}}
GROUP BY ?item ?itemLabel ?itemDescription

If I copy image url from result, I get:
https://commons.wikimedia.org/wiki/File:Elvis%20Presley%20promoting%20Jailhouse%20Rock.jpg
but if I look at query response (in Dev Tools), I get:
http://commons.wikimedia.org/wiki/Special:FilePath/Elvis%20Presley%20promoting%20Jailhouse%20Rock.jpg
Why different urls?
Why second http, not https?
Running query in my application I get second result too, but I want first.
And why I get second image from Elvis Presley profile, not first?
Query link


text:
Q: How to remove part of url in htaccess I want to have only last part of URLs in my blog using .htaccess.
https://example.com/blog/category1/category2/postname1
https://example.com/blog/category1/postname2

I want to have only:
https://example.com/blog/postname1
https://example.com/blog/postname2

A: User RewriteRule Rule
The Rule will be like..
RewriteRule ^([a-zA-Z0-9-]+)$  blog/postname1?slug=$1 [L]

Check this url :- How to rewrite url with post title slug?


text:
Q: What is wrong with this proof of continuity of a function of two variables? If a function is define as:
1)$$f(x,y)=\begin{cases} \frac {2xy}{x^2+y^2} &\mbox{for} (x,y)\neq (0,0) \\0 &\mbox{for} (x,y)=(0,0) \end{cases} $$
Then the following proof argument,
$$\frac {2xy}{x^2+y^2}\leq\frac {2x^2y}{x^2+y^2}\leq\frac {2(x^2+y^2)y}{x^2+y^2}=2y$$
As $(x,y) \rightarrow (0,0)$,  $2y=0$
2) $$f(x,y)=\begin{cases} \frac {x+y}{x^2+y^2} &\mbox{for} (x,y)\neq (0,0) \\0 &\mbox{for} (x,y)=(0,0) \end{cases} $$
$$\frac {x+y}{x^2+y^2}\leq\frac {x^2+y|x|}{x^2+y^2}\leq\frac{x^2|y|+y^2|x|}{x^2+y^2}\leq\ \frac{(x^2+y^2)|y|}{x^2+y^2} + \frac{(x^2+y^2)|x|}{x^2+y^2}=|x|+|y|$$
As $(x,y)  \rightarrow  (0,0)$, $|x|+|y|=0$.
I have seen that 1) was not continuous somewhere and I almost positive that I seen that for 2) but I arrive to conclusion that both are continuous.
What is wrong with this proof? or are they in fact continuous? If so, is this a rigorous proof for continuity?

A: Hints:
To prove that your functions are discontinous at $(x,y) = (0,0)$ switch to polar coordinates
$$(x,y)=(r\cos\theta,r\sin\theta)$$
For function 1) we get
$$f_1(x) = \frac{2xy}{x^2+y^2} = 2\cos\theta\sin\theta$$
Now take the limit $(x,y)\to (0,0)$ along any line $y = (\tan\theta) x$ that is $r\to 0$ with $\theta = $ constant. Note that if the limit exists then it has to give the same result no matter how you approach $(0,0)$. The same method can be used for function 2).

A: Note that, if $$\lim\limits_{(x,0)\rightarrow (0,0)}f(x,0)=\lim\limits_{(x,0)\rightarrow (0,0)}\frac{2x.0}{x^2+0^2}=0.$$
But $$\lim\limits_{(x,x)\rightarrow (0,0)}f(x,x)=\lim\limits_{(x,x)\rightarrow (0,0)}\frac{2x^2}{x^2+x^2}=\lim\limits_{(x,x)\rightarrow (0,0)}\frac{2x^2}{2x^2}=1.$$
This implies that if we approach to the point $(0,0)$ from the direction of the line $y=0$ we have a different limit value that the direction of the line $y=x$. Thus, the limit does not exist.


text:
Q: Styles and scripts not working when change route (vue.js + laravel) I have included some scripts in my blade file, but it didn't work, and the reason is that the scripts are loaded before the app.js, but I added defer attribute for tags and it seemed to work fine, but when I change to another route, the style and script stopped working.
<script src="{{asset('assets/admin/app-assets/vendors/js/forms/icheck/icheck.min.js')}}" type="text/javascript" defer></script>

Is there a solution and an explanation for this problem?


text:
Q: Multiple occurance issue in XML Parsing using hive I'm trying to create an Hive table out of XML file using com.ibm.spss.hive.serde2.xml.XmlSerDe. This works quite good for the tags with single occurrence. But I've an issue with multiple occurrence.
Below is my source XML.
<Item>
      <TimeStamp>2016-02-19T12:27:06.387Z</TimeStamp>
      <AlsoSeen End="2014-08-21T13:44:32.557Z" Start="2014-08-21T13:44:04.637Z" />
      <AlsoSeen End="2014-08-21T13:44:33.557Z" Start="2014-08-21T13:45:04.637Z" />
      <AlsoSeen End="2014-08-21T13:44:34.557Z" Start="2014-08-21T13:46:04.637Z" />
      <Title ID="112031424">FAULT IN OUR STARS, THE</Title>
      <FileName>The Fault in Our Stars (2014) EXTENDED HDRip x264 AAC-CPG</FileName>
</Item>

Below is my Hive Table DDL
add jar hivexmlserde-1.0.5.3.jar;

CREATE EXTERNAL TABLE xml_test
(
         Item_TimeStamp String
         ,Item_AS_Start  String
         ,Item_AS_End    String
         ,Item_Title     String
         ,Item_ID        String
         ,Item_Artist    String
         ,Item_Author    String
         ,Item_FileName  String
)
ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
WITH SERDEPROPERTIES (
"column.xpath.Item_TimeStamp"="/Item/TimeStamp/text()",
"column.xpath.Item_AS_Start"="/Item/AlsoSeen/@Start",
"column.xpath.Item_AS_End"="/Item/AlsoSeen/@End",
"column.xpath.Item_Title"="/Item/Title/text()",
"column.xpath.Item_ID"="/Item/Title/@ID",
"column.xpath.Item_FileName"="/Item/FileName/text()"
)
STORED AS
INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
LOCATION '/user/xxxxxx/XML_text'
TBLPROPERTIES (
"xmlinput.start"="<Item>",
"xmlinput.end"="</Item>"
);

When I query the table I get the below value
2016-02-19T12:27:06.387Z <string>2014-08-21T13:44:04.637Z2014-08-21T13:45:04.637Z2014-08-21T13:46:04.637Z</string> <string>2014-08-21T13:44:32.557Z2014-08-21T13:44:33.557Z2014-08-21T13:44:34.557Z</string> FAULT IN OUR STARS, THE 112031424 The Fault in Our Stars (2014) EXTENDED HDRip x264 AAC-CPG

But I expected output should be 3 different lines for 3 difference occurances of AlsoSeen tag as below
2016-02-19T12:27:06.387Z  2014-08-21T13:44:04.637Z 2014-08-21T13:44:32.557Z FAULT IN OUR STARS, THE 112031424 The Fault in Our Stars (2014) EXTENDED HDRip x264 AAC-CPG
2016-02-19T12:27:06.387Z  2014-08-21T13:45:04.637Z 2014-08-21T13:44:33.557Z FAULT IN OUR STARS, THE 112031424 The Fault in Our Stars (2014) EXTENDED HDRip x264 AAC-CPG
2016-02-19T12:27:06.387Z  2014-08-21T13:46:04.637Z 2014-08-21T13:44:34.557Z FAULT IN OUR STARS, THE 112031424 The Fault in Our Stars (2014) EXTENDED HDRip x264 AAC-CPG

Can anyone please help me?

A: The documentation has some examples for this.
https://github.com/dvasilen/Hive-XML-SerDe/wiki/XML-data-sources
Using text() or @Elementname gives you single (primitive) values, and also, your table has been declared as all STRING columns, you may need complex types to hold multiple values, i.e. Map, Struct or Array.
The behaviour you are seeing relates to (5. Complex Types) in the documentation in the link above.

"Complex content being used as a primitive type will be converted to a
  valid XML string by adding a root element called <string>"

In your example, this result you are seeing is the 3 values for the @Start attribute concatenated and then wrapped with the <string> tag:
<string>2014-08-21T13:44:04.637Z2014-08-21T13:45:04.637Z2014-08-21T13:46:04.637Z</string>

Your XPath is using @Start and @End, not the /* pattern though, so I am surprised it worked at all.
I understand the results you want, but I am not sure that it is really matching the way the data is modeled. I think that <Item> is effectively a single row. Item has a <TimeStamp>, and a <Title> which has an @ID attribute, and it also has a property called <AlsoSeen> which can have multiple values for @End & @Start. A straight mapping from XML to Hive table would probably be this complex datatype:
 ARRAY<STRUCT<End: TIMESTAMP, Start: TIMESTAMP>> , an Array of Structs containing End and Start timestamps.
Unfortunately your data doesn't conform to the String format that Hive expects for timestamps, so you can just use STRING, as per https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Types#LanguageManualTypes-timestamp
So you would end up with this table create statement (I've removed the Item_Artist and Item_Author in your original create table because you had no matching xpath for those columns in the SERDEPROPERTIES )
CREATE EXTERNAL TABLE xml_test
(
         Item_TimeStamp String
         ,Item_AlsoSeen ARRAY<STRUCT<End: STRING, Start: STRING>>
         ,Item_Title     String
         ,Item_ID        String
         ,Item_FileName  String
)
ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
WITH SERDEPROPERTIES (
"column.xpath.Item_TimeStamp"="/Item/TimeStamp/text()",
"column.xpath.Item_AlsoSeen"="/Item/AlsoSeen",
"column.xpath.Item_Title"="/Item/Title/text()",
"column.xpath.Item_ID"="/Item/Title/@ID",
"column.xpath.Item_FileName"="/Item/FileName/text()"
)
STORED AS
INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
LOCATION '/user/xxxxxx/XML_text'
TBLPROPERTIES (
"xmlinput.start"="<Item>",
"xmlinput.end"="</Item>"
);

Note the xpath I used for the AlsoSeen field: "/Item/AlsoSeen"
This is the pattern for Arrays and Structs as in the documentation linked above.
It will give you results like
+--------------------+--------------------+--------------------+---------+--------------------+
|      Item_TimeStamp|       Item_AlsoSeen|          Item_Title|  Item_ID|       Item_FileName|
+--------------------+--------------------+--------------------+---------+--------------------+
|2016-02-19T12:27:...|[[2014-08-21T13:4...|FAULT IN OUR STAR...|112031424|The Fault in Our ...|
+--------------------+--------------------+--------------------+---------+--------------------+

The Item_AlsoSeen column contains this, an Array () of Structs [] separated by commas, each struct has the end and the start.
WrappedArray([2014-08-21T13:44:32.557Z,2014-08-21T13:44:04.637Z], [2014-08-21T13:44:33.557Z,2014-08-21T13:45:04.637Z], [2014-08-21T13:44:34.557Z,2014-08-21T13:46:04.637Z])

From there, you can query the result set you wanted by using the  LATERAL VIEW explode() technique
e.g.
SELECT
Item_TimeStamp,
    --Item_AlsoSeen,
    ias.End,
    ias.Start,
    Item_Title,
    Item_ID,
    Item_FileName
FROM xml_test
    LATERAL VIEW explode(Item_AlsoSeen) ias as ias

Note that because I created AlsoSeen as an Array of Struct, the explode() function returns each struct as a row. LATERAL VIEW then effectively does a cross join or probably better called a CROSS APPLY to get a cartesian product.
+--------------------+--------------------+--------------------+--------------------+---------+--------------------+
|      Item_TimeStamp|                 End|               Start|          Item_Title|  Item_ID|       Item_FileName|
+--------------------+--------------------+--------------------+--------------------+---------+--------------------+
|2016-02-19T12:27:...|2014-08-21T13:44:...|2014-08-21T13:44:...|FAULT IN OUR STAR...|112031424|The Fault in Our ...|
|2016-02-19T12:27:...|2014-08-21T13:44:...|2014-08-21T13:45:...|FAULT IN OUR STAR...|112031424|The Fault in Our ...|
|2016-02-19T12:27:...|2014-08-21T13:44:...|2014-08-21T13:46:...|FAULT IN OUR STAR...|112031424|The Fault in Our ...|
+--------------------+--------------------+--------------------+--------------------+---------+--------------------+

Ref Hive Datatypes: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Types

A: There are custom written UDF's which are array_index , numeric_range solves the problem easily. In order to use the functions the column type should be an Array. Please refer the post Hive Explode / Lateral View multiple arrays


text:
Q: Delete image created by Interop Powerpoint in WPF Application I wrote a WPF Application that opens a PowerPoint presentation and save the slides as images to be displayed in a PictureBox. The PictureBox is bounded to ImageBitmap property.
        PowerPoint.Application app = new PowerPoint.Application();
        PowerPoint.Presentations pres = app.Presentations;
        p = pres.Open(FileName, ofalse, ofalse, otrue);
        p.Slides[0].Export(ImagePath, "png", 640, 480);
        ImageBitmap = new BitmapImage(new Uri(ImagePath));

When the application is closed, I would like to delete all the image files created, but instead I got an error: ""The process cannot access the file because it is being used by another process".
I have determined (using ProcessExplorer) that the files were being used only by my application.
I read some suggestions that using the code below will allow the image file (located in ImagePath) to be deleted, but I think this will break MVVM since the viewModel now knows about the View.
        Image im = GetCopyImage(@"D:\Temp\AAAA.jpg");
        myPictureBox.Image = im;
        File.Delete(@"D:\Temp\AAAA.jpg");
        }

        private Image GetCopyImage(string path)
        {
        using (Image im = Image.FromFile(path))
            {
            Bitmap bm = new Bitmap(im);
            return bm;
            }
        }

A: You may set the BitmapCacheOption.OnLoad option during initialization of the BitmapImage. This lets WPF close the image file right after loading the image.
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.UriSource = new Uri(ImagePath);
bitmap.EndInit();
ImageBitmap = bitmap;


text:
Q: VBA excel loop through a range to split name from column I am trying to loop through an entire range (column) in excel to give me an ID by splitting at the "_". This code works for a single row, but I'm not sure how to make it loop through the entire row. File name is the column A as seen below. There are 276 rows that I need to iterate through. It is obviously copying the same thing for 2-276, because I'm only selecting C2 as the range. It will output D28NQ5 for everything. If I change the range to C:C, it does not work.
Sub splitName()
  Dim ImageName As String
  Dim newImageName As String
  Dim ImageNameParts() As String
  Dim ID As String
  Dim sourceSheet As Worksheet

  Columns("A:B").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
  Range("B1").Value = "ID Temp"
  Range("A1").Value = "ID"

  ImageName = Range("C2")
  newImageName = Replace(ImageName, ".", "_")
  ImageNameParts = split(newImageName, "_")

  Range("B2:B276").Value = ImageNameParts(4)

  SensorID = Right(ImageNameParts(4), 6)

  Range("A2:A276").Value = ID

  Set sourceSheet = Sheet1
  sourceSheet.Range("B:C").EntireColumn.Delete

End Sub

File name
CV42231.A.10.1_BAM92D28NQ5.czi - Scene #0.txt
CV42231.A.10.1_BAM92D28NQ5.czi - Scene #0.txt
CV42231.A.10.1_BAM92D28NQ5.czi - Scene #1.txt
CV42231.A.10.1_BAM92D28NQ5.czi - Scene #1.txt
CV42231.A.10.1_BAM92D28NQ5.czi - Scene #0.txt
CV42231.A.10.1_BAM92D28NP2.czi - Scene #0.txt
CV42231.A.10.1_BAM92D28NP2.czi - Scene #1.txt
CV42231.A.10.1_BAM92D28NP2.czi - Scene #1.txt


text:
Q: difference in incrementing pointer with ** and without in C I've got an issue in understanding the difference in  this two ways of incrementing pointers :
int **a;

a++;      //works fine
**a++;    //same here
a += n;   //still good
**a += n; //is not the same and I can't figure out what is going on

I was trying to print parameters of the program in reverse order here
int main(int argc, char **argv)
{
    argv += argc;                 //works fine until it is changed to
                                  //                   **argv += argc
    while (--argc > 0)
    {
        argv--;
        (*argv)--;
        while (*(*argv)++)
            ft_putchar(**argv);
        if (argc - 1 > 0)
            ft_putchar('\n');
    }
    return (1);
}

Summing the question - why the second way is not working the same?

A: What I think is confusing you:
**a++ is parsed as **(a++) while
**a += n is parsed as (**a) += n
This is due to operator precedence
My advice is to always use parenthesis in cases like this to avoid any confusion.
Now on to each case:
Case 1
a++

Pointer arithmetic. Post-increments a
Case 2
**a++

is parsed as **(a++)

*

*it post increments a - Pointer arithmetic

*the result of evaluating (a++) is a - the value before the increment

*then you have a double indirection.

So the above is equivalent (more or less) with the following:
**a;
a = a + 1;

Case 3
a += n

Pointer arithmetic. I would expect self-explanatory.
Case 4
**a += n

This is parsed as
(**a) += n

So you do a double indirection on a getting the value of the pointed integer and then you increase that integer (integer arithmetic).


text:
Q: List comprehension with split Input: ["0:start:0","1:start:2","1:end:5","0:end:6"]
Output: [[0, "start", 0], [1, "start", 2], ... ]
This one [item.split(":") for item in logs] doesn't convert to int. Tried various ways, but cannot make it to work: [(int(a), b, int(c)) for item in logs for (a,b,c) in item.split(":")]
Thanks!

A: You can use a generator expression in the list comprehension:
a = ["0:start:0","1:start:2","1:end:5","0:end:6"]
b = [[int(x[0]), x[1], int(x[2])] for x in (item.split(":") for item in a)]
print(b)

Output:
[[0, 'start', 0], [1, 'start', 2], [1, 'end', 5], [0, 'end', 6]]

My answer was inspired by: List comprehensions splitting loop variable

A: For clarity, I'd do it this way, in two steps:
logs = ["0:start:0", "1:start:2", "1:end:5", "0:end:6"]
split_logs = (log.split(':') for log in logs)
result = [(int(a), b, int(c)) for a, b, c in split_logs]

A: You can add the map function:
[(int(i), j, int(k)) for i, j, k  in map(lambda x: x.split(':'), lst)]

A: Try this one:
 [[int(a), b, int(c)] for a,b,c in [item.split(":") for item in logs]]

You came pretty close!

A: There comes a point where a list comprehension is complex enough that perhaps you really should just use a for loop. However, I think this ends up being pretty readable:
input_list = ['0:start:0', '1:start:2', '1:end:5', '0:end:6']

transformed = [
    [
        int(subitem) if subitem.isdigit() else item
        for part in item.split(':')
    ]
    for item in input_list
]

print(transformed)
>>> [[0, 'start', 0], [1, 'start', 2], [1, 'end', 5], [0, 'end', 6]]

It's one list comprehension nested inside another. The inner one iterates through the subitems of each item in the original list, and converts each one to an int if it contains only digits.


text:
Q: NodeJS : Parsing csv and returning the list through a promise I am trying to parse a csv inside a node server.
I decided to try the csv module, installed using 'npm install csv'
When I execute the code below, the logs display the right value for rows. But I can't manage to export this result through a promise that I can share across my environnement.
var parse = require('csv-parse')
var csvPromise = fs.readFile('path/to/file.csv', function
(err, fileData) {
  return parse(fileData, {}, function(err, rows) {
    console.log('rows', rows, err)
    return rows ;
  })
})

I would like to be able to call the following code in severall places.
csvPromise.then(function (res) {return res ;})

I have tried severall ways but cannot find a solution. How can I manage that ?

A: var parse = require('csv-parse');
const csvPromise = new Promise((resolve, reject) => {
  fs.readFile('path/to/file.csv', (err, fileData) => {
    parse(fileData, {}, function(err, rows) {
      console.log('rows', rows, err)
      resolve(rows) ;
    });
  });
})

hope this helps.


text:
Q: URLConnection or HTTPClient: Which offers better functionality and more efficiency? I am looking to create a login form for an Android application. I want to use a post method to send information to the server side where it is handled by a PHP file; which in turn validates the parameters and sends back a response.
I've looked through implementations using HttpClient and URLConnection, and they are very similar. Which is more efficient for use within an Android app?

A: I believe in this case it's up to whichever API you find more natural. Generally, HTTPClient is more efficient inside a server side application (or maybe batch application), because it allows you to specify a multithreaded connection pool, with a max number of total connections, and a max per host connection count (which ensures concurrent connections to the same host don't get serialized (a problem with HttpUrlConnection)). But in an android app, you'll probably only be making a single connection at a time, so this doesn't matter.

A: I have done a bit of research over this.
I have been using Apache HttpClient for a long time on Android.
It looked like a natural choice to me and I thought that it would be improved over time.
On the other hand, while I was developing for legacy BlackBerry OS, I have been using
HttpUrlConnection.
It was clearly evident to me that the performance of BlackBerry was better than Android in context of networking.
HttpClient is a fully functional, but buggy, class that provides a huge set of APIs/methods. It can be used to create a fully functional web browser for Android. But it has some issues on older versions of Android and it's not actively being contributed to by Google.
Whereas HttpUrlConnection has a pretty useful API that is just useful to develop a networking client application. It has improved response caching and improved compression technique on Android 2.3 and above. It is recommenced when you are building a networking client application.
"Apache HTTPClient has fewer bugs on Android 2.1 (Eclair) and Android 2.2 (Froyo). It is the best choice for these releases.
For Android 2.3 (Gingerbread) and better, HttpURLConnection is the best choice. Its a simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where Google will be spending its energy going forward."
Reference for details
Android's HTTP Clients

A: According to the Android team you should be using HttpURLConnection on Android 2.3 (Gingerbread) and better, since that is where they will put new development effort.
Android's HTTP Clients
These days I have found OkHttp by Square, that includes SPDY support and automatic retries.

A: I would generally recommend URLConnection because it can get updated with the JDK.  In one case we had a call that used an older version of HTTP Client which didn't support TLS v1.2.
However, I wouldn't use URLConnection directly. I would generally use a higher level API like a JAX-RS client or the wsimport clients to connect to another site.

A: If you are not trying to send and receive large files, I'd suggest HttpClient.
It is much easier to get started and use, and there are many more working examples available on the Internet.
NOTE: HttpClient is different from HTTPClient (note case) which is another vendor's implementation.

A: Though the tag is specifically for Android, in general HttpURLConnection is also the better choice when it comes to Java EE applications as it will utilize the HTTP stack that comes with the application server which includes configuration of HTTPS certificates in the application server level rather than the code.
It will also allow you to obtain the latest version of SSLs provided by the application server stack rather than being stuck with an old version of httpclient that may not work with TLS 1.2


text:
Q: UserFrom in Excel, VBA I have a excel with three Sheets, lets call them sheet1, sheet2, sheet3. I have few data points in sheet1, and sheet2 and based on those data points I want to calculate some outcomes in sheet3.
Now I hava created a form in which user could enter the datapoints for sheet1 and sheet2 and on clicking the OK button, sheet3 will be activated and outcomes will be shown.
My questions are:
1. how do i open the userform as soon as the excel file is opened.
2. i dont want to show sheet1 and sheet2 to the user as it also has some propriety datapoints. Given that i have the userform to fill in the required datapoints, how do i hide the actual sheet1 and sheet2?
Thanks in advance.

A: Considering name of the userform to be Userform1, use the below code:
Private Sub Workbook_Open()

    Sheet1.Visible = xlSheetVeryHidden
    Sheet2.Visible = xlSheetVeryHidden
    UserForm1.Show

End Sub


text:
Q: IPathVariableManager.validateValue(URI) returns null in the Eclipse plugin I'm working on I have a piece of code which basically looks like this:
public static void checkProblemV1() {
   try {
      String path = "C:\\temp";
      org.eclipse.core.runtime.IPath value =
         new org.eclipse.core.runtime.Path(path);
      IPathVariableManager pathManager =
         ResourcesPlugin.getWorkspace().getPathVariableManager();
      String name = "somename";
      IStatus statusName = pathManager.validateName(name);
      IStatus statusValue = pathManager.validateValue(value);

      if (statusName == null || statusValue == null) {
         System.err.println("checkProblemV1(): statusName is " +
            (statusName == null ? "null" : ("not null: '" + statusName + "'.")));
         System.err.println("checkProblemV1(): statusValue is " +
            (statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
      }
      else if (statusName.isOK() && statusValue.isOK()) {
         pathManager.setValue(name, value); // setValue is deprecated
         System.out.println("checkProblemV1(): Everything fine");
      }
      else {
         if (!statusName.isOK()) {
            System.err.println("checkProblemV1(): statusName is not OK.");
         }
         if (!statusValue.isOK()) {
            System.err.println("checkProblemV1(): statusValue is not OK.");
         }
      }
   }
   catch (CoreException e) {
      System.err.println("checkProblemV1(): CoreException: " + e.getMessage());
   }
}

When the above method is executed, there are no problems, but I get a deprecation warning for setValue() when compiling. It's when I wanted to fix that deprecation warning by replacing the call to setValue() with a call to setURIValue() that I got into trouble. First I had to tweak how that Windows-style path was written to avoid an URISyntaxException but after doing that, setURIValue() returns null and after having a look in the documentation I can't see that it should do that? I guess the URI is invalid after all but don't know how to fix it. Below is a test method in the same style as the one above demonstrating the problem.
public static void checkProblemV2() {
   try {
      String path = "C:\\temp";
      // Have to replace \ with /, or we get URISyntaxExeption:
      // checkProblemV2(): URISyntaxException: Illegal character in opaque part at index 2: C:\temp
      path = path.replace('\\', '/');
      java.net.URI value = new java.net.URI(path);
      IPathVariableManager pathManager =
         ResourcesPlugin.getWorkspace().getPathVariableManager();
      String name = "somename";
      IStatus statusName = pathManager.validateName(name);
      IStatus statusValue = pathManager.validateValue(value);

      if (statusName == null || statusValue == null) {
         System.err.println("checkProblemV2(): statusName is " +
            (statusName == null ? "null" : ("not null: '" + statusName + "'.")));
         System.err.println("checkProblemV2(): statusValue is " +
            (statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
      }
      else if (statusName.isOK() && statusValue.isOK()) {
         pathManager.setURIValue(name, value);
         System.out.println("checkProblemV2(): Everything fine");
      }
      else {
         if (!statusName.isOK()) {
            System.err.println("checkProblemV2(): statusName is not OK.");
         }
         if (!statusValue.isOK()) {
            System.err.println("checkProblemV2(): statusValue is not OK.");
         }
      }
   }
   catch (URISyntaxException e) {
      System.err.println("checkProblemV2(): URISyntaxException: " + e.getMessage());
   }
   catch (CoreException e) {
      System.err.println("checkProblemV2(): CoreException: " + e.getMessage());
   }
}

When I run the above two methods, I get the following output.
checkProblemV1(): Everything fine
checkProblemV2(): statusName is not null: 'Status OK: unknown code=0 OK null'.
checkProblemV2(): statusValue is null

Thanks for reading and for any help, it's seriously appreciated!

A: There's a bug in org.eclipse.core.internal.resources.PathVariableManager.validateValue(URI) where it is using other internal methods but returning null no matter what else is going on.  Please open a bug with Eclipse Platform/Resources.
And I agree with your comment, you should use:
URI uri = new File("C:\\temp").toURI();
pathManager.setURIValue(theName, uri);


text:
Q: ... and visiting relatives can intrude Could you explain the grammar of this long sentence and the words 'can intrude' and what part of sentence they relate to.

They fish together every spring and early summer, the first two or
  three months of the season, before family vacations, little league
  baseball, and visiting relatives can intrude.

So Much Water So Close to Home
by Raymond Carver


text:
Q: I don't have a monitor; how to play copy-protected content? Let me preface this with the fact that I am totally blind so do not have a monitor hooked up to my computer.
I have a cable card tuner that I would like to use to record and play TV shows. It appears that I can record anything I want but cannot play it back if it has the copy protection flag set since I don't have a monitor hooked up to my computer.
What can I do that will allow me to play back copy-protected content?

A: Do you have HDMI out on your computer? Without knowing the exact issue at hand, you could try getting a device like I bought earlier this year: Monoprice 108204 Mini HDMI Splitter with 3D Support. I like to watch my satellite signal remotely over the internet via my Slingbox. This usually entails the TV being off while the satellite box is on, since no one is actually at home watching this. Most channels would come through fine. Pay channels like HBO, Showtime, Starz, etc. would not; those would display an HDCP message along with a blank image. These channels needed the TV to be powered on.
To combat this, I purchased the powered HDMI splitter and it works perfectly. I can tune those pay channels without the TV being on.
It might help in your case as well.

A: Monitors are pretty cheap, and easy to acquire. If you aren't actually going to be looking at it, a malfunctioning monitor (perhaps with a dead backlight or cracked LCD panel) may be even cheaper.