text:
Q: Control flow and error handling with asynchronous node.js functions I have a function in which a lot of little processes take place independently, but the result of all of them must go into a final callback. It's not a very unreasonable situation; this kind of code where you don't necessarily know ahead of time what's going to run, when, and for how long is rather common, but after hours in front of this I can't figure out a neat way of doing it. I'm not asking for hours of code time, just a simple explanation on how this could be done.
The wrapper function below completes a series of tasks, asynchronous functions, in a way that it is unclear before execution exactly what will run, when, and how many times. I'm trying to find a neat way of calling a callback (final callback comment) once all of them are done completing, if they didn't fail first, but exit the wrapper function immediately on failure. An example of this type of situation would be something like that below.
// Definition for wrapper function
function wrapper(callback) {
    asyncfunction1();
    for(/*conditions*/) {
        asyncfunction2();
    }
    asyncfunction3(function(results) {
        asyncfunction4(results);
        for(res in results) {
            asyncfunction5(res);
        }
    });
}

// Call to wrapper function
wrapper(function(err) {                // final callback
    if (err) console.log("Failure");
    else console.log("Success");
});

The wrapper holds a series of functions (asyncfunction#()) which must all be completed successfully for the callback to be called as callback(false). If any one fails, the callback is called then and there as callback(true) and the whole wrapper exits, without closing the process.
My stumbling blocks:

*

*Is there a way to call the callback upon exit from the wrapper function using a built-in event?

*Is there a native way to exit the wrapper function from several functions deep into it without killing the whole process?

A: I would also suggest using async.js and you'll have some nested calls. Async was made for this type of thing - control flow in NodeJS is tricky. There are other packages for it (promises, other asynchronous packages, etc).
An example using async is below. Note that the outer .series method could be .parallel if your flow can be run in parallel. I like to pass things around in an outer resultsObj that carries over to each async call. It can hold arrays, values, objects, etc . . . just a holder.
I am also using the .series notation where an object of named functions are passed in, rather than an array of functions. The values passed to the callback are stored, which I've used in asyncFunction4.
var resultsObj = {};
async.series( {
  asyncFunction1: function( seriesCb ) {
    //do stuff
    seriesCb();
  },
  asyncFunction2: function( seriesCb ) {
    async.each( yourArray2, function( item, eachCb ) {
      //do stuff
      eachCb();
    }, function( errEach ) {
      resultsObj.someFlag = true;
      seriesCb( errEach );
    } );
  },
  asyncFunction3: function( seriesCb ) {
    callAsyncFunction3( function( results3 ) {
      async.series( {
        asyncFunction4: function( innerSeriesCb ) {
          var results4 = "yes";
          innerSeriesCb( results4 );
        },
        asyncFunction5: function( innerSeriesCb ) {
          async.each( yourArray5, function( item, eachCb ) {
            //do stuff
            eachCb();
          }, function( errEach ) {
            innerSeriesCb( errEach );
          } );
        }
      }, function( innerSeriesErr, innerSeriesResults ) {
        console.log("Result value of async4 was " + innerSeriesResults.asyncFunction4 );
        seriesCb( innerSeriesErr, innerSeriesResults );
      } );
    } );
  }
}, function( seriesErr, seriesResults ) {
  if ( seriesErr ) console.log( "Failure" );
  else console.log( "Success.  results=" + JSON.stringify( resultsObj ) );
} );

EDIT: One more thing. You'll notice how large this control skeleton is already. And that's without code. Break apart your methods and have them accept (and use) the typical NodeJS callback(err) or callback(err, results) style. Then in your async flows, call them in that shorter way. It will just keep this large controlling file a little more manageable.
function doSomething( input1, input2, callback ){
  if( input1 === input2 ) return callback( new Error("Cannot be equal") );
  callback( null, "Success ");
}

async.series( {
  asyncFunction1: function( seriesCb ) {
    doSomething( 1, 2, seriesCb );
  }
}, function( seriesErr, seriesResults ) {
  if ( seriesErr ) console.log( "Failure" );
  else console.log( "Success" );
} );


text:
Q: Brackets plugins not working in Ubuntu 19.04 I am running brackets v14 and the plugin manager is not loading after a fresh install of brackets (through the software center).
In the debug tools I am seeing the following error:
NodeConnection.js:84 WebSocket connection to 'ws://localhost:37055/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

Any ideas on how to debug this?
(in the software center I see many reports with regards to the plugins not working, but no solution so far)
My node version is: 10.15.2

A: This is a known issue of Brackets. you should take it up with his developer:
https://github.com/adobe/brackets/issues/13730
There is a quick fix though : you can change the language under "debug" from "system default" to "English(US)".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show two values in range slider I have input sliders in social context where many people can input to the same slider.
I have set the initial position to be in the middle signifying that the user hasn't input anything. And when the user inputs their value I want to show both their input value and the average of all the input values.
I'm able to save all values and show the average but I want to show two thumbs instead of just the average.
I'm using the bootstrap custom range. The avgValue is calculated after getting ajax data from another function. Actually this function is called inside the function that gets ajax data and at the end html variable is passed to be displayed with the whole article.
function showValues(data) {
var html = "", edit = false, avgValue = 50;

for (let i = 0; i < data.values.length; i++) {
    var value = data.values[i];

    avgValue += Number(value.value)/data.value.length;

    if (values._id == window.user._id){edit = true};
    //                                                //set second thumb to show value
}

html += '';
    html += '<input type="range" class="custom-range" id="customRange" value="' + avgValue + '" />';
html += '';

return html;
}

data.values is an array with objects for each value along with the id of the user who has input the value.
{
    "_id": user._id,
    "value": value
}

The function that sets the value and saves it in monogodb is here
function setValue(self) {
    var _id = self.getAttribute("data-id");
    var value = self.childNodes[0].value;

    var ajax = new XMLHttpRequest();
    ajax.open("POST", "/setValue", true);

    ajax.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

            // var response = JSON.parse(this.responseText);
            //                                                //set second thumb to show value
        }
    };

    var formData = new FormData();
    formData.append("accessToken", localStorage.getItem("accessToken"));
    formData.append("_id", _id);
    formData.append("value", value);
    ajax.send(formData);
}

Do I need to use some other kind of range slider other than bootstrap custom range or can this be modified to my needs? How do I add a second thumb with user's actual value and show it alongwith the average?


text:
Q: What is the Brachistochrone curve with an initial velocity? I'm basically trying to solve the opposite of the brachistochrone problem. You know how the  brachistochrone is the shortest path between two points A and B, falling under the influence of gravity? Well I'd essentially like to find the shortest path between two points A and B, however I'd like the object to be travelling upwards (like a projectile).
Essentially, I'm trying to find the curve that minimises the time that a penalty kick in soccer takes between two distinct points. Here is a picture:

I know that the integrand of the T integral is $ds/v$. I'm just not sure how to pose this as a calculus of variations problem. Any help would be much appreciated.


text:
Q: How to display a side nav menu with many sub-categories using PHP and MySQL? Okay I was wondering how can you use PHP and MySQL to create and display a side nav menu with many categories and sub-categories?
I just don't know where to begin coding the PHP code?

First Nested Link

First Nested Link

First Nested Link

Second Nested Link

Second Nested Link

Second Nested Link

Third Nested Link

Third Nested Link

Third Nested Link

Fourth Nested Link

Fourth Nested Link

Fourth Nested Link

Third Nested Link

Third Nested Link

Second Nested Link

Second Nested Link

First Nested Link

First Nested Link

Here is my MySQL tables.
* categories
      id | category_name | description
* sub_categories
      id | parent_id | category_name | description

A: You should only need one table for your categories; just set the parent_id field to null for top-level categories.
As for actually generating the HTML, you can do something along these lines (pseudocode), where $category_data is the results of the query in a two-dimensional array and $category_id is the id of the parent category being generated.  To kick it off, use $category_id = 0
function print_category($category_data, $category_id)
{
    print "
";
    foreach ($category_data as $category)
    {
        if ((integer)$category['parent_id'] == $category_id)
        {
            print "
" . $category['category_name'] . "
";
            print_category($category_data, $category['id']);
        }
    }
    print "
";
}

You'll have to modify that for your own layout and table structure.  You can improve the performance (if you have a huge number of categories) by transforming the array into a three-dimensional array, $category_data[parent_id][id][category_row].


text:
Q: How to parse dhcpd.conf files with python and bicop? I want to edit files (dhcpd.conf, dns files) with python. I was looking for any option and i found bicop library. I try to do:
from bicop import parse
parse("/home/tigov/dhcp/dhcpd.conf")

and i got:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/bicop/config.py", line 83, in parse
    return _Parse(tokenizer, dictclass=dictclass)
  File "/usr/local/lib/python2.6/dist-packages/bicop/config.py", line 141, in _Parse
    raise ParseError, (input.infile, input.lineno, "Unexpected end of file")
bicop.config.ParseError: None[1]: Unexpected end of file

Any ideas what i have to do, or any "bicop how to"? Or maybe another library to do this? (iscpy library doesn't work well for me) Thanks for help and sorry, my english is weak.

A: It looks like the examples for bicop don't work.  Parse only accepts string input.  Try this:
from bicop import parse
parse(open("/home/tigov/dhcp/dhcpd.conf").read())

A: Seems that this answer is helpful here.  bicop does not appear to work for parsing more complex ISC config files, but iscpy seems to
# Here is the file that I'm parsing (which bicop won't parse)
#
# zone "example.com" IN {
#   type master;
#   file "/var/named/example.com";
#   allow-update { none; };
# };

>>> import iscpy
>>> iscpy.ParseISCString(open('./named.conf').read())
{'zone "example.com" IN': {'allow-update': {'none': True},
  'file': '"/var/named/example.com"',
  'type': 'master'}}

A: If you want to modify ISC files in a nice fashion, preserving comments, adapting to existing formatting etc, the confctl utility might be a good choice: https://github.com/trasz/confctl/


text:
Q: Problems converting JSONObject/JSONArray to String array I got a problem with a JSONObject. I'm receiving data from my website to an android app, the JSONParser returns a JSONObject:
public JSONObject makeHttpRequest(String url, String method, HashMap<String, String> params) {

    sbParams = new StringBuilder();
    int i = 0;
    for (String key : params.keySet()) {
        try {
            if (i != 0){
                sbParams.append("&");
            }
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        i++;
    }

    if (method.equals("POST")) {
        // NOT IMPORTANT, WORKS FINE
    } else if(method.equals("GET")) {

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setConnectTimeout(15000);
            conn.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

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

        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

    }

    conn.disconnect();
    return jObj;
}

Here's my getAsync class:
class GetAsync extends AsyncTask<String, String, JSONObject> {

    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL = my_url;

    @Override
    protected JSONObject doInBackground(String... args) {

        JSONObject json = null;

        try {
            HashMap<String, String> params = new HashMap<>();
            Log.d("request", "startingGET");
            json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);

            if (json != null) {
                return json;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return json;
    }

    protected void onPostExecute(JSONObject json) {
         // DUNNO WHAT TO WRITE HERE
    }
}

JSONParser returns:
 D/JSON Parser: result: {"success":1,"message":"Scores downloaded properly","scores":[{"place":"1","nick":"testnick","score":"1149","date":"2016-08-13 14:00:07"},{"place":"2","nick":"testnick","score":"741","date":"2016-08-13 11:35:28"}, [...]

But I want the result as a String[][], HashMap, ArrayList or whatever else that could be useful to show the result as a ranking later. To get rid of the "success" and "message" arrays I can use one of the following lines (I'm not using both at the same time) in the doInBackround or onPostExecute:
json = json.optJSONObject("scores");
JSONArray jsonArray = json.optJSONArray("scores");

And here's where I stopped. Been searching the whole day how to convert it into one of the previously mentioned types. I've even tried iterating a String stream char by char... and there always been a problem. I have no idea what else to try, help me, please.

A: You could create a simple POJO:
public class Ranking {

    private int place;
    private String nick;
    private int score;
    private String date;

    public int getPlace() {
        return place;
    }

    public void setPlace(int place) {
        this.place = place;
    }

    public String getNick() {
        return nick;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

And then do something like this to get a List of Rankings:
List<Ranking> rankingList = new ArrayList<>();

try {
    JSONArray array = json.optJSONArray("scores");

    for (int i = 0; i < array.length(); i++) {
        JSONObject rankingObject = array.getJSONObject(i);

        Ranking ranking = new Ranking();
        ranking.setPlace(rankingObject.getInt("place"));
        ranking.setNick(rankingObject.getString("nick"));
        ranking.setScore(rankingObject.getInt("score"));
        ranking.setDate(rankingObject.getString("date"));

        rankingList.add(ranking);
    }
} catch (JSONException j) {
    j.printStackTrace();
}

// do whatever you want with rankingList

Or use Gson to make the parsing simplier:
String rankingsJson = json.optJSONArray("scores").toString();

List<Ranking> rankingList = new Gson().fromJson(rankingsJson,
            new TypeToken<List<Ranking>>(){}.getType());

A: protected void onPostExecute(JSONObject json) {
     // DUNNO WHAT TO WRITE HERE --> DO THE FOLLOWING :

        JSONArray jsonArray = json.optJSONArray("scores");

        HashMap<String, String>[] resultMap = new HashMap[jsonArray.length()];
        for(int i=0; i<jsonArray.length(); i++){
            String place = jsonArray.getJSONObject(i).getString("place");
            String nick = jsonArray.getJSONObject(i).getString("nick");
            String score = jsonArray.getJSONObject(i).getString("score");
            String date = jsonArray.getJSONObject(i).getString("date");

            resultMap[i] = new HashMap<>();
            resultMap[i].put("place", place);
            resultMap[i].put("nick", nick);
            resultMap[i].put("score", score);
            resultMap[i].put("date", date);

        }
}

Explanation:
jsonArray contains the following data:

[{"date":"2016-08-13
  14:00:07","score":"1149","nick":"testnick","place":"1"},{"date":"2016-08-13
  11:35:28","score":"741","nick":"testnick","place":"2"}]

Note that its length is two in this case.
To access this array you should iterate on jsonArray and get each row/value using jsonArray.getJSONObject(i)
Then each row contains the four items: place, nick, score, date.
I used HashMap[] to store each row in a map. And the map array will store the group of rows.


text:
Q: What is the spectral norm of a random projection times a diagonal? Take $n\ll N$. Let $P$ be an $n\times N$ matrix of iid $\mathcal{N}(0,1)$ random variables, and let $D$ be an $N\times N$ diagonal matrix.
What can be said about the distribution of the largest singular value of $PD$?
When $n=1$, I get concentration inequalities from Lemma 1 of this paper. I would like a probabilistic upper bound for the general case, and I wouldn't be surprised if this is already available in the literature.

A: I think the following answers your question (and more):
http://www-personal.umich.edu/~romanv/papers/product-random-deterministic.pdf


text:
Q: Sliding Unity 3D In my Unity Project I am working on the Controller. I have it all working but I want to add a momentum based slide. So you press ctrl and you slide until your momentum reaches zero. And when you are on a slope you should be able to gain speed.
My Question is, how do I make a sliding mechanic based on momentum?
This is my code so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovment : MonoBehaviour
{
    //Varibels
    [Header("Movement")]
    private float originalSize;
    Rigidbody rb;
    Vector3 movementDirection;
    float moveSpeed;
    bool moving = false;
    [SerializeField] private Transform orentation;
    float horizontalInput;
    float verticalInput;

    [Header("Walking")]
    [SerializeField] private float walkingSpeed;

    [Header("Sprinting")]
    [SerializeField] private float sprintSpeed;
    [SerializeField] private KeyCode sprintKey;
    bool sprintKeyPressed;

    [Header("Jumping")]
    [SerializeField] private float jumpForce;
    [SerializeField] private float jumpColdown;
    bool readyToJump = true;

    [Header("Crouch")]
    [SerializeField] private float crouchSpeed;
    [SerializeField] private float crouchSize;
    [SerializeField] private KeyCode crouchKey;
    bool crouchKeyPressed = false;

    [Header("Slide")]
    [SerializeField] private float slideSpeed;
    [SerializeField] private float slideSize;
    [SerializeField] private KeyCode slideKey;
    bool slideKeyPressed = false;

    [Header("GroundCheck")]
    private bool grounded;
    private float crouchOriginalSize;
    [SerializeField] private LayerMask whatIsGround;
    [SerializeField] private float playerHight;
    [SerializeField] private float groundDrag;

    [Header("Slopes")]
    private RaycastHit slopehit;
    private Vector3 slopeMovementDirection;

    //Update Logics
    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        originalSize = transform.localScale.y;
        rb.freezeRotation = true;
    }

    private void Update()
    {
        grounded = Physics.Raycast(transform.position, Vector3.down, playerHight * 0.5f + 0.2f, whatIsGround);

        stateHandler();
        playerInput();

        if (grounded)
            rb.drag = groundDrag;
        else
            rb.drag = 0;

        slopeMovementDirection = Vector3.ProjectOnPlane(movementDirection, slopehit.normal);
    }
    private void FixedUpdate()
    {
        movingPlayer();
    }

    //Input
    private void playerInput()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");

        if (Input.GetKey(KeyCode.Space))
        {
            jump();
        }
        if (Input.GetKeyDown(crouchKey))
        {
            if (crouchKeyPressed == false)
            {
                startCrouch();
            } else
            {
                stopCrouch();
            }
        }
    }

    public movementState state;
    public enum movementState
    {
        walking,
        sprinting,
        crouching,
        jumping,
        sliding,
        air
    }
    private void stateHandler()
    {
        if (grounded && Input.GetKey(slideKey))
        {
            state = movementState.sliding;
            moveSpeed = slideSpeed;
            startSlide();
        }
        else if (grounded && Input.GetKey(crouchKey))
        {
                state = movementState.crouching;
                moveSpeed = crouchSpeed;
        }
        else if (grounded && Input.GetKey(sprintKey) && !crouchKeyPressed)
        {
            state = movementState.sprinting;
            moveSpeed = sprintSpeed;
        }
        else if (grounded && !crouchKeyPressed)
        {
            state = movementState.walking;
            moveSpeed = walkingSpeed;
        }
        else
        {
            state = movementState.air;
        }
    }

    //What moving do

    private void movingPlayer()
    {
        movementDirection = orentation.right * horizontalInput + orentation.forward * verticalInput;
        if (grounded && state == movementState.sliding)
        {
            rb.AddForce(movementDirection * slideSpeed, ForceMode.VelocityChange);
        }
        else if (grounded)
        {
            rb.AddForce(movementDirection.normalized * moveSpeed * 10f, ForceMode.Force);
        }
    }

    private void jump()
    {
        if (!crouchKeyPressed)
        {
            if (readyToJump == true && grounded == true)
            {

                rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
                rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
                readyToJump = false;
                Invoke(nameof(resetJump), jumpColdown);
            }
        }
    }
    private void resetJump()
    {
        readyToJump = true;
    }
    private void startCrouch()
    {
        transform.localScale = new Vector3(transform.localScale.x, crouchSize, transform.localScale.z);
        rb.AddForce(Vector3.down * 10f, ForceMode.VelocityChange);
        crouchKeyPressed = true;

    }
    private void stopCrouch()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, Vector3.up, out hit, playerHight * 0.5f + 0.3f))
        {} else
        {
            transform.localScale = new Vector3(transform.localScale.x, originalSize, transform.localScale.z);
            crouchKeyPressed = false;

        }
    }
    private void startSlide()
    {
        transform.localScale = new Vector3(transform.localScale.x, slideSize, transform.localScale.z);
        rb.AddForce(Vector3.down * 10f, ForceMode.VelocityChange);
    }

    //onSlope SpeedControl ect
    public bool onSlope()
    {
        if (Physics.Raycast(transform.position, Vector3.down, out slopehit, playerHight * 0.5f + 0.5f))
        {
            if (slopehit.normal != Vector3.up)
            {
                return true;
            }
            return false;
        }
        return false;
    }

}


text:
Q: How to pass array list of data from fragment back to its Activity I have an Activity And I started a Fragment for selecting some list and after selection I want to get List of selected things in fragment.
I used onActivityResult()...!! But it's not working!
Please Help!
This is my Activity Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private RecyclerView foldersRV;
    private RecyclerView.Adapter foldersAdapter;
    private AppCompatButton addFolderBtn;
    private AppCompatTextView hiddenText;
    private List<String> selectedFoldersToHide = new ArrayList<>();
    private static final int REQ_FOR_FOLDERS = 1;

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

    private void initView() {
        addFolderBtn = (AppCompatButton) findViewById(R.id.add_folder_btn);
        hiddenText = (AppCompatTextView) findViewById(R.id.hidden_text_view);

        foldersRV = (RecyclerView) findViewById(R.id.folders_list_recycler_view);
        foldersRV.setVisibility(View.GONE);
        hiddenText.setVisibility(View.VISIBLE);

        addFolderBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_folder_btn:
                moveToFragment(new FoldersHiddenFragment(), "Add Folders Fragment");
        }
    }

    private void moveToFragment(Fragment toFragment, String TAG) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG);
        if (fragment != null && fragment.isVisible()) {
            System.out.println("*** ALREADY there ****");
        } else {
            transaction.replace(R.id.main, toFragment, TAG);
            transaction.addToBackStack(null).commit();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQ_FOR_FOLDERS) {
            selectedFoldersToHide = data.getStringArrayListExtra("FOLDERS_TO_HIDE");
        }
    }

}

And Below is my Fragment Code:
public class FoldersHiddenFragment extends Fragment {
    private View allFoldersView;
    private RecyclerView foldersRV;
    private RecyclerView.Adapter foldersAdapter;
    private AppCompatButton hideFoldersBtn;
    private ArrayList<String> selectedFoldersToHide = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        allFoldersView = inflater.inflate(R.layout.folders_hidden_fragment_view, container, false);
        initView();
        return allFoldersView;
    }

    private void initView() {
        foldersRV = (RecyclerView) allFoldersView.findViewById(R.id.folders_list_recycler_view);
        foldersRV.setHasFixedSize(true);
        foldersRV.setLayoutManager(new LinearLayoutManager(getActivity()));
        MyFiles myFiles = new MyFiles();

        foldersAdapter = new FoldersAdapter(getActivity(), myFiles.getAllDirectoriesNames(), new FoldersAdapter.FileInterface() {
            @Override
            public void getFilesSelected(List<String> folderSelectedList) {
                selectedFoldersToHide = (ArrayList<String>) folderSelectedList;
            }
        });
        foldersRV.setAdapter(foldersAdapter);
        foldersAdapter.notifyDataSetChanged();

        hideFoldersBtn = (AppCompatButton) allFoldersView.findViewById(R.id.hide_folder_btn);

        hideFoldersBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("******** TOTAL SELECTED: " + selectedFoldersToHide.size());
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putStringArrayListExtra("FOLDERS_TO_HIDE", selectedFoldersToHide);
                getActivity().setResult(RESULT_OK, intent);
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
    }
}

A: Create an interface let say PassArrayList and implement it in your Activity.
 public interface passArrayList {
        public void onItemsSelected(List<String> selectedItems);
}

public class MainActivity extends AppCompatActivity implements passArrayList{
    // ...
    @override
    public void onItemsSelected(List<String> selectedItems){
      //your code goes here
    }
}

And in your fragment, add following:
PassArrayList mCallback;

@Override
public void onAttach(Activity activity) {
   super.onAttach(activity);
   mCallback = (PassArrayList) getActivity();
}

@Override
public void onDetach() {
   super.onDetach();
   mCallback = null;
}

And somewhere in your code, when you want to pass your list of songs back to the Activity call the method onItemsSelected() on your mCallback object and pass to this method your ArrayList. Then this ArrayList will come as an argument to the method onItemsSelected() in your Activity and you could make with it anything that you like. But don't forget to nullify link to mCallback in onDetach() hook method to prevent context leak.

A: 1) This is a basic example to pass data from fragment to activity:
In fragment A
((ParentActivity)getActivity()).dispatchInformations(list);

In ParentActivity
public void dispatchInformations(List dataList){

}

2) Or create a interface and implement in activity pass reference to fragment and get the result in activity.

A: The easiest way is use EventBus:
public static class MessageEvent { /* your arraylist here */ }
//Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode in Activity:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
// send event from your Fragment
 EventBus.getDefault().post(new MessageEvent(YourArrayList));


text:
Q: How to use EnumValueOptions in protobuf I'm trying to use the custom options feature in protobuf. I'm not sure if I'm creating the custom option incorrectly, or if I'm trying to retrieve the option incorrectly.
Here's my proto definition:
syntax = "proto3";

import "google/protobuf/descriptor.proto";

package common;

message Foo {
    EventType event_type = 1;
}

enum AuditEventType {
    AuditEventDefault = 0;
    AuditEventError = 1;
    AuditEventInfo = 2;
}

enum EventType {
    Undefined = 0;
    AuditSourceType.Pearl)]
    Lead = 1 [(audit_event_type) = AuditEventInfo];
}

extend google.protobuf.EnumValueOptions {
    AuditEventType audit_event_type = 50000;
}

So in my code, how would I get the the audit_event_type from the event_type field on Foo?
I see examples like such:
func TestExtension(t *testing.T) {
    foo := &Foo{
        EventType: EventType_Lead,
    }

    _, md := descriptor.ForMessage(foo)

    auditEvent, err := proto.GetExtension(md.Options, E_AuditEventType)
    if err != nil {
        t.Error("error:", err)
    }
    t.Log(auditEvent)
}

But I get an error:
error: proto: nil *descriptor.MessageOptions is not extendable


text:
Q: How should I use ExecutionContext to provide flow of my own context? Update:

Found similar question.
I want to implement some services following AmbientContext design pattern for our ASP.NET application.
For example I need user name (like Thread.CurrentPrincipal) to be set once at the very beginning of the request processing and flow between threads when async operations are performed.
Thus I need to attach data to ExecutionContext and then detach it when request is processed.
Unfortuantely, I have no idea, how to do it.

There is only a small hint in documentation:

Internally, the ExecutionContext stores all data that is associated
  with the LogicalCallContext. This allows the LogicalCallContext data
  to be propagated when the ExecutionContext is copied and transferred.

A: I had the same question. I eventually found the CallContext class, which can do this using the LogicalGetData and LogicalSetData methods. Here's a very good article with examples that discusses how to use this class.


text:
Q: yarn "EPERM: operation not permitted, mkdir" when I try to use yarn install it says
warning ........\package.json: No license field
error An unexpected error occurred: "EPERM: operation not permitted, mkdir 'C:\Users\HiteshKumar'".
info If you think this is a bug, please open a bug report with the information provided in "C:\Users\Hitesh Kumar\OneDrive\Desktop\intern\mvp-web\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
screenshot of the error
I was trying to use the command yarn install to install the node modules required for the project.


text:
Q: Firebug can't choose script I messed something up.  In firebug I select the scipts tab, then click on inline and select the script I would like to step through with some break points.  I am reasonably sure I have done this with the script before.
Now after removing and reinstalling firebug, clearing cache etc., scratching my head, when I select any of the scripts, the script briefly shows up and then immediately drops back to the HTML page that includes the script.  If I'm quick, when I select the script I can scroll down and when I stop, it scrolls up, on it's own, line by line and when it reaches the top it goes back to the HTML page that has included the script
So from the screenshot, there are some js scripts below (cropped them out, didn't want to share the names).  I've tried checking and un-checking inline with now result.  I have a feeling it's related to my swiss cheese knowledge of js and web programming.

A: I hate to answer my own question, but I don't want to leave this post incomplete, so feel to improve on the answer.  I don't plan to give myself the check unless there appears to be no further activity.  I found a bug fix at issue #5134, and installed the 1.10.0a6 update found here and one last thing, the auto-scrolling stopped when I toggled the "Break on next" button pictured below. (the yellow pause button below the firebug.

A: Im not sure how can further can I assist without having to see the live site or some codes that may point to some explanation. However, here are some tricks that might help.
I use FirefoxAurora that comes with a tab called Changes. or maybe I install the Firebug extension somewhere. I forgot. But googling it up, this may be it Firediff.
The tab looks like the image attached and it will Diff the changes inside a page and then you might have a clue what's going on. It's detect element/attributes changes (not sure about inline script).
P/s: Somehow it doesn't work now, forgot how I've tested before. The url above have more explanation on this. But do check it out. Its been useful to me last time.


text:
Q: how to save Correlation map generated in pandas I have a correlation map that i generated using this code
#Correlation Plot
corrplot = df.corr()

#Correlation in 4 d.p.
corrplot.style.background_gradient(cmap='Pastel1').set_precision(4)

im trying to save the plot generated but do not know how. I have tried using functions from other posts but to no avail. please advise, thank you


text:
Q: Move SKSpriteNode with CoreMotion I have a SKSpriteNode that represents the user and I'd like this node gets move with the user movement, if the user walks then the node moves in the same direction.
The start position is the center of the view and I think it's possible to make this works with rotationRate, userAcceleration and gravity from CMMotionManager (iOS 7) but I don't know if I'm wrong or what operations I should do with these values.
I appretiate if someone could help me.
Thanks.

A: Now, I'm do
if ([self.motionManager isDeviceMotionAvailable] == YES) {
            [self.motionManager startDeviceMotionUpdatesToQueue:self.queueMotion withHandler:^(CMDeviceMotion *motion, NSError *error) {
                self.xpos = motion.userAcceleration.x * motion.gravity.x * motion.rotationRate.x;
                self.ypos = motion.userAcceleration.y * motion.gravity.y * motion.rotationRate.y;

                [self performSelectorOnMainThread:@selector(updatePosition:) withObject:nil waitUntilDone:YES];
            }];
        }

Then I add these x and y coordinates to the SKSpriteNode position and I move the SKSpriteNode to this final position. What I am getting is that the SKSpriteNode doesn't get move while I'm walking but if I make a hard acceleration it moves but just a moment, if I'm walking with a constant velocity it doesn't get move.


text:
Q: Changing texture on gameobject in Unity using c# script I have created a dressup game in Unity using c# script which changes the texture on the body when I click the change button using the following code:
gotexture = GameObject.Find ("Body");
Texture2D mytexture=(Texture2D) Resources.LoadAssetAtPath("Assets/characters/Female/textures/texture2.tga",typeof(Texture2D));
gotexture.renderer.material.mainTexture = mytexture;

This code changes the texture on the body when I run the project in unity but when I build the project for Windows Phone and run it, the texture doesn't change when button is clicked.
are there any settings of the textures to be changed when using it on Windows Phone? The textures are tga files.

A: When you build the project, your resources are not living in the same file paths as they are in the project. Instead of using Resources.LoadAssetAtPath, just use Resources.Load.
In order to use this though, you need to put anything that you might dynamically load like that under a folder called Resources. For example,
Resources
|___
    -Textures
    -Sound Effects
    -Prefabs
    -etc

Now you can load those assets like so:
Resources.Load("Textures/myTexture");

This is really handy for loading prefabs too! And it should work no matter where you run it.
Note: I believe you omit the file extension when using it like this. I don't quite remember and I'm not in a place where I can test it. If it doesn't work, just play around with the filename until it works.


text:
Q: Is there a way to get Entity Framework to include primary key columns when scaffolding CRUD pages? I have a .net core 3.1 MVC app with EF 6. I am having it create CRUD pages using the "New scaffolded item" feature based on models that were already generated (I'm doing "database first"). The cshtml files it generates never have the primary key columns included, like there's no textboxes and labels made for them. These are not identity columns. Although for the tables that do have identity cols, it would be nice if it included it on the CRUD pages besides Create.
Model:
namespace ABCDashboard.Models
{
    public partial class TableMap
    {
        public string EventOID { get; set; }
        public string FormOID { get; set; }
        public string ItemGroupOID { get; set; }
        public string TableSchema { get; set; }
        public string TableName { get; set; }
        public int? FormOrder { get; set; }
        public int? ItemGroupOrder { get; set; }
    }
}

The .cshtml files for create, details, delete, edit and index leave out EventOID, FormOID, and ItemGroupOID.

A: The solution was to add DatabaseGenerated annotations:
using System.ComponentModel.DataAnnotations.Schema;

namespace ABCDashboard.Models
{
    public partial class TableMap
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public string StudyEventOID { get; set; }
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public string FormOID { get; set; }
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public string ItemGroupOID { get; set; }
        public string TableSchema { get; set; }
        public string TableName { get; set; }
        public int? FormOrder { get; set; }
        public int? ItemGroupOrder { get; set; }
    }
}

This worked on Create, Index and Edit pages for my tables with non-identity PKs. Not sure yet how to have it put the IDs that are identity columns on the pages as well (besides Create) but that's always just one column so it's easier to add that manually.


text:
Q: Update single row of table in template page using ajax in Django I am working on Django project and I have no idea of ajax that how to implement it. The scenario is my db contains a table name "demo" which contains the column stat_id. My database contains the following details:
table name = demo
id int primary key NOT NULL,
stat_id int(11) NOT NULL             #value is 1

Now, the scenario is that I am getting the stat_id value from database and its purpose to show the running and complete button. If python script is running then it will display the running button and if python script has executed it will display the completed button.
status.html:

    <form action = "/modules" method="get">
    {% if status == 1 %}
    {% csrf_token %}
    <button link="submit" class="btn btn-default btn-sm">

    Completed</button>
    </form>
     {% else %}
    <button type="button" class="btn btn-default btn-sm">

    Running</button>
     {% endif %}

views.py:

    def process(request):
     hash_id = request.session.get('hash_id')
     print(hash_id)
     check = request.session.pop('check_status',)
      if hash_id and check:
        stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first()
        if stat:
          stat = stat.stat_id
        print(stat)

      return render(request, 'enroll/status.html', {'status': stat})

urls.py:
path('status', views.process, name='process')

models.py:
class status_mod(models.Model):
  id = models.BigIntegerField(primary_key=True)
  stat_id = models.BigIntegerField()

  class Meta:
    db_table = "demo"

jquery / ajax in my status.html page:

Now, I want to update my table row as situation will be if status == 1 then completed button will display else running. Hence it is working fine without ajax but I have to refresh again and again when process function is executed. So, I want to use ajax in this case to update the table row automatically without reloading it.


text:
Q: Getting the date from PHP's date() function How can I use PHP's date() function to get the next day's date? I can easily get the current day's date. For example, if today is July 14, I would like to get July 15.

A: date('j F', strtotime('+1 day'));

A: date('y-m-d', strtotime('+1 day'));

A: You can use the strtotime function
strtotime("+1 day"); // will give u the next day

A: If you insist on date:
date(' ... your format ... ', time() + 60 * 60 * 24); // WRONG; see edit for proof
then you have a timestamp of tomorrow which you can turn into a formatted date.
EDIT:
regarding the critics for adding (60*60*24).
for($i = 0; $i < 4*365; $i++)
{
   $t = time() + $i*60*60*24;

  if(strtotime("+1 day", $t) != ( $t + (60*60*24) ) )
  {
    echo "x: ".$t,PHP_EOL;
  }
}

shows that indeed it's not sufficient to just add 60*60*24:
x: 1319882214
x: 1332583014
x: 1351331814
x: 1364637414
x: 1382781414
x: 1396087014
x: 1414231014
x: 1427536614

A: <?php

$timestamp = time();
$tomorrow = date("j F", $timestamp+3600*24);

?>


text:
Q: Changing styles of fontawesome icons I am using font awesome icons in my angular code. My code is as follows:
component.ts:
import { faSquare } from '@fortawesome/free-solid-svg-icons';

 faSquare =faSquare;

html:

<fa-icon [icon]="faSquare"</fa-icon>

I want to change width, height and rotate this square by 45 degree. I tried giving styles using inline styling but it is not working. How to do that?

A: You can provide inline styles to the icon as:
    <fa-icon [icon]="faSquare" [styles]="{height: '30px', width: '30px', transform: 'rotate(45deg)'}"></fa-icon>

Output:

You can also refer the Features documentation to explore more.


text:
Q: Flush first and last margin in CSS I would like to make the top element (wether it be a p, img, hx or whatever) flush with the top of the parent element while keeping it's normal separation between it's siblings.
For instance, I have a div full of p elements. Each p element has a top and bottom margin, say 10px. Each p element is separated by 20px (10 from the one above and 10 from the one below). The side effect of this is that the first p is pushed down by 10px and the bottom p is pushed up by 10px.

A: You could also use the :first-child and :last-child pseudo-selectors if that is ok with the browsers you support. Set the margin you want, then replace it for specific elements.
.container p{margin:10px 0;}
.container p:first-child{margin-top:0;}

A: The simplest approach is to use a sibling selector:
p + p {
    margin-bottom: 10px;
    margin-top: 10px;
}

This rule applies to paragraphs only if they come directly after another paragraph. So, this rule doesn't apply to your first paragraph, as it doesn't follow a paragraph.
If you want space between every paragraph, but not before the first and not after the last, use this:
p + p {
    margin-top: 20px;
}

A: The simplest way to accomplish this is to only add bottom margins to your elements. So in your case, every p element would have a 20px bottom margin. This will also retain the 20px spacing between your p elements.
If you wish to remove the extra 20px added to the last p tag then you need to add a negative bottom margin to the container of the p elements.
.container {margin-bottom:-20px;}
.container p {margin-bottom:20px;}

You can also accomplish this by retaining the separate top and bottom margins but it makes your code more complex:
.container {margin-top:-10px; margin-bottom:-10px;}
.container p {margin-top:10px; margin-bottom:10px;}

In addition, this will work in all browsers whereas if you use special selectors, your CSS won't be applied to IE6 and the like.


text:
Q: delete all columns of a dimension except for a specific column I want to make a function which takes a n-dimensional array, the dimension and the column index, and it will return the (n-1)-dimensional array after removing all the other columns of that specific dimension.
Here is the code I am using now
a = np.arange(6).reshape((2, 3))  # the n-dimensional array
axisApplied = 1
colToKeep = 0
colsToDelete = np.delete(np.arange(a.shape[axisApplied]), colToKeep)
a = np.squeeze(np.delete(a, colsToDelete, axisApplied), axis=axisApplied)
print(a)
# [0, 3]

Note that I have to manually calculate the n-1 indices (the complement of the specific column index) to use np.delete(), and I am wondering whether there is a more convenient way to achieve my goal, e.g. specify which column to keep directly.
Thank you for reading and I am welcome to any suggestions.

A: In [1]: arr = np.arange(6).reshape(2,3)
In [2]: arr
Out[2]:
array([[0, 1, 2],
       [3, 4, 5]])

Simple indexing:
In [3]: arr[:,0]
Out[3]: array([0, 3])

Or if you need to used the general axis parameter, try take:
In [4]: np.take(arr,0,axis=1)
Out[4]: array([0, 3])

Picking one element, or a list of elements, along an axis is a lot easier than deleting some.  Look at the code for np.delete.


text:
Q: Where 2 separate columns are in a nested query I am writing SQL filters and have limited space within the User_Condition so I am wondering if it is possible to use an OR before the Nested Query I am running.
Here is an example of the base code that works and an example of what I think I am trying to accomplish.
select *
from tlorder
where detail_line_id = '3806526'
  and (origpc in (select zone_id
                  from zone
                  where (zone_id = origpc
                    and service_type = 'DIRECT' or zone_id = destpc
                    and service_type <> 'DIRECT'))
   or desctpc in (select zone_id
                  from zone
                  where (zone_id = origpc and service_type = 'DIRECT' or
                         zone_id = destpc and service_type <> 'DIRECT')))

Starting with the and clause is the filter value but I am wondering if there is any options for something like this:
select *
from tlorder
where detail_line_id = '3806526'
  and (origpc OR destpc) in (select zone_id
                             from zone
                             where (zone_id = origpc and service_type = 'DIRECT' or
                                    zone_id = destpc and service_type <> 'DIRECT'))

-- Note I cannot edit the highlighted section so that poses the biggest issues.

A: (
    origpc IN (SELECT zone_id FROM zone
    WHERE (  (
            zone_id = origpc
            AND service_type = 'DIRECT'
            )
            OR
            (
            zone_id = destpc
            AND service_type <> 'DIRECT'
            )
          )
    OR destpc IN (SELECT zone_id FROM zone
    WHERE (  (
            zone_id = origpc
            AND service_type = 'DIRECT'
            )
            OR
            (
            zone_id = destpc
            AND service_type <> 'DIRECT'
            )
          )
    )

Based on your screen shot this should work.

A: The best thing to do is add the limiting logic to the where clause of your subquery and change your IN to an EXISTS.  In fact you've already almost done this because of how you're filtering the rows in your subquery.  This should work for you:
select *
  from tlorder
 where detail_line_id = '3806526'
   and EXISTS (select 1
                 from zone
                where (zone_id = origpc and service_type = 'DIRECT') or
                      (zone_id = destpc and service_type <> 'DIRECT')
               )

Note that you can select any value inside the exists I just use 1 because it's simple and won't slow anything down.  Also I made the parentheses inside your where subquery more specific.
To answer your specific question, no it's not possible to use multiple columns on the left side of an IN statement.  However, it is possible on the right hand side of an IN when you aren't using a subquery.  Example:
select *
  from tlorder
 where detail_line_id = '3806526'
   and 123 in (origpc, destpc)


text:
Q: In-/upserting a nested document in MongoDB I'm trying to upsert a nested document (activities) in a structure similar to
{
  "_id" : "123",
  "modules" : {
    "x" : {
    },
    "y" : {
      "activities" : {
        "preview": {
          "createdAt": "2014-10-13 15:21:22.113",
          "data": {}
        }
      }
    },
    "z" : {
      "activities" : {
        "render": {
          "createdAt": "2014-10-15 04:22:25.171",
          "data": {}
        },
        "render": {
          "createdAt": "2014-10-14 02:42:24.132",
          "data": {}
        }
      }
    }
  }
}

I then try
selector = { "_id": id, "modules": module, "activities" }
activity = { "preview": { "data": data }}
Meteor.users.upsert(selector, { $set: activity, $setOnInsert: { "createdAt: new Date()" }})

Which yields
MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: meteor.users.$_id_  dup key: { : "123" }

_id is a unique index key. There are additional fields/documents on the _id 'level' of each user and on the activities 'level' of each module, but none concerning the upsert. Each module is unique. The activities document doesn't exist before the first record is inserted.
With that, I hope someone gets the gist of what I'm trying to accomplish and can help me in the right direction.

A: Upsert is for insert or update(if exist) a new document. It does not apply for a sub-document.
You should just update your document:
selector = { "_id": id, "modules": module, preview : null }
activity = { "preview": { "data": data , "createdAt" : new Date() }}
Meteor.users.update(selector, { $set: 'activity' : activity }})


text:
Q: upload files with ajax and node.js without express Hello guys i'm trying send files with ajax and node but i don't find the info that show me how do!!, i'm now built a script but me can follow more
var server=http.createServer(function(req, res){
    if(req.url==='/upload'){
        if(req.method==='OPTIONS'){//OPTIONS is the method that show in the server when i send files
            req.on('data', function(a){
                console.log(a);//i dont know what are?? after to here!!
            });
        }
    }
});

i have listened of some module like formidable, multipart, and busboy but i can't run its
Thanks
i can solved it with FORMIDABLE :) look the next code:
var server=http.createServer(function(req, res){
    if(req.url==='/upload'){
        var headers = {};
              // IE8 does not allow domains to be specified, just the *
              // headers["Access-Control-Allow-Origin"] = req.headers.origin;
              headers["Access-Control-Allow-Origin"] = "*";
              headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
              headers["Access-Control-Allow-Credentials"] = false;
              headers["Access-Control-Max-Age"] = '86400'; // 24 hours
              headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
        if(req.method==='OPTIONS'){
              res.writeHead(200, headers);
              res.end();
        }else if(req.method==='POST'){
            var form = new formidable.IncomingForm(),
                files = [],
                fields = [];
            form.uploadDir = '/home/sonick7/';//direccion donde va a ser gusradado

            form.on('field', function(field, value) {
                fields.push([field, value]);
              })
              .on('file', function(field, file) {
                console.log(file.name, file.size, file.type, file.path)
                files.push([field, file]);
              })
              .on('end', function() {
                console.log('Upload terminado ');
                res.writeHead(200, headers);
                res.end();
              });
            form.parse(req);//no se que hace eso y para que sirve el modulo util?
        }
    }
});

A: UPDATE AND SOLVED
let server=http.createServer((req, res)=>{
    if(req.url==='/upload'){
        let headers = {}
              // IE8 does not allow domains to be specified, just the *
            headers={
                'Access-Control-Allow-Origin':'*',
                'Access-Control-Allow-Methods':'POST, GET, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Credentials':false,
                'Access-Control-Max-Age':'86400', // 24 hours
                'Access-Control-Allow-Headers':'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
              }
        if(req.method==='OPTIONS'){
              res.writeHead(200, headers)
              res.end()
        }else if(req.method==='POST'){
            let form=new formidable.IncomingForm(),
                files=[],
                fields=[]
            form.uploadDir='/home/sonick7/'

            form.on('field', (field, value)=>{
                fields.push([field, value])
            })
            .on('file', (field, file)=>{
                files.push([field, file])
            })
            .on('end', ()=>{
                console.log(files, fields, 'FT here awefwa', __filename)
                console.log('Upload terminado ')
                res.writeHead(200, headers)
                res.end()
            })
            form.parse(req)
        }
    }
})

A: If you received the request from you client with OPTIONS it probably means the client send CORS request first. I'm not sure which client library are you using, AFAKI AngularJS will send CROS request within each Ajax request.
So what you need to do on server side would handle this OPTIONS request, tell the client this is a valid CROS request, then the client should send the file upload request (POST maybe).
The code below is what I'm using in my project to handle CORS requests in DEV environment with express module, which means it allows request from any origin. In production environment you need to check the origin header and accept those you trust.

    app.configure(function () {
        app.use(function (req, res, next) {
            var oneof = false;
            if (req.headers.origin) {
                res.header('Access-Control-Allow-Origin', '*');
                oneof = true;
            }
            if (req.headers['access-control-request-method']) {
                res.header('Access-Control-Allow-Methods', 'OPTIONS, HEAD, GET, POST, PUT, DELETE');
                oneof = true;
            }
            if (req.headers['access-control-request-headers']) {
                res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Range, Content-Disposition, Authentication');
                oneof = true;
            }
            if (oneof) {
                res.header('Pragma', 'no-cache');
                res.header('Cache-Control', 'no-store, no-cache, must-revalidate');
                res.header('Content-Disposition', 'inline; filename="files.json"');
            }
            if (oneof && req.method == 'OPTIONS') {
                res.send(200);
            }
            else {
                next();
            }
        });
    });


text:
Q: Expression Engine Channels in CodeIgniter? I need to build an application wherein the admin must be able to define forms for data entry. The data to be entered is unknown to me. But the system will need to be able to support all the possible form fields (minus hidden fields, I suppose). So text areas, text fields, radios (with ability to specify what the options are), checkboxes, etc. Also, it needs to be able to support line item entries (similar to EE's Matrix plugin).
Obviously, I don't want to try to build this from the ground up. Are there any libraries I can use in CI to make life easier for me?
If none exist, what are some database design patterns I should consider for such a problem?

A: The best database-design for this is the Entity-Attribute-Value Model. For use with a FORM, essentially your form is the ENTITY, the Attribute will have a type (used for deciding how input will be captured, and data interpreted). Make sure that you index properly.
Remember that you'll only need to data to change the form, don't read from this model everytime you need to show a form. Store a flat file (.json is handy) of the finished form and read that when displaying the form.


text:
Q: Subtracting values based on date SQL I have data that looks like this but with many more index names and index values
dt                     indx_nm      indx_val
2013-08-13 00:00:00.000 ABQI        1571.93
2013-08-12 00:00:00.000 ABQI        1568.55
2013-08-09 00:00:00.000 ABQI        1566.1
2013-08-08 00:00:00.000 ABQI        1573.98
2013-08-07 00:00:00.000 ABQI        1567.42
2013-08-06 00:00:00.000 ABQI        1579.49
2013-08-13 00:00:00.000 ACNACTR     280.3931
2013-08-12 00:00:00.000 ACNACTR     275.1943
2013-08-09 00:00:00.000 ACNACTR     268.8868
2013-08-08 00:00:00.000 ACNACTR     265.7915
2013-08-07 00:00:00.000 ACNACTR     264.8321
2013-08-13 00:00:00.000 ACNITTR     145.3845
2013-08-12 00:00:00.000 ACNITTR     144.1252
2013-08-09 00:00:00.000 ACNITTR     143.2331
2013-08-08 00:00:00.000 ACNITTR     141.4968
2013-08-07 00:00:00.000 ACNITTR     140.6079

How could I write a SQL query in order to subtract the indx_val by the indx_val of the previous date for all dates. I would like to find daily returns essentially. For example for ABQI it would be 1571.93 - 1568.55 as the return for the date 2012-08-13 and so forth. I would like for the result to have a dt column, indx_nm column, and dly_rtn column. Thank you!

A: Try following:
;with cte as (
    select dt, indx_nm, indx_val,
        rn = row_number() over (partition by indx_nm order by dt desc)
    from TableName
)
select c1.dt, c1.indx_nm, c1.indx_val - c2.indx_val as dly_rtn
from cte c1
    left join cte c2 on c2.rn = c1.rn + 1 and c2.indx_nm = c1.indx_nm
order by c1.indx_nm, c1.dt desc

Also, if query is supposed to be run quite frequently, I would recommend having index:
create unique index IX_TableName_1
    on TableName (indx_nm, dt desc) include (indx_val)

A: select a.dt,a.indx_nm ,(b.indx_val-a.indx_val)dly_rtn From table1 a join
Table1 b on a.dt=dateadd(dd,1,b.dt) and
a.indx_nm=b.indx_nm


text:
Q: Explaination of high current zener transistor regulator circuit This is a high current zener TRANSISTOR regulator circuit. I want to know

*

*What does "high current" mean here?

*How is this circuit working as a zener regulator?

*What is the purpose of transistor here?How is it working?

*What is the main component in the circuit diagram?

*What is the purpose of capacitor here?

*Why is the purpose of resistor here?

A: Assuming you don't know what to search for, I'll give you this to read for starters.

What does "high current" mean here?

"high current" means that you can draw the maximum current provided from the input with a proper transistor

How is this circuit working as a zener regulator?

the transistor can provide constant emitter voltage, because it has constant base (reference) voltage. for more, read the next link.

What is the purpose of transistor here? How is it working?

Read this

What is the main component in the circuit diagram?

what do you mean by main? they are all required

What is the purpose of capacitor here?

Usually, the output capacitor is set for high current startup load and for further voltage smoothing

Why is the purpose of resistor here?

Read this and this


text:
Q: PHP PDO bindParam with html content I try to save html content to the database, with ' or " it auto give a slash which is great so I don't have to do mysql_escape_string. However when I load up the string it shows as
test

and if I save it again I got this
test

Does that means when I echo out the string I should strip out the slash?
$html = 'test';
$insertStatement = $pdo->prepare('insert into content (html) values (:html)');
$pdo->bindParam(:html, $html);
$pdo->execute();

A: use
$pdo->bindValue(':html', $html, PDO::PARAM_STR);

instead of
$pdo->bindParam(:html, $html);


text:
Q: Using gcloud to deploy to a custom domain I have a Google App Engine application that runs in a custom URL xxx.org. I can deploy an updated version using the graphical GAE Launcher, only by clicking the "Deploy" button. Still, I'm now trying to learn how to use the gcloud machinery since the Launcher will no longer work after July 30, 2020. I'm stumped as to how to deploy using the gcloud app deploy.
I've tried many things based on hints in the documentation and discussions available on the web, but all I can get is incomprehensible error messages. I'm guessing that I need to modify my app.yaml file. Can someone please give me very explicit instructions on what I need to do? (I should say that I have learned how to run locally using gcloud commands rather than the Launcher, but I can't deploy.)

A: Assuming that the app can be deployed with the custom domain it means that the mapping is already been done and the DNS records have been updated. Nonetheless you can find all the important documentation [here].(https://cloud.google.com/appengine/docs/standard/python/mapping-custom-domains)
A simple summary using gcloud commands to map the custom domain would consist of:

*

*Opening Webmaster Central to verify the ownership of your domain (notice that for App Engine using a CNAME record is the preferred option rather than using TXT records):

gcloud domains verify example.com

*Check if the domain is verified with:

gcloud domains list-user-verified

*Delegate ownership to the relevant users or service accounts used by your application with the Webmaster Central page.

*Create the mapping:
gcloud app domain-mappings create '*.example.com'

*Add the resource records (A, AAAA, CNAME, TXT, etc.) to the DNS configuration of your domain registrar.

After you have tested that you can use your app via the custom domain (in this case www.example.com) there is not much to be done regarding the use of gcloud app deploy. But notice that if you use wildcards to map subdomains with services at any level you would need to use a dispatch.yaml file. Which you need to deploy with the gcloud app deploy dispatch.yaml command.

A: If gcloud command is new for you, maybe you could consider to follow one of the good tutorials published on Google Cloud docs, with a new simple demo app, in a new isolated project, just to validate you're able to deploy using gcloud app deploy command.
First, I suggest you to check if gcloud sdk is correctly installed and configured. For that, you can follow this procedure :

*

*Quickstart for Linux

*Quickstart for Windows

*Quickstart for macOS
One important step is gcloud init which will initialize your configuration and set your default project, with also your credentials. (authentication).
After that procedure, the command gcloud config list should retrieve some environments properties, at least :
[core]
account = your@email
project = your-project-id

Your active configuration is: [your-project-id]

your-project-id is the identifier of your project in GCP. Check console.cloud.google.com for more details and an ergonomic UI view.
This is the basis. No need to go further, if it does not work well at this stage.
Custom domains
About custom domains, no real link with gcloud app deploy. You just have to add mapping, and update DNS records. But it seems this is already done, because your app is already active.
Follow this official procedure (with gcloud commands) to add a mapping.
Check Daniel's answer with a good detail of each step you have to follow.

A: *

*You can't deploy to a 'specific' url. You deploy to a specific project via the command
gcloud app deploy {path to your app.yaml file} --project={PROJECT_NAME}

*Separately, you would have mapped your '.appspot.com' address to your custom domain on the App Engine Settings page


text:
Q: Pact File creation failed due to NoHttpResponseException : 127.0.*.*.*** failed to respond I am unable to create the Pact file.
Facing NoHttpResponseException : 127.0.0.1:56314 failed to respond.
I was able to generate the pact file successfully, but after I did Maven->clean i am facing a series of issues.
Please let me know what can be the cause and how do I resolve it now?
My POM File :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>Customer</groupId>
  <artifactId>Auth_Api_Consumer</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Auth_Api_Consumer</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
        <dependency>
            <groupId>au.com.dius</groupId>
            <artifactId>pact-jvm-consumer-junit_2.11</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
            <version>4.5.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.0</version>
        </dependency>

    </dependencies>
</project>

My Pact Test File :
package Customer.Auth_Api_Consumer;

import java.io.IOException;

import org.apache.http.entity.ContentType;
import org.junit.Rule;
import org.junit.Test;
import Utilities.ApplicationConstants;
import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRuleMk2;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.RequestResponsePact;
import junit.framework.Assert;

public class Authorisation_API_Test {
    @Rule
    public PactProviderRuleMk2 provider = new PactProviderRuleMk2(ApplicationConstants.Provider_EcCustomer, this);

    @Pact(provider = ApplicationConstants.Provider_EcCustomer, consumer = ApplicationConstants.Consumer_EcCart)
    public RequestResponsePact createFragment(PactDslWithProvider builder) {

        return builder.given("Provider State:Verify that the user Vijay exists")
                .uponReceiving("Verify Valid User Login").path("/hue-ec-customer/v1/customers/userlogin/verify")
                .method("POST")
                .body("{\"customerGroupId\": \"3ee05990-5022-11e7-a2ea-e7a96dab751e\", \"login\": \"vijay\", \"password\": \"testing\" }")
                .willRespondWith().status(200)
                .given("Provider State:Verify that the user Vijay exists")
                .uponReceiving("Verify Invalid User Login").path("/hue-ec-customer/v1/customers/userlogin/verify")
                .method("POST")
                .body("{\"customerGroupId\": \"3ee05990-5022-11e7-a2ea-e7a96dab751e\", \"login\": \"vijay\", \"password\": \"123456\" }")
                .willRespondWith().status(401).
                uponReceiving("Create User")
                .path("hue-ec-customer/v1/customers/userlogin/create").method("POST")
                .body("{\"customerGroupId\": \"3ee05990-5022-11e7-a2ea-e7a96dab751e\","
                        + " \"userId\": \"tehuser\", \"loginEmailAddress\":" + " \"teh.sm@mail.com\" "
                        + " \"loginPhoneNumber\": \"8934234\"" + " \"password\": \"defaultpassword\"}")
                .willRespondWith().status(201)
                .toPact();
    }

    @Test
    @PactVerification(ApplicationConstants.Provider_EcCustomer)
    public void runTest() throws IOException {
        System.out.println("Mock Server started at : " + provider.getUrl());
        System.out.println(new Client(provider.getUrl()).postBody("/hue-ec-customer/v1/customers/userlogin/verify",
                        "{\"customerGroupId\": \"3ee05990-5022-11e7-a2ea-e7a96dab751e\","
                                + " \"login\": \"vijay\", \"password\": \"testing\" }",
                        ContentType.APPLICATION_JSON)
                .getStatusLine().getStatusCode());
        Assert.assertEquals(200, new Client(provider.getUrl())
                .postBody("/hue-ec-customer/v1/customers/userlogin/verify",
                        "{\"customerGroupId\": \"3ee05990-5022-11e7-a2ea-e7a96dab751e\","
                                + " \"login\": \"vijay\", \"password\": \"testing\" }",
                        ContentType.APPLICATION_JSON)
                .getStatusLine().getStatusCode());
        Assert.assertEquals(new Client(provider.getUrl())
                .postBody("/hue-ec-customer/v1/customers/userlogin/verify",
                        "{\"customerGroupId\": \"3ee05990-5022-11e7-a2ea-e7a96dab751e\","
                                + " \"login\": \"vijay\", \"password\": \"123456\" }",
                        ContentType.APPLICATION_JSON)
                .getStatusLine().getStatusCode(), 401);

        Assert.assertEquals(
                new Client(provider.getUrl()).postBody("/hue-ec-customer/v1/customers/userlogin/create",
                        "{\"customerGroupId\": \"3ee05990-5022-11e7-a2ea-e7a96dab751e\","
                                + " \"userId\": \"tehuser\", \"loginEmailAddress\":" + " \"teh.sm@mail.com\" "
                                + " \"loginPhoneNumber\": \"8934234\"" + " \"password\": \"defaultpassword\"}",
                        ContentType.APPLICATION_JSON).getStatusLine().getStatusCode(),
                201);

    }
}

A: I had to downgrade the Junit version to 4.9


text:
Q: Simultaneously highlight two associated words on hover (HTML, JS, PHP) I need a little help.
I want to be able to simultaneously highlight two (or more) different but related words on a page when I hover over or click either of them.
This is the kind of thing I mean:
Example of parallel French-English text with highlight
In the example, if I hover over 'croyez' in French then the word English word 'believe' is highlighted and vice versa. I would want to create correspondences for every word in the text.
I came across this code, which I edited a bit. It does the job but is obviously inelegant and would be too laborious to create links for a large file.
JAVASCRIPT:
var spana = document.getElementsByClassName('classA');
var i = 0;
while(i < spana.length){
    spana[i].onmouseover = function change(){
        var i = 0;
        while(i < spana.length){
            spana[i].style.color = 'red';
            i++;
        }
    }

    spana[i].onmouseout = function change(){
        var i = 0;
        while(i < spana.length){
            spana[i].style.color = 'black';
            i++;
        }
    }

    i++;
}

var spanb = document.getElementsByClassName('classB');
var i = 0;
while(i < spanb.length){
    spanb[i].onmouseover = function change(){
        var i = 0;
        while(i < spanb.length){
            spanb[i].style.color = 'red';
            i++;
        }
    }

    spanb[i].onmouseout = function change(){
        var i = 0;
        while(i < spanb.length){
            spanb[i].style.color = 'black';
            i++;
        }
    }

    i++;
}

var spanc = document.getElementsByClassName('classC');
var i = 0;
while(i < spanc.length){
    spanc[i].onmouseover = function change(){
        var i = 0;
        while(i < spanc.length){
            spanc[i].style.color = 'red';
            i++;
        }
    }

    spanc[i].onmouseout = function change(){
        var i = 0;
        while(i < spanc.length){
            spanc[i].style.color = 'black';
            i++;
        }
    }

    i++;
}

CSS:
.classA:hover {
  color: blue;
}

.classB:hover {
  color: blue;
}

.classB:hover {
  color: blue;
}

HTML:

Le
chat
noir
The
black
cat

Thanks for your help,
AB

A: I made three changes in your code: 1. You were using the same variable i for two nested loops. So, I named the second variable as j. 2: I switched the position of the HTML and the JavaScript code as the JavaScript code was referring to the HTML tags which were written after the JavaScript code. 3: I have reduced the JavaScript code, as requested by you.

Le
chat
noir
The
black
cat


text:
Q: How to alter hover effects for image button and embedded text? I have a button with embedded text inside the button and when hovering over the button, I would like it to display the image as well as change the color of the text.
Here is my code:
http://jsfiddle.net/2qCY7/
HTML:

Photo Albums

CSS:
 .album-button {
width: 230px;
height: 230px;
border: 5px solid white;
overflow: hidden;
background: #EC580E;
display:inline-block;
}

.album-text {
font-size: 24px;
color:#FFFFFF;
top: 110px;
height: 80px;
width: 170px;
margin-left:50px;
margin-top:170px;
}

.album-button:hover {
background-image:url('http://www.photobookgirl.com/blog/wp-content/uploads/2010/06/LargeAssembledAlbumMpix.jpg');
background-size:cover;
background-position:-30px;
-webkit-transition: 400ms;
-moz-transition: 400ms;
-o-transition: 400ms;
-ms-transition: 400ms;
transition: 400ms;
}

.album-text:hover {
  color:#000000;
}

Right now, I can only change the color of the text by hovering over the text, specifically, but how do you change both elements by hovering over the image?
BTW, the image used is an example only for this posting.

A: Try changing this:
.album-text:hover {
  color:#000000;
}

to this:
.album-button:hover .album-text{
  color:#000000;
}

Here's demo.

A: You can do this with a lot less HTML and only two classes:
Photo Albums

CSS:
.album-button {
    width: 230px;
    height: 60px;
    border: 5px solid white;
    overflow: hidden;
    background: #EC580E;
    display:inline-block;
    font-size: 24px;
    color:#FFFFFF;
    text-align:center;
    padding-top:170px;
    text-decoration:none;
}

.album-button:hover {
    background-image:url('http://www.photobookgirl.com/blog/wp-content/uploads/2010/06/LargeAssembledAlbumMpix.jpg');
    background-size:cover;
    background-position:-30px;
    -webkit-transition: 400ms;
    -moz-transition: 400ms;
    -o-transition: 400ms;
    -ms-transition: 400ms;
    transition: 400ms;
    color:#000000;
}

Demo


text:
Q: Name a JS Function by clientId I have the following control on my page:
        <abc:OrcaShowHidePanelExtender ID="NumberPlate" ShowHideControlID="RadioButtonListNumberPlate"
            TargetControlID="panelNumberPlate" runat="server"
            ShowHideClientPredicate="NumberPlate_ClientPredicate" />

So this is used to hide/show a panel on screen.  The problem now is I have 3 tabs and I need to show hide the panel on the 3 tabs which are on the same page.
        function NumberPlate_ClientPredicate() {

            return $('#<%= RadioButtonListNumberPlate.ClientID %> input:radio:checked').val() === 'Yes';
}

My question is can I add Client Id to the function so the each panel would call the function idependently as it only calls for the final panel at the minute
so I tried the below but with no success:
 function  $('#<%= NumberPlate_ClientPredicate.ClientID %>')() {
//my return check
}

A: ok so i just used:
<%= this.ClientID %> before the function name and taking ShowHideClientPredicate="NumberPlate_ClientPredicate" off the panel worked for me and then adding the name in code behind


text:
Q: issue with loading a model in Keras in Colab I've saved my model as follows:
model.save('/content/model')
When my model is saved: I got this WARNING:
WARNING:absl:Found untraced functions such as embeddings_layer_call_fn, embeddings_layer_call_and_return_conditional_losses, encoder_layer_call_fn, encoder_layer_call_and_return_conditional_losses, pooler_layer_call_fn while saving (showing 5 of 430). These functions will not be directly callable after loading.
INFO:tensorflow:Reduce to /job:localhost/replica:0/task:0/device:CPU:0 then broadcast to ('/job:localhost/replica:0/task:0/device:CPU:0',).
INFO:tensorflow:Reduce to /job:localhost/replica:0/task:0/device:CPU:0 then broadcast to ('/job:localhost/replica:0/task:0/device:CPU:0',).
INFO:tensorflow:Reduce to /job:localhost/replica:0/task:0/device:CPU:0 then broadcast to ('/job:localhost/replica:0/task:0/device:CPU:0',).
INFO:tensorflow:Reduce to /job:localhost/replica:0/task:0/device:CPU:0 then broadcast to ('/job:localhost/replica:0/task:0/device:CPU:0',).
INFO:tensorflow:Assets written to: /content/model/assets
INFO:tensorflow:Assets written to: /content/model/assets
WARNING:absl:<keras.layers.recurrent.LSTMCell object at 0x7f95000fac10> has the same name 'LSTMCell' as a built-in Keras object. Consider renaming <class 'keras.layers.recurrent.LSTMCell'> to avoid naming conflicts when loading with `tf.keras.models.load_model`. If renaming is not possible, pass the object in the `custom_objects` parameter of the load function.
WARNING:absl:<keras.layers.recurrent.LSTMCell object at 0x7f950018eb50> has the same name 'LSTMCell' as a built-in Keras object. Consider renaming <class 'keras.layers.recurrent.LSTMCell'> to avoid naming conflicts when loading with `tf.keras.models.load_model`. If renaming is not possible, pass the object in the `custom_objects` parameter of the load function.

Now,when I try to load the model I got error message:
model_CSP = keras.models.load_model('/content/model')
I got an error message as follows:
2022-06-22 01:57:09.702116: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0.
Traceback (most recent call last):
  File "Do_predection_Combined_model_.py", line 730, in <module>
    model_CSP = keras.models.load_model('/content/CSP_model')
  File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/nest.py", line 573, in assert_same_structure
    % (str(e), str1, str2))
ValueError: The two structures don't have the same nested structure.

First structure: type=tuple str=(({'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name=None)},), {'training': False})

Second structure: type=tuple str=((TensorSpec(shape=(None, 128), dtype=tf.int32, name='inputs'),), {'token_type_ids': TensorSpec(shape=(None, 128), dtype=tf.int32, name='token_type_ids'), 'training': False, 'attention_mask': TensorSpec(shape=(None, 128), dtype=tf.int32, name='attention_mask')})

More specifically: Substructure "type=dict str={'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name=None)}" is a sequence, while substructure "type=TensorSpec str=TensorSpec(shape=(None, 128), dtype=tf.int32, name='inputs')" is not
Entire first structure:
(({'input_ids': .},), {'training': .})
Entire second structure:
((.,), {'token_type_ids': ., 'training': ., 'attention_mask': .})

'''

I don't know what is wrong? I follow the best practice in saving and loading a model. but I still get this error.
Edit the question:
I think I make a big mistake when I choose Keras API to train my model. After I spend a lot of time designing and training my model. I can't save and reload again. I don't know why the ML experiments recommend this API for beginners. I tried all practice for saving and loading my model and  All of them failed. get tired of this


text:
Q: How do I change the Java version of my "installed project facet" in Eclipse? I just installed Eclipse 3.7 and the Google Plugin for Eclipse because I want to teach myself how to use Google App Engine.
When I create a new web application and run, I got an error that noted that annotations were not allowed in my JRE version (1.4). Hence, I set my JRE to 1.6 and my compiler compliance level to 1.6.
However, I now get this new error.
Description Resource    Path    Location    Type
Java compiler level does not match the version of the installed Java project facet.
Myprojectname       Unknown Faceted Project Problem (Java Version Mismatch)

How do I change "the version of the installed Java project facet"?
There is no item called "Project Facet" to the left of my project's properties menu.

A: If you are using Eclipse IDE for Java EE Developers, you should have the Project Facets property section.
It is possible that your Eclipse 3.7 is the Eclipse IDE for Java Developers. In that case you need to add the ability to have facets by installing the EE goodies...
use the Help -> Install New Software... -> Work with: (choose Indigo) and then turn down "Web, XML, Java EE and OSGi Enterprise Development" and check Eclipse Java EE Developer Tools
Allowing Eclipse to be restarted should now add the Project Facets property section visibility.

A: If you are getting that validation message, you should be able to find "Project Facets" under your project's properties. You should see a screen like this one, where you will be able to change Java facet version:

If you are not seeing this page, then the project you created is likely corrupted somehow. How did you create it? Did you use a wizard provided by Google Plugin for Eclipse? If so, you will need to file a bug report with Google as they are not creating a valid project.
Regardless of the above, you should be able to resolve this problem by right clicking on the problem in the problems view and selecting "quick fix", where you will be guided in aligning your java facet and java compliance settings.

A: In case you have not yet found a solution or somebody else is facing this problem:
I had the same problem with the "Project facet" and not having the "Project Facets" page in the project properties when switching from 1.7 down to 1.6. I was able to fix it with editing the file org.eclipse.wst.common.project.facet.core.xml in the project folder .settings.
In this file I had the following code, in which the 1.7 was replaced by 1.6 and the error went away:
    <?xml version="1.0" encoding="UTF-8"?>
    <faceted-project>
    <installed facet="java" version="1.7"/>
    </faceted-project>

EDIT: I forgot to mention that you have to edit the filters on the "Package Explorer" to show .* resources: Select "View Menu" (the down-facing arrow) -> Filters... -> uncheck ".* resources" -> click "Ok" and you should see the .settings folder.


text:
Q: In git how to merge the Feature branch into Main branch and then Resynchronize We have a feature branch "feature" created from the main branch "main".
We did changes in "feature" and then merged into "main"
In the meantime others also merged their changes in "main". If we want these changes in "main" to also come back to "feature" what is the best way - i.e. we want to resynchronize "feature" with "main"

A: My suggestion:
Check out the main branch again:
git checkout main

Pull the latest changes:
git pull

Check out feature branch again and merge main into feature branch:
git checkout feature
git merge main

You can do this quicker, but this is the - to me - most intuitive way.


text:
Q: ¿Como hacer uso del cortar de palabras truncatewords en django? tengo el siguiente codigo que me recorta las palabras pero, no puedo mostrar el contenido que ya fue recortado
Codigo donde hago uso el truncateword

{{ correspondencia.referencia| truncatewords:"4" }}
leer mas ...

¿como podria mostrar el contenido que esta oculto?


text:
Q: display open ports grouped by process given a netstat output, how can i display the selected open ports grouped by process?
what i got so far:
:~# netstat -tnlp | awk '/25|80|443|465|636|993/ {proc=split($7,pr,"/"); port=split($4,po,":"); print pr[2], po[port]}'

haproxy 636
haproxy 993
haproxy 993
haproxy 465
haproxy 465
exim4 25
apache2 80
exim4 25
apache2 443

desired output (in one line):
apache2 (80 443), exim4 (25), haproxy (465 636 993)

please note:

*

*i have duplicated lines because they listen on different IPs, but i only need one (sort -u is ok)

*if possible, id like to sort by process and then by port

the main goal is to have this single line displayed to the user on ssh logon, using motd (i got this part covered)

A: netstat -tnlp|awk '/25|80|443|465|636|993/ {proc=split($7,pr,"/"); port=split($4,po,":"); print pr[2], po[port]}'|sort|uniq|awk '{a[$1]=a[$1](" "$2" "$3)}END{for (i in a) printf "%s (%s),",i,a[i]}'

try this, Later addition
sort|uniq|awk '{a[$1]=a[$1](" "$2" "$3)}END{for (i in a) printf "%s (%s),",i,a[i]}'


text:
Q: Не выделяется треугольник в меше в Unity using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
public Camera cam;

void Start()
{
    cam = GetComponent<Camera>();
}

void Update()
{
    RaycastHit hit;
    if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
        return;

    MeshCollider meshCollider = hit.collider as MeshCollider;
    if (meshCollider == null || meshCollider.sharedMesh == null)
        return;

    Mesh mesh = meshCollider.sharedMesh;
    Vector3[] vertices = mesh.vertices;
    int[] triangles = mesh.triangles;
    Vector3 p0 = vertices[triangles[hit.triangleIndex * 3 + 0]];
    Vector3 p1 = vertices[triangles[hit.triangleIndex * 3 + 1]];
    Vector3 p2 = vertices[triangles[hit.triangleIndex * 3 + 2]];
    Transform hitTransform = hit.collider.transform;
    p0 = hitTransform.TransformPoint(p0);
    p1 = hitTransform.TransformPoint(p1);
    p2 = hitTransform.TransformPoint(p2);
    Debug.DrawLine(p0, p1);
    Debug.DrawLine(p1, p2);
    Debug.DrawLine(p2, p0);
}
}

Код с официального сайта Unity, с минимальными изменениями под себя. Почему треугольники меша не выделяются, как должно?

A: Все работает.
Во-первых, скрипт должен висеть там, где камера.
Во-вторых, Debug.DrawLine рисует только в Unity Editor
В-третьих, Debug.DrawLine не отображается в Game окне, если там не нажать кнопку Gizmos(в верху справа). По дефолту только в Scene окне.
В-четвертых, рисуются линии белого цвета, и если модель белая, то не увидите.
Варианты:

*

*Debug.DrawLine(p0, p1, Color.red); добавить цвет линиям

*Можно в окне Scene поставить режим Wireframe( в верху слева)


text:
Q: How to include more than one value in IN operator in Big Query I have the following query that is working fine in Big Query:
SELECT
date,
nombre,
i.identifier,
i.hour
FROM
  `table` t, unnest(identifier_s) i
where 2 in unnest(i.hour)

However, I need to include more integers in the search value of the IN operator. Something like this:
...where (2 or 5 or 6) in unnest...

A: Consider below example - hope yo will be able to adopt it to your specific use-case
select date, nombre, i.identifier, i.hour
from `adsmovil-produccion.analisis_alejandro.100_temp_pers` t,
unnest(identifier_s) i
where exists (
  select 1
  from unnest(i.hour) x
  join unnest([2, 5, 6]) x
  using(x)
)


text:
Q: How to update component state that is connected by componentDidUpdate() I am passing selectedOrderState as props from parent and want to populate the state and that works but can't figure how to change the state for use in an input field with an onChange=(handleChange) function attached to manipulate the data. Seems as though componentDidUpdate() and getDerivedStateFromProps() both seem to lock the state so no change can occur. **componentDidMount also does not work because the selectedOrderState prop comes from an onClick event and so the component had already mounted.
Code below - Any thoughts would be helpful!
import React, { Component } from 'react'

export class addOrder extends Component {
state = {
    AoOrder: false,
    AoProgress: false,
    AoChat: false,
    visibility: "visible",
    Order: {},
    DeliveryDate:"",

  };
 //Functs
 componentDidUpdate(prevProps){
    if(this.props.selectedOrderState !== this.state.Order){
    this.setState({
                Order:this.props.selectedOrderState
            });
    }

 }

 handleChange = (e) => {
   this.setState({
    Order:{
        ...this.state.Order,
        [e.target.id]: e.target.value,
      }

  })

};
handleSubmit = () => {

  };

 };
render() {
    const order = this.props.selectedOrderState;
    const { user: { credentials: { handle, imageUrl}}} = this.props;

    return (

    <form className='OrderInfo'onSubmit={this.handleSubmit}>

Order Id:

{this.props.selectedOrderState.OrderId}

Delivery Date:

        <input className="OrderInfoInput" id="DeliveryDate" type="text" onChange=
         {this.handleChange}></input>

    </form>

    )
   }
}

 export default addOrder

A: Declare your state inside the constractor and bind your functions. I'm inviting you to take a look to forms docs with react
constructor(props) {
    super(props);
    this.state = {
        AoOrder: false,
        AoProgress: false,
        AoChat: false,
        visibility: "visible",
        Order: {},
        DeliveryDate:"",
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

A: Probably the most hackerish way to do something but it worked:)
What i did was keep the componentDidUpdate() feeding the state to the child component but from the parent i passed down a function called handleChangeUP() for which i was able to use pass the event of onChange data through to change the original state selectedOrderState. Have a look!
Child
import React, { Component } from 'react'

export class addOrder extends Component {
state = {
   AoOrder: false,
   AoProgress: false,
   AoChat: false,
   visibility: "visible",
   Order: {},

};
//Functs
componentDidUpdate(prevProps){
  if(this.props.selectedOrderState !== this.state.Order){
  this.setState({
            Order:this.props.selectedOrderState
        });
  }

}

handleChange = (e) => {
    this.props.handleChangeUP(e)
  };
render() {
    const order = this.props.selectedOrderState;
    const { user: { credentials: { handle, imageUrl}}} =
this.props;

   return (

   <form className='OrderInfo'onSubmit={this.handleSubmit}>

Order Id:

      {this.props.selectedOrderState.OrderId}

Delivery Date:

    <input className="OrderInfoInput" id="DeliveryDate" type="text"
    value={this.state.Order.DeliveryDate}
    onChange={this.handleChange}></input>

   </form>

    )
  }
}

 export default addOrder

Parent
import React, { Component } from 'react'
import Child from './child'
export class Parent extends Component {
     state = {
    creating: false,//creat order window toggle
    profiling: false,//Profile window toggle
    chatting: false,//Chat window toggle
    searching: false,//Search inside Chat window
    selectedOrder: {}

};
 handleChangeUP = (e) => {
    console.log(e.target.id);
    this.setState({
       // [e.target.id]: e.target.value
        //Order: e.target.value
        selectedOrder:{
            ...this.state.selectedOrder,
            [e.target.id]: e.target.value
        }

    })
}
 render() {
    return (

                    <Child  handleChangeUP={this.handleChangeUP}
                            selectedOrderState={this.state.selectedOrder}/>

    )
  }
}

export default Parent;


text:
Q: HtmlRenderer doesn't render background image from css I use HtmlRenderer to generate jpg images from html markup. However it doesn't apply background image from css:

   Some content here.

Here is the C# code:
String ecardHtml = File.ReadAllText("testWithGoodImage.html");
using (Image img = HtmlRender.RenderToImageGdiPlus(ecardHtml, maxWidth: 440, textRenderingHint: TextRenderingHint.AntiAliasGridFit))
{
    img.Save("result.jpg");
}

Debugging shows that the image is not even requested, so I suspect it's not supported. However  elements do work well.
So the question is how to make it work.
I know that I can render html on image in HtmlRenderer, but I want to have all markup only in html code.

A: HTML renderer supports background Image CSS, if you really want to do it in HTML then something like this will do the job :

Some content here.

or simply add  background-image not just background

   Some content here.


text:
Q: Table view cell with label and textField and equal space between each other i want to create a table view with cells which have a textField.
What drives me crazy is the spacing between label and textField cause i want a equal spacing in all cells.
To better explain take a look at this screenshot.

So im searching for a good way to get the spacing between Second Label and Second textField and set this on the other cells, too.
Is there a way to do it in the storyboard and not by edit the constraint in code?

A: I would suggest that:

*

*use a horizontal stackview to hold the label and textField with some spacing in between, like 10.

*set the label's width constraint to a fixed value.
the details are as follows:

*

*add a horizontal stackview into the cell's contentView

*set the stackview constraints to fill the contentView with some margins:
eg. leading: 20, trailing 20, top 10, bottom 10.

*add a label and a textField into the stackview.

*in the stackview's Attribute inspector, set the spacing to 10.

*set the label's width constraint to 100, or 0.3:1 to the contentView's width

so the label will have a fixed width, fixed spacing between label and textField, and the textField will take all the horizontal space remain.