text:
Q: How To Create An App That Allows For Profile Picture Upload/Change permanently I want to allow users to upload a profile picture in my app so far I have achieved this, but the problem is when I exit the app the profile picture disappears, so I was asking is there a way to store the picture in cache I'm using glide but don't know how to go about it
changing load defaults on my oncreate method but still does not work.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
public static final int REQUEST_IMAGE = 100;

@BindView(R.id.img_profile)
ImageView imgProfile;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(null);

    loadProfileDefault();

}

private void loadProfile(String url) {
    Log.d(TAG, "Image cache path: " + url);

    GlideApp.with(this).load(url)
            .into(imgProfile);
    imgProfile.setColorFilter(ContextCompat.getColor(this, android.R.color.transparent));
}

private void loadProfileDefault() {
    GlideApp.with(this).load(R.drawable.baseline_account_circle_black_48)
            .into(imgProfile);
    imgProfile.setColorFilter(ContextCompat.getColor(this, R.color.profile_default_tint));
}

@OnClick({R.id.img_plus, R.id.img_profile})
void onProfileImageClick() {
    Dexter.withActivity(this)
            .withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {
                        showImagePickerOptions();
                    }

                    if (report.isAnyPermissionPermanentlyDenied()) {
                        showSettingsDialog();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
}

private void showImagePickerOptions() {
    ImagePickerActivity.showImagePickerOptions(this, new ImagePickerActivity.PickerOptionListener() {
        @Override
        public void onTakeCameraSelected() {
            launchCameraIntent();
        }

        @Override
        public void onChooseGallerySelected() {
            launchGalleryIntent();
        }
    });
}

private void launchCameraIntent() {
    Intent intent = new Intent(MainActivity.this, ImagePickerActivity.class);
    intent.putExtra(ImagePickerActivity.INTENT_IMAGE_PICKER_OPTION, ImagePickerActivity.REQUEST_IMAGE_CAPTURE);

    // setting aspect ratio
    intent.putExtra(ImagePickerActivity.INTENT_LOCK_ASPECT_RATIO, true);
    intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
    intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_Y, 1);

    // setting maximum bitmap width and height
    intent.putExtra(ImagePickerActivity.INTENT_SET_BITMAP_MAX_WIDTH_HEIGHT, true);
    intent.putExtra(ImagePickerActivity.INTENT_BITMAP_MAX_WIDTH, 1000);
    intent.putExtra(ImagePickerActivity.INTENT_BITMAP_MAX_HEIGHT, 1000);

    startActivityForResult(intent, REQUEST_IMAGE);
}

private void launchGalleryIntent() {
    Intent intent = new Intent(MainActivity.this, ImagePickerActivity.class);
    intent.putExtra(ImagePickerActivity.INTENT_IMAGE_PICKER_OPTION, ImagePickerActivity.REQUEST_GALLERY_IMAGE);

    // setting aspect ratio
    intent.putExtra(ImagePickerActivity.INTENT_LOCK_ASPECT_RATIO, true);
    intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
    intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_Y, 1);
    startActivityForResult(intent, REQUEST_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getParcelableExtra("path");
            try {

                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

                loadProfile(uri.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

I want the selected image to remain even after closing the app how do I go about it please enter

A: There are 2 ways to achieve your result.

*

*Using Shared Preferences. You can save your variable uri to shared preference and fetch data from it next time. For this, you can check if uri is available in Shared Preference or not.

*Using Room database library.
Below is the code using Shared Preference :
Your onCreate() will be like :
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(null);

    loadImageFromSharedPrefernce();
}

private void loadImageFromSharedPrefernce() {
        SharedPreferences prefs = getSharedPreferences("PREF_NAME", MODE_PRIVATE);
        if (prefs.contains("imageUrl")){
            String imageUrl = prefs.getString("imageUrl", "");
            loadProfile(imageUrl);    //your method

        }
        else {
            loadProfileDefault();      //your method
        }

    }

Your onActivityResult() will be like :
 @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == Activity.RESULT_OK) {
                Uri uri = data.getParcelableExtra("path");
                try {
                    saveImageToSharedPreference(uri);
                    loadImageFromSharedPrefernce();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

private void saveImageToSharedPreference(Uri uri) {
        SharedPreferences.Editor editor = getSharedPreferences("PREF_NAME", MODE_PRIVATE).edit();
        editor.putString("imageUrl", String.valueOf(uri));
        editor.apply();
    }

A: You should save profile pic URI in SharedPreference which is being received in onActivityResult() method. Adding the sample code below, have a look.
private void saveProfilePicLocal(String uri){
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
    Editor editor = pref.edit();
    editor.putString("profile_uri", uri); // Storing string
    editor.commit(); // commit changes
}

Now you have to call above function in onActivityResult() method like below.
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getParcelableExtra("path");
            try {

                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                saveProfilePicLocal(uri.toString())
                loadProfile(uri.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

After that, you should check whether you have any profile locally saved or not if there is any URI exists in SharedPreference read it and load otherwise load default one. Check the sample code below.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(null);

    //Check whether profile pic URI exists in Local SharedPreference
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
if (prefs.contains("profile_uri")){
        String uri = pref.getString("profile_uri", null);
        if(TextUtils.isEmpty(uri.trim())
          loadProfileDefault();
        else
          loadProfile(uri);
    }
}

Happy coding!.


text:
Q: ngx bootstrap alert - detect on close event How can I detect if an alert has been closed using Angular? I am using ngx bootstrap: https://valor-software.com/ngx-bootstrap/#/alerts
Is there a way to detect if onClosed is called?
HTML:
<alert type="success" [dismissible]="dismissible">Detect if I am closed or open</alert>

my-component.component.ts:
alertIsClosed = false;

someFunction(detectAlertIsClosed) {
   alertIsClosed = true;
}

A: Alert component provides an event called onClosed. You need to use it.
From the Documentation

onClosed - This event fires when alert closed, $event is an instance of
  Alert component

Register to it and add the handler
Markup
<alert type="success" [dismissible]="dismissible" (onClosed)="onClosed($event)">
   Detect if I am closed or open
</alert>

Component
public onClosed($event) {

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Putting an Ember partial inside Rails view I have an application in Rails. Recently Ember was installed, and is being used on the part of the views. It works fine there. Now, I need to add some ember functionality to the navbar. At the moment navbar is the part of the Rails layout. I've never dealt with ember before, I've only read some tutorials.
The first solution I've found so far is rewriting and moving the navbar from Rails layout to Embers layout. But that seems like a lot of work, and I'm not sure if it is a good idea.
There is also a way, of puting a div named, for example, "ember-app" and root the Ember there. But that works for a whole ember app, and I want only a part in navbar, and something else in the body. Essentially, what I would like to do, is something like this

     *rails things*

      *more rails things*

Is it possible? There are some ember partials things I've found, but they work inside embers app. Maybe moving the navbar into embers app is normal things?

A: For your use case I recommend you to checkout ember-wormhole.
I think it could allow you to render things from within ember to any div with an given id.
But in general I would strongly recommend you to keep all your view logic in one framework. If you want to use client-side rendering, do all rendering client-side. So if you want to use ember, go  full and use it with ember-cli.
Only thins way you will profit from the ecosystem. You will notice when you try to implement ember-wormhole that it would be one line in an ember-cli app, and a lot of work in any other setup.
Also if you use server side navigation you have to boot your ember app after every transition, which is insane!


text:
Q: Using AmCharts to create bar chart from JSON object retrieved from localStorage I'm trying to create a bar chart using AmCharts using an array that is part of a larger JSON object that is being retrieved from localStorage.  Basically, what I do is retrieve the JSON string, parse it back to JSON object, search take the specific array I'm dealing with ("results"), search that array for the result I'm looking for (via "id"), and then take the array I need ("scores") from that specific result.  Then, I use that array as the input for the AmChart code.
I've tested the AmChart code with another sample array (defined in the code) and it works fine.  However, when I try to retrieve from localStorage, I am unable to get the chart to display.  Any thoughts as to why?  The code in question is here:
//retrieve initial results response from localstorage
var search_results = localStorage.getItem("results_response");

//convert retrieved string back to JSON array
var search_results_object = JSON.parse(search_results); //search_results_objects is now a JSON array

var results = search_results_object.results; //pull out results array

//get venue_id of detail page from local storage
var ven_id = localStorage.getItem("country_id");

//search JSON response for venue ID
var chartDataResults = [];
var searchField = "id";
var searchVal = ven_id;
for (var i=0 ; i < results.length ; i++)
{
if (results[i][searchField] == searchVal) {
    chartDataResults.push(results[i]);
}
}

var chartDataInput = chartDataResults.scores;

//this all works:
var chartData = chartDataInput;

var chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
chart.rotate = true;

var graph = new AmCharts.AmGraph();
graph.valueField = "score";
graph.type = "column";
chart.addGraph(graph);

var categoryAxis = chart.categoryAxis;
categoryAxis.autoGridCount = false;
categoryAxis.gridCount = chartData.length;
categoryAxis.gridPosition = "start";
categoryAxis.labelRotation = 90;
graph.fillAlphas = 0.8;
chart.write('chartdiv');

Most recently, the dev console in Chrome has told me "Uncaught TypeError: Cannot read property 'length' of undefined".  The chart does not render, either.  Thoughts?  I appreciate any and all help.

A: Your code fails because of this:
var chartDataInput = chartDataResults.scores;

chartDataResults is an array by your declaration, not an object. According to the amDocs you could pass chartDataResults directly, given that it is in the correct format, eg [{title:"sample 1",value:130},{title:"sample 2",value:26}];.
If so - try to replace:
var chartDataInput = chartDataResults.scores;

//this all works:
var chartData = chartDataInput;

with
var chartData = chartDataResults;

If you chartDataResults array is not in the correct format, you need to construct it in that loop. Something like:
for (var i=0 ; i < results.length ; i++)  {
  if (results[i][searchField] == searchVal) {
    var aResult = new Object();
    aResult.title = results[i].title; // or results[i]['title']
    aResult.value = parseInt(results[i].value); // or results[i]['value']
    chartDataResults.push(aResult);
  }
}

I am speculating that in your json objects you have .title and .value. If not - replace them accordingly. If you're not sure :) what properties they have - print them to the console and inspect them.


text:
Q: What is the meaning of an entropy current? Imagine some kind of thermoionic device, where electrons jump off a metal in vacuum due to a fixed temperature bath and in the presence of a bias voltage.
In a steady state regime (and quasi-equlibrium regime), there will be a net particle current. Thanks to the first law of thermodynamics,
$$\Delta U=T\Delta S+\mu\Delta N$$,
we can define the energy and entropy currents,
$$\dot{U}=T\dot{S}+\mu J$$,
where $U$ is the energy, $S$ is the entropy, $T$ the temperature, $N$ the number of particles, $\mu $ the chemical potential of the metal, $\dot{U}$ the energy current, $\dot{S}$ the entropy current and $J$ the particle current.
In a microscopic picture, $J\propto \int f(E)\tau(E) \mathrm{d}E$ and $\dot U\propto \int E f(E)\tau(E) \mathrm{d}E$, where $\tau(E)$ takes into account the probability of escaping the metal and $f$ is the Fermi-Dirac distribution.
By construction, $\dot{U}$ will be positive (as long as the metal is not receiving electrons). But $T\dot{S}=\dot{U}-\mu J$ can be negative or positive.
What is the physical interpretation of $T\dot{S}$? Why it can take positive and negative values?

A:
we can define the energy and entropy currents

What you defined are the rates of change ($\dot U$, $\dot S$). In the case of energy, which is conserved, the rate of change must correspond to the net flow. But entropy is different; it is not conserved.
Your example can be generalized to
$$T\dot S=\dot U-\sum_i F_i\frac{\partial x_i}{\partial t},$$
where $\dot S$ is the rate of system entropy increase and $F_j$ and $x_j$ are respectively generalized forces and displacements; examples include

*

*negative pressure and volume

*surface tension and surface area

*electric field and polarization

*voltage and charge

*magnetic field and magnetic moment

*force and distance

*stress and volumetric strain

*chemical potential and amount of matter

Along with energy, the generalized displacements above are conserved except for the electrical polarization and magnetic moment; thus, we ignore those forms of work for simplicity. By the divergence theorem expressed as $\frac{dA}{dt}=-\nabla\cdot\boldsymbol{J_A}+\dot\sigma =-\nabla\cdot\boldsymbol{J_A}$, where $\boldsymbol{J_A}$ is the flux of A and $\dot\sigma$ represents generation (absent for a conserved quantity), we obtain the continuity relation
$$T\dot S=-\nabla\cdot\boldsymbol{J_U}+\sum_iF_i\nabla\cdot\boldsymbol{J_i}.$$
From the chain rule, $A\nabla\cdot\boldsymbol{B}=-\boldsymbol{B}\nabla\cdot A+\nabla\cdot (A\boldsymbol{B})$; thus, letting $A=\frac{1}{T}$,
\begin{align}T\dot S&=T\left(\boldsymbol{J_U}\cdot\nabla\frac{1}{T}-\nabla\cdot\frac{\boldsymbol{J_U}}{T}-\sum_i\boldsymbol{J_i}\cdot\frac{F_i}{T}+\nabla\cdot\frac{\sum_iF_i\boldsymbol{J_i}}{T}\right)\\&=T\left[\underbrace{\boldsymbol{J_U}\cdot\nabla\frac{1}{T}-\sum_i\boldsymbol{J_i}\cdot\frac{F_i}{T}}_{\substack{\text{this looks like}\\\text{a generation term}}}\underbrace{-\nabla\cdot\left(\frac{\boldsymbol{J_U}-\sum_iF_i\boldsymbol{J_i}}{T}\right)}_{\substack{\text{this looks like}\\\text{a flux term}}}\right].\end{align}
Looking again at the divergence theorem, we infer a relation
$$T\dot S=T(\dot \sigma-\nabla\cdot \boldsymbol{J_S}),$$
where we identify
$$\dot\sigma =\boldsymbol{J_U}\cdot\nabla\frac{1}{T}-\sum_i\boldsymbol{J_i}\cdot\nabla\frac{F_i}{T}$$
as the entropy generation rate and
$$\boldsymbol{J_S}=\frac{\boldsymbol{J_U}-\sum_iF_i\boldsymbol{J_i}}{T}$$
as the conserved entropy flux or current.
As derived here, for example, $\boldsymbol{J_U}=\boldsymbol{J_Q}+\boldsymbol{J_W}+\boldsymbol{J_H}$, where $\boldsymbol{J_Q}$ is the heat flux, $\boldsymbol{J_W}$ is the work flux (excluding flow work) and $\boldsymbol{J_H}$ is the enthalpy flux related to mass transfer (recall that the molar enthalpy $h=\mu+Ts$, where $\mu$ is the chemical potential). The subtraction of $\sum_iF_i\boldsymbol{J_i}$ from $\boldsymbol{J_U}$ above effectively removes $\boldsymbol{J_W}$ and $\sum_i\mu_i\boldsymbol{J_i}$ for mass flow $\boldsymbol{J_i}$. This allows us ultimately to write the above relation as
$$\boldsymbol{J_S}=\frac{\boldsymbol{J_Q}+T\sum_is_i\boldsymbol{J_i}}{T},$$
where $s_i$ is the entropy, if any, carried by generalized displacement $i$ (e.g., the flow of charge carriers).
In addition, applying the chain rule to the entropy generation rate gives
$$\dot\sigma=\frac{1}{T^2}\left(-\boldsymbol{J_U}\cdot\nabla T+\sum_iF_i\boldsymbol{J_i}\cdot \nabla T-T\sum_i\boldsymbol{J_i}\cdot\nabla F_i\right);$$ thus, $$T\dot\sigma=\underbrace{-\boldsymbol{J_S}\cdot\nabla T}_{\substack{\text{contributes to entropy}\\\text{generation from flow down}\\\text{a temperature gradient}}}+\underbrace{\sum_i-\boldsymbol{J_i}\cdot\nabla F_i.}_{\substack{\text{contributes to entropy}\\\text{generation from flow down}\\\text{all other gradients}}}$$
What this tells us is that entropy can be transferred in and out of a system through heating and through the entropy carried by matter, for example. This is $\boldsymbol{J_S}$.
In addition, entropy is generated whenever flow of a generalized displacement (all $\boldsymbol{J_i}$ plus the entropy flow $\boldsymbol{J_S}$ itself) is driven by a gradient in any internal property (all $\boldsymbol{\nabla F_i}$ plus temperature $\boldsymbol{\nabla T}$). The direction of spontaneous flow is opposite the direction of the gradient in the intensive property; in this way, Nature smooths out disturbances. This is $\boldsymbol{\dot\sigma}$.
Depending on how much entropy you transfer in and out and how much entropy you generate, $\boldsymbol{\dot S}$ can be positive or negative.


text:
Q: Can't Add Large Icons to Asset Catalog I am trying to add images for my app icon to my project using asset catalogs. My version of OSX is 10.9.3 and version of Xcode is 5.1.1. The Apple documentation states that you can drag and drop your images into the set boxes in the Asset Catalogs folder. However, many of my drag and drop boxes are cut off and I cannot horizontally scroll:

Am I doing something wrong or is it a bug? I couldn't find another way to add files to a specified size in an AppIcon set. Is there another way to do it?
Thanks!

A: You can simply fix this problem by hiding the side bar from the top of the screen. This will reveal all the image drops. Even so, just dropping the images in should auto-sort them into the right place


text:
Q: How to open real popup window in Flex I need to open popup window in my flex / air application that will be displayed like normal application window. All I could manage is to open a window which is displayed inside my main flex window.
Is it something like that possible, and is there some workarounds if not?

A: You'll have to use a NativeWindow for that. More info the API docs: http://livedocs.adobe.com/flex/3/langref/flash/display/NativeWindow.html
import flash.display.NativeWindowInitOptions;
import flash.display.NativeWindowSystemChrome;
import flash.display.NativeWindowType;
import flash.display.NativeWindow;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.geom.Rectangle;

var windowOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
windowOptions.systemChrome = NativeWindowSystemChrome.STANDARD;
windowOptions.type = NativeWindowType.NORMAL;

var newWindow:NativeWindow = new NativeWindow(windowOptions);
newWindow.stage.scaleMode = StageScaleMode.NO_SCALE;
newWindow.stage.align = StageAlign.TOP_LEFT;
newWindow.bounds = new Rectangle(100, 100, 800, 800);

newWindow.activate();

A: For a Flex application, you'll want to use mx.core.Window. For a non-Flex ActionScript application, you should use flash.display.NativeWindow.

A: There is a good example here for flex 3.


text:
Q: Windows 7 Media Center alternatives with Blu Ray Support I can't believe Win7 doesn't have Blu-Ray support yet. Having plugins open in the background breaks the 10Ft experience. PowerDVD (came with blu-ray player) is unusable from the couch.
Are there any comprehensive packages (paid or otherwise) that will give me TiVo usability, Blu-Ray support, Hulu and Netflix integration and music library functionality?
Should I scrap the HTPC concept and buy an AppleTV instead?

A: don't know about TiVo or Hulu, but i'm using PowerDVD 9, which enables Bluray-playback in Windows Media Center.
Cinema Playback Mode

When using Microsoft Windows Media
  Center, Cinema enables Blu-ray
  playback. Cinema also supports remote
  control colored keys during Blu-ray
  movies playback.

Obviously, Microsoft is outsourcing Blu-ray support in Windows 7 to Cyberlink.

A: I don't own it nor know much about it, but I often hear about the popcornhour device in the HD/Blu-ray community (http://www.popcornhour.com). Take a look perhaps.
As for me, I still stick around MediaPlayerClassic Home Cinema (http://mpc-hc.sourceforge.net/) with AnyDVD HD for decrypting the discs. The solution is far from elegant, but provide fine-grained control that I have yet to find elsewhere.


text:
Q: Tomcat servlet engine is not running, but pid file exists. What does this message mean? Do I need to recover Tomcat if I get it? I am making a shell script to restart tomcat after crash.
I wonder I need to handle this message in my script "Tomcat servlet engine is not running, but pid file exists."
What does this message means?
Do I need to take it into account as an error message that oblige me to restart Tomcat?
My script is as follow:
#!/bin/bash
SERVICE=/etc/init.d/tomcat7
STOPPED_MESSAGE=" * Tomcat servlet container is not running."
PID_FILE_MESSAGE=" * Tomcat servlet engine is not running, but pid file exists."

if [ "`$SERVICE status`" == "$STOPPED_MESSAGE" ];
then
{
    $SERVICE start
}
else
    if [ "`$SERVICE status`" == "$PID_FILE_MESSAGE" ];
    then
    {
        $SERVICE restart
    }
    fi
fi

A: Here's the definition of PID. A PID file is a file that contains a process identifier. If Tomcat's startup scripts are run with CATALINA_PID environment variable set properly, then the PID of the Tomcat process will be recorded to a file upon startup. If the file exists when you try to start Tomcat, the scripts will refuse to run because it does not want to clobber a (possibly valid) PID file.
If you are sure that Tomcat is not running, simply delete the file (it should be available through the CATALINA_PID environment variable) and try again.
I share @jordanm's comment about using exit codes instead of checking for specific (text) output: the latest version of Tomcat does not even use the messages that you have shown above, so it's very fragile.
If you want a self-re-starting service, considering looking at jsvc, which actually ships with Tomcat binaries in source form.

A: I had a same problem when i restart the tomcat. Also i found "java.net.BindException: Cannot assign requested address" in cataline.out log file.
Soultion: Kill all the java pid by using killall -9 java the restart the tomcat again.
For me problem has been resolved


text:
Q: Alternate to Like in jsonb postgres I have a Postgres table with more than 25M records, there I have a jsonb column called info.
sample json format:
{
"username1":{"name":"somename","age":22,"gender":"male"},
"fathername":{"name":"somename","age":22,"gender":"male"}
}

I am going to find number of records that match the 'user%' key value.
Here is my query
select count(1) from tablename where info::text like '%user%';

this query is working and I am getting result for it, but it is taking long time to execute this query in 25M records.
Is there any way that I can optimize this query or any alternate method to achieve it? Please help.
Thanks in advance!

A: As @klin as pointed out, this query will only give you 0:
select count(1) from tablename where info::text like 'user%';

Why because this is just a simple pattern match and you don't have any strings in your info column that begins with 'user'. You might have better luck with '%user%' but that's going to be awfully slow (unless you have trigram extension enabled and an index created)
If you want to count exactly how many users have the username1 set it's a really simple query.
select count(1) from tablename where info ? 'username1'

This works on 9.5. If you have a finite number of 'user%' keywords, you can try something like this:
select count(1) from tablename where info ?| array['username1','username2',..]

If you are uncertain about the nature of the keys then you can do
SELECT COUNT(1) FROM (
    SELECT * FROM JSONB_EACH(info) FROM tablename
) AS a WHERE a.key like '%user%'

A: Well, it looks ugly, but I think this could work:
select count(1) from (
    -- unnest an array of keys
    select id, unnest(array_agg(d.k)) as k from (
        -- extract info keys
        select id, jsonb_object_keys(info) as k from tablename
    ) as d
    where k like '%user%'
    group by id
) as q
group by id;


text:
Q: JQuery draggable element not moving I have a simple draggable example, which is not working. Draggable element (div with green border) is not moving when I try to move it with the mouse.
My code for dragging:
  $("#divDraggable").draggable({
    revert: 'invalid',
    helper: 'clone'

  });

I just want to copy element into another (larger) element. If it's not dropped, return it to it's initial position. Why it's not working?

$(function(){

  $("#divDraggable").draggable({
    revert: 'invalid',
    helper: 'clone'

  });

  $("#divDroppable").droppable({
    accept: '.draggable',
    drop: function (event, ui) {
        debugger;
        var droppable = $(this);
        var draggable = ui.draggable;
        draggable.clone().appendTo(droppable);
    }

  });

})
#divDroppable{
  border:1px solid black;
  width: 300px;
  height: 300px;
}

#divDraggable{
  margin-top: 50px;
  width: 100px;
  height: 100px;
  border: 2px solid green;
}

<link href="https://test73.webo.hosting/Styles/jquery-ui-1.10.0.custom.css" rel="stylesheet"/>

A: Here you go with a solution https://jsfiddle.net/4hzcq0q5/

$(function(){

  $("#divDraggable").draggable({
    revert: 'invalid',
    helper: 'clone',
  });

  $("#divDroppable").droppable({
    accept: '.draggable',
    drop: function (event, ui) {
        var droppable = $(this);
        var draggable = ui.draggable;
        draggable.clone().appendTo(droppable);
    }
  });
})
#divDroppable{
  border:1px solid black;
  width: 300px;
  height: 300px;
}

#divDraggable{
  margin-top: 50px;
  width: 100px;
  height: 100px;
  border: 2px solid green;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

Issue was with you class class="draggable" added to dropped div instead of draggable div.

A: Your problem with helper attribute in draggable. Please check this fiddle, i remove helper property and its work https://jsfiddle.net/x6hdan8L/1/

A: Syntax was wrong. It should be like this:
$("#divDraggable").draggable({
    revert: true,
    helper: 'clone'

  });

Working example:
draggable


text:
Q: Best choice for mail server under ubuntu server Not so long ago I did setup my development server on vmware. Currently I'm using ubuntu server. Yesterday when I was trying somethings with php mail() function it didn't work. I got curious. Well for one I went to google. Okey. So I need sendmail program. Then I edited php5/apache2/php.ini file. Set path to sendmail -t -i and restarted apache2 server. Great mail is sent, but nothing was received.
So a coworker said, that I also need a mail server. So now there's a question, what would be the best choice if there is such.
Read this article Setup ubuntu server to send mail(). Can't say much. Would like to hear other opinions if there are any.
Thanks a lot.

A: I won't call it the best, but I like postfix a lot... It is powerful and easy to configure, which is important for security purposes.  When it installs, you will get an alias to it as sendmail, so scripts that work with sendmail should be fine under a postfix install.
UBUNTU / DEBIAN TUTORIAL for outbound mail with local delivery:
(as root)
aptitude install postfix
# OR, if already installed....
dpkg-reconfigure postfix
# Select "Internet host".
# Accept defaults
echo "a test from me" | mailx -s "postfix test" you@someemail.local

If your ISP blocks port 25 outbound, configure relayhost = <hostname_of_your_isp_mailserver> in /etc/postfix/main.cf and restart postfix.
Older linux admins tend to use mail, but Ubuntu has renamed mail as mailx

A: Not really clear from the question whether or not you already have a mail service set up somewhere to receive these emails. I'm going to assume that your organization has one or that you're sending it to Gmail/Yahoo/Whatever.
We've had very good results with the default Ubuntu exim4 on servers that can simply forward their email elsewhere for safekeeping. Our customer-facing LTSP servers only use it for crontab'd script output and Logwatch.
We use Exim on those forwarding boxes because that's what Ubuntu installs by default with mailutils. Running dpkg-reconfigure exim4-config and it's a mere 30 seconds of configuration work to point it at the main server.
easy peasy.

A: You want to be able to receive email? Then you need something that will accept email into a mail box. Although this is for Debian, there isn't much difference between it and Ubuntu. It includes a full setup of Postfix and Courier.
Setup Mail server
I find that HowToForge has many great setup guides for the Linux community.
There are other equally good SMTP and MAilStores, but this is the better supported setup from the Ubuntu community. Other SMTP servers include Exim and Sendmail. Another MailStore includes Dovecot.

A: Not saying that it is the "best" but I like qmail a lot, espeacilly for its security and modularity. qmail is built in the Unix way: one small task is handled by a simple process and ali tais processes interact with each other.
Hope this helps!

A: I've asked for more details, but I'm going to bite here:
For most Web applications/sites I setup that need to send mail (and again, this isn't necessarily the best way to scale, but my stuff is usually low-load with < 100 concurrent users), I use Postfix on the same box as Apache/PHP.
Because I'm usually dealing with a domain that already has MX records and an authoritative mail server somewhere else, I'll either relay it through that authoritative mail server as a smarthost (usually the easiest method) or set it to send outbound only directly and make sure that the SPF records are updated accordingly and that the public IP address I'm (usually) NAT'ing out as has reverse DNS setup.
If you do end up sending it directly, make sure your banner that's displayed from Postfix has mail.yourdomain.com and that you have an A record setup that resolves to the public IP that Postfix is listening on.  This shouldn't be necessary, but there's alot of odd anti-spam vigilance out there.  I'd also setup postmaster@yourdomain.com and abuse@yourdomain.com as well; these can be aliases/forwarders to your real email address, but again, I've seen some mail servers try to reconnect and issue a rcpt to from the address that mail is sent as in the header and if it doesn't exist, you'll be black/graylisted.
If you don't have an authoritative mail server, you could setup Postfix and Dovecot for IMAP support, but you'll likely have an easier/more reliable experience setting up Google Apps for your Domain for free and relaying mail off of their servers.  As long as you don't plan on sending massive amounts of mail, this works really well and gives you a nice interface for adding email addresses.
Note: I'm finding that increasingly receiving mail servers/anti-spam configurations are setup to drop SMTP traffic originating from Amazon's EC2 block and other commodity hosting providers (HostGator, Dreamhost, etc.), so again, setting up a secure relay to your authoritative mail server is likely the best option.


text: Q: Can't connect on RDP on Google Cloud on EU servers (US works) I have problem with connecting to server on Google Cloud, I'm using free trial and while I create server in any of three European zones I can't connect to it through RDP, in case when I create servers in US-central location everything is fine. I tried it on different computers and on every each one of them the same problem has occured. In firewall port for RDP is unlocked, I'm connecting from Poland.


text:
Q: How to control json data nodejs im making a bot to get the price of the peso argentino. Im using a Api but im having some problems to get only the sell price.
if (command == "peso"){
    request('https://www.dolarsi.com/api/api.php?type=valoresprincipales', (err, res, body) => {

        const data = JSON.parse(body);
        message.channel.send(body);
});

Im getting this output:

And I need to get only this price:

A: If you only want to get that particular sell price, you must be particular on what property you want to compare to get that sort of data.
Example:
const data = JSON.parse(body);

const item = data
   .find(({ casa: { venta } }) => venta === "161,000")
   .casa
   .venta;

Attach is the Stackblitz Demo for your reference with the mock data in reference to your screenshot above


text:
Q: Storing a 30KB BLOB in SQL Server 2005 My data is 30KB on disk (Serialized object) was size should the binary field in t-sql be?
Is the brackets bit bytes ?
... so is binary(30000) .... 30KB?
Thanks

A: You need to use the varbinary(max) data type; the maximum allowed size for binary is 8,000 bytes.  Per the MSDN page on binary and varbinary:

varbinary [ ( n | max) ]
Variable-length binary data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of the data entered + 2 bytes. The data that is entered can be 0 bytes in length.

A: The number after binary() is the number of bytes, see MSDN:

binary [ ( n ) ]
Fixed-length binary data of n bytes. n
  must be a value from 1 through 8,000.
  Storage size is n+4 bytes.

Whether 30kb is 30000 or 30720 bytes depends on which binary prefix system your file system is using.


text:
Q: bash script to call two functions, consecutively, each with its own argument There are a lot of similar questions, but I cannot find an example of what I am looking for, nor in the Bash scripting guides (I'm sure it's there but its a big book...)
What I want is this:
I have a file I call by:   ./runMe.sh, whose contents are this:
callMaxima() {
maxima -b "$1"
}
callSINGULAR() {
/opt/local/bin/Singular -b "$2"
}
callMaxima $1;
callSINGULAR $2;

I want Maxima to do some stuff, dictated by the first argument passed in the terminal, e.g. ./runMe MaximaFile SINGULARFile, and which will generate a text file, Maxima.OUT.
I then want, after the file above (Maxima.OUT) is written, to start SINGULAR in batch mode (also), with the file passed to it by the second argument, e.g. SINGULARFile. It will read in data from Maxima.OUT and do some stuff.
The problem:
The sccript runs Maxima fine, writes the file, exits and enters SINGULAR. But apparently the file argument, e.g. SINGULARFile, is not being opened. I can easily start SINGULAR from the terminal and automatically execute/open the file with
/opt/local/bin/SINGULAR -b SINGULARFile

but it isn't working in the runMe.sh. Since the programs seem very very similar, I'm assuming my runMe.sh isn't working right...

A: This function should looks like:
callSINGULAR() {
/opt/local/bin/Singular -b "$1"
}

Because the parameter is first, provided to function


text:
Q: Verifying Green's Theorem If we have the line integral of F=$(x^2-2xy)dx+(y^2-x^3y)dy$ over a square with vertices at $(0,0)$ , $(2,0) ,(2,2) ,(0,2)$ I get the answer $24$ when doing the double integral in Green's theorem , but my book gives the answer $-8$ . Am I correct??

A: Using Green's Theorem we get ,


text:
Q: Criar instalador no Visual Studio 2019 Criei um instalador para a minha solução no Visual Studio 2019 usando o Setup Wizard (componente do próprio VS), e configurei ele de forma que ficasse ao meu gosto, mudei a aplicação de debug para release e aparentemente está tudo certo.
Porém quando eu executo o instalador, ele me diz que devo instalar o .NET Framework, de fato é um requisito para a instalação, mas eu já estou com ele instalado e mesmo assim essa janela continua aparecendo e não prossegue com a
instalação.

Se eu colocar "Não" ele interrompe a instalação, e mesmo desinstalando o .NET Framework e fazendo a instalação dele por ai, quando reaberto ele retorna nessa mesma tela. Acredito que há N formas de fazer isso mas gostaria de criar o instalador pelo próprio VS, pensei em retirar o .NET Framework como requisito da instalação, mas não é possível.


text:
Q: Stylesheet that replaces some elements but keeps remaining XML document completely intact I am using the following XSLT stylesheet for removing all Connectors from server.xml, i.e. a Tomcat configuration file, and replacing them with a new one. It works well enough (with xsltproc), except that the transformations won't preserve comments, etc. (These elements should be redundant, as far as server.xml is concerned.)
How can I modify the stylesheet so that it keeps all nodes (including comments, texts, processing instructions, etc.) faithfully intact, except for the intended changes to Connectors?
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="/ | * | @*">
    <xsl:copy>
      <xsl:apply-templates select="* | @*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="Service">
    <xsl:copy>
      <xsl:apply-templates select="*[not(self::Connector)] | @*"/>
      <Connector/>  <!-- actual new attributes removed for brevity -->
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

A:
How can I modify the stylesheet so that it keeps all nodes (including
  comments, texts, processing instructions, etc.) faithfully intact,
  except for the intended changes

Replace this part:
  <xsl:template match="/ | * | @*">
    <xsl:copy>
      <xsl:apply-templates select="* | @*"/>
    </xsl:copy>
  </xsl:template>

with the standard identity transform template:
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>


text:
Q: Why is my exception about pagecontext which I do not have? I get this error message
pageContext cannot be resolved

but I have no variable pagecontext.
This is the code (I know there are other problems here that are beyond the scope of this question):
<%@page import="se.prv.pandora.arendeprocess.util.PandoraPersonHandler"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<%@ page import="org.apache.log4j.Logger" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.Map" %>
<%@ page import="se.prv.pandora.arendeprocess.general.ArendeProcessLocator"%>
<%@ page import="se.prv.pandora.arendeprocess.page.ArendeProcessPageController" %>
<%@ page import="se.prv.pandora.arendeprocess.page.GrunduppgifterPageController" %>
<%@ page import="se.prv.pandora.arendeprocess.obj.Navigation" %>
<%@ page import="se.prv.pandora.arendeprocess.obj.AnsokanInfo" %>
<%@ page import="se.prv.pandora.arendeprocess.obj.Oversikt" %>
<%@ page import="se.prv.pandora.arendeprocess.obj.PersonInfo" %>
<%@ page import="se.prv.pandora.arendeprocess.obj.PersonInfoIndex" %>
<%@ page import="se.prv.pandora.arendeprocess.obj.Land" %>
<%@ page import="se.prv.pandora.arendeprocess.obj.ArendesokInfo" %>

<%@ page import="se.prv.pandora.arendeprocess.entity.Prioritet" %>
<%@ page import="se.prv.pandora.arendeprocess.util.PandoraFieldConstants" %>
<%@ page import="se.prv.pandora.arendeprocess.entity.Deposition" %>
<%@ page import="se.prv.pandora.arendeprocess.util.ArendeComparatorManager" %>
<%@ page import="se.prv.pandora.arendeprocess.obj.ArendeSearchAdmin" %>
<%@ page import="se.prv.framework.forms.IFormData" %>
<%@ page import="se.prv.framework.general.Action" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.text.DateFormat" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@page import="se.prv.pandora.arendeprocess.obj.ArendeProcessSessionData"%>
<%@ page import="se.prv.pandora.arendeprocess.util.PandoraConstants" %>
<%@page import="se.prv.pandora.arendeprocess.entity.PRVNummerPerson"%>

<%@ page import="se.prv.pandora.arendeprocess.entity.Region" %>
<%@ page import="se.prv.pandora.arendeprocess.obj.Land" %>
<%@ page import="se.prv.pandora.arendeprocess.entity.LandKod" %>
<%@ page import="se.prv.pandora.arendeprocess.util.MessageHandler" %>
<%@page import="se.prv.pandora.arendeprocess.general.PandoraManager"%>

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css">
    <link href="css_js/styles.css" rel="stylesheet" type="text/css">
    <link href="css_js/positions.css" rel="stylesheet" type="text/css">
    <link href="css_js/dialog_box.css" rel="stylesheet" type="text/css">
    <link href="css_js/floats.css" rel="stylesheet" type="text/css">

    <title>Ingivningsdag - NAT. - Pandora </title>

<%
    final Logger logger = Logger.getLogger("arendeprocess_grunduppgifter.jsp");
    ArendeProcessPageController apc = new ArendeProcessPageController(request);
    GrunduppgifterPageController pc = new GrunduppgifterPageController(request);
    ArendeProcessSessionData sessionData =(ArendeProcessSessionData) PandoraManager.getSessionData(request);

    String arendeTyp = apc.getArendeTyp();
    boolean showSearch = false;
    boolean showSearchD = false;
    boolean showSearchP = false;
    boolean showSearchI = false;
    boolean showSearchR = false;
    boolean showSearch2 = false;
    boolean showSearchF = false;
    boolean showSearchA = false;
    boolean showSearchU = false;
    boolean showSearchO = false;
    boolean showSearchEPa = false;
    boolean showSearchEPn = false;
    AnsokanInfo ansokanInfo = apc.getAnsokanInfo();
    PersonInfo editPerson = new PersonInfo();
    PersonInfo editOmbud = new PersonInfo();
    String chosenPersonTyp = "";
    String chosenPersonOrdNr = "";
    if(ansokanInfo != null && ansokanInfo.hasEditPersonInfo()) {
        editPerson = ansokanInfo.getEditPersonInfo();
        Action latestAction = sessionData.getLatestAction();
        chosenPersonTyp = latestAction.getActionModifier();
        //+1 eftersom listindex börjar på 0
        chosenPersonOrdNr = latestAction.getCurrIndexAsInt()+1+"";
    } else {
        editPerson.setFornamn(apc.getNyregPerson().getFornamn());
        editPerson.setEfternamn(apc.getNyregPerson().getEfternamn());
        editPerson.setForetag(apc.getNyregPerson().getForetag());
        //editPerson.setOrgnr(apc.getNyregPerson().getOrgnr());
        editPerson.setLandKod(apc.getNyregPerson().getLandKod());
        editPerson.setReferens(apc.getNyregPerson().getReferens());
    }
    if(apc.getLatestAction().equals("Namnsokning") && apc.getLatestActionCommand().equals("search")) {
        showSearch = true;
    }
    if(apc.getLatestAction().equals("Arendesokning") && apc.getLatestActionCommand().equals("search")) {
        showSearchF = true;
    }
    int nbOfRelatedPersons = 0;
    String relatedPersons = "";
    if(editPerson.getPersonTyp().containsKey(PandoraConstants.PERSONTYP_OMBUD)) {
        editOmbud = editPerson;

        PersonInfoIndex pii = editOmbud.getPersonTyp().get(PandoraConstants.PERSONTYP_OMBUD);
        if(pii!=null) {
            nbOfRelatedPersons = pii.getRelatedPersons().size();
            //Ska bara skrivas ut om inte ombudet gäller för alla sökande
            if(ansokanInfo.getSokandeList().size()> nbOfRelatedPersons)
                relatedPersons = pii.getRelatedPersonsAsString();
        }

        editPerson = new PersonInfo();
    }

    int vectr = 0; // får bara användas i errormessages.jspf
    IFormData ifData = sessionData.getFormData();

%>

Sök person/
företag:

<input type="button" value="Sök" onClick="document.getElementById('popupF').style.display='';">

<div class="popup" id="popupF"
<% if(!showSearchF) { %>
style="display: none;"
<% } %>
>
<%@ include file="WEB-INF/jspf/fullfoljd_fran_sok.jspf" %>

<div class="popup" id="popupSokNamn2"
<% if(!showSearch2) { %>
style="display: none;"
<% } %>
>
<%@ include file="WEB-INF/jspf/namnuppgifter_sok2.jspf" %>

<div class="popup" id="popupSokNamn"
<% if(!showSearch) { %>
style="display: none;"
<% } %>
>
<%@ include file="WEB-INF/jspf/namnuppgifter_sok.jspf" %>

<div class="popup" id="popupD"
<% if(!showSearchD) { %>
style="display: none;"
<% } %>
>
<%@ include file="WEB-INF/jspf/handlaggare_sok.jspf" %>

<div class="popup" id="popupI"
<% if(!showSearchI) { %>
style="display: none;"
<% } %>
>
<%@ include file="WEB-INF/jspf/ingivningsdag_sok.jspf" %>

<div class="popup" id="popupP"
<% if(!showSearchP) { %>
style="display: none;"
<% } %>
>
<%@ include file="WEB-INF/jspf/prioriteter_sok.jspf" %>

<div class="popup" id="popupR"
<% if(!showSearchR) { %>
style="display: none;"
<% } %>
>
<%@ include file="WEB-INF/jspf/rabattgrundande_sok.jspf" %>

</form>
<%@ include file="WEB-INF/jspf/arendeprocess_messages_inc.jspf" %>

And when I add this part it starts complaining about pagecontext:
<div class="popup" id="popupF"
<% if(!showSearchF) { %>
style="display: none;"
<% } %>
>
<%@ include file="WEB-INF/jspf/fullfoljd_fran_sok.jspf" %>

I don't even have JSP code in the popup, I reduced it to plain HTML to prove that it is not my JSP that is causing this error:

Sök efter ärende

  X

Sök efter ärende

Visa sökformulär

Dölj sökformulär

 Sök efter ärende

<input type="text" size="60" name="">

<input type="button" value="Avbryt">

<input type="button" value="  Sök  " onclick="javascript:doSubmit('Arendesokning', 'search')">

Sökresultat:

    En massa text Hjälp!

    <input type="button" value="Visa alla">

    Antal ärenden: <%= resultList.size() %>

    Visa ärenden: <a class="link" href="javascript:doSubmit('MenyNavigation', 'REW_<%= thisPage %>')" >

        <a class="link" href="javascript:doSubmit('MenyNavigation', 'FWD_<%= thisPage %>')" >

    Ärende
    Ingivningsdag
    Sökande1
    Uppfinnare1
    Ombud1

<tr  class="g2" onmouseover="javascript:setStoreStyle(this)"; onmouseout="javascript:getStoreStyle(this)" <%}else{%>class="g1" onmouseover="javascript:setStoreStyle(this)" onmouseout="javascript:getStoreStyle(this)"<%} %> onclick="javascript:goToOversikt('','','','','','')" style="cursor:pointer;">

<input type="button" id="visaknapp" value="Visa" disabled style="width:150px;" onClick="getElementById('sokR').style.display='', getElementById('bottomA').style.display='', getElementById('bottomV').style.display='none', getElementById('Vsok').style.display='', getElementById('sokF').style.display='none'">
<input type="button" value="Avbryt" style="width:150px;" class="checkmargin"><input type="button" value="Infoga" disabled style="width:150px;">

<input type="button" value="Ändra i register" style="width:150px;">
<input type="button" value="Avbryt" style="width:150px;" class="checkmargin"><input type="button" value="Infoga" style="width:150px;">

A: I think this is because of having scriplets in your JSP. You might have some scriptlet which is not closing the block properly.
Or could be some of your jspf's are is not having proper braces. Look at your generated Java code and debug where it has gone wrong.
Using Java code inside JSP should be avoided to get rid of these kind of problems. Java code should be put in Sevlets and EL should be used in JSP's.


text:
Q: how to find slope of discrete point? I am wondering if it is possible to find the slope at each point in the following dataset,

%  X       Y
%===================
0.7761  0.5715
0.794   0.5729
0.8117  0.5744
0.8292  0.5762
0.8465  0.5782
0.8637  0.5804
0.8807  0.5828
0.8977  0.5853
0.9144  0.5879
0.9311  0.5907
0.9477  0.5937
0.9641  0.5968
0.9805  0.6
0.9967  0.6033
1.0129  0.6067
I understand that the slope can be obtained using the difference of the two neighboring points by
$$m = \frac{y_2-y_1}{x_2-x_1}$$
and, the angle that each point made with the $x$-axis is essentially the $atan$ of $m$
$$\theta = \tan^{-1}(m) $$
But, is it possible to calculate the slope without using the above formula? without trying to curve-fit the points.

A: In my experience,
when trying to estimate the slope at a point,
it is better to use the slope of the line
between the preceding and following point.
This is analogous to the fact that
$f'(x)$
is more accurately estimated by
$(f(x+h)-f(x-h))/(2h)$
(error of order $h^2$)
than by
$(f(x+h)-f(x))/(h)$
(error of order $h$).


text:
Q: Set Max filesize in PHP7 on Ubuntu16 Running Nginx I have changed the following lines in
vi /etc/php/7.0/cli/php.ini

upload_max_filesize = 24M
post_max_size = 32M

I run
service nginx restart
and
systemctl restart php7.0-fpm.service

but it does not seem to update in my phpinfo  - it still says 2M.

A: It's the wrong .ini
vi /etc/php/7.0/fpm/php.ini

this works.


text:
Q: How can you locate a cron job script that's running on a production server? Transitioning development teams and the Cron Job scripts are "unavailable", however, they are still running and being executed.  How can we locate those scripts?

A: Take a look at the table of jobs with crontab -l
and edit them if needed with crontab -e
A directory which stores a file for each job is often named
/var/spool/cron/crontabs/, and other crontab file locations include (many thanks to steeldriver for these) the system-wide crontab file /etc/crontab, as well as possibly the Debian-specific files /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, /etc/cron.monthly and any conformant files under /etc/cron.d .


text:
Q: How to avoid save conflicts when edit item hierarchy in Sharepoint 2013 Developing Sharepoint 2013 portal, I met the problem of saving conflicts, caused by rapidly item updates by several users. Yep, i know about versioning and checkin/checkout, but situation gets harder because, editing one item, user indirectly updates fields of all related items hierarchy. Making item checkout will cause all range of related items to get uneditable, that is unacceptable.
Is anyone faced this problem? I need your help


text:
Q: Animate.css jQuery animate one element after another I am currently using the animate.css library and i am trying to add a class to one element then once that animation has ran i want to add another class to another element so it in simple terms something fades in then something else fades in afterwards.
link to library :
Animate.css
example code :
<!doctype html>

Welcome!

The above is the way i tried to accomplish this but it doesn't work. Im fairly new to jquery/css animations so any help appreciated!

A: Unfortunately you can't perform an action on completion of a CSS animation.  Your other options are to use javascript setTimeout() function, or move the animations to JQuery, which will be easier to synchronize.  Here's an example:
$('#element1').fadeOut(500, function() {
    $('#element2').fadeIn(500);
});

fadeOut, fadeIn, and other JQuery animation functions come with a callback for when the animation is complete.  This helps quite a lot with timing.  I know this example isn't specifically your animations, but should demonstrate how it can be done.
On second glance, though, your library looks like it has callback functionality built in.  Perhaps it's not working properly because of the typo "fucntion()"?

A: Creating your own jQuery plugin could be useful. Place this code right after jQuery definition:
$.fn.animate_css = function(animation, duration, callback) {
    if ((typeof duration !== "undefined") || (duration != null) ) {
        this.css("-webkit-animation-duration", duration+"s");
    }
    this.addClass("animated " + animation);
    this.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', callback);
}

With this you are able to use it like this:
$(".some_element").animate_css("shake", 1.5, function() {
    $(".some_element").animate_css("flash", 2.5);
} );

This code starts "shake" animation with 1.5 second duration and after it starts "flash" animation with 2.5 seconds duration. For better understanding i suggest to learn how callbacks work in javascript.


text:
Q: Using quantum entanglement to send messages back to the past
Possible Duplicate:
Entanglement in time

I heard that there is an experiment that uses quantum entanglement to try to send messages back to the past. I am having a hard time understanding how such experiments would work theoretically.
Can anyone offer me some insights toward these types of experiment?

A: My theory is if one day we can send a message to the past, somebody will obviously sent message in the past to explain they are able to send message over the time.
Today, as we know, we never receive this kind of message. So we will never able to send message in the past.

A: I don't know what kind of experiment might work like that. The only thing that comes to mind is that it could somehow exploit the superluminal speed of wavefunction collapse to transmit information. But this is, of course, impossible.
Although the collapse itself is instantaneous, it is completely random so there is no information transferred in it. The moment of transfer comes when the two parties use classical communication to compare the measurement results on both parts of the system. But this can never happen faster than with the speed of light.

A: Perfect state distinguishability and computational speedups with
postselected closed timelike curves
http://rd.springer.com/article/10.1007/s10701-011-9601-0
http://arxiv.org/pdf/1008.0433.pdf
....Postselection of quantum teleportation in this fashion implies that an entangled state efectively creates a noiseless quantum channel into the past.....


text:
Q: Sum of element in a list with python I have a list of feature :
[(0.14409883378622257, 'count_90'), (0.1274820635854658, 'count_60'), (0.10362930186446877, 'count_30'), (0.017066033814948037, 'country_code_destination_ID'), (0.014104260612047153, 'country_code_destination_US'), (0.011414953372550486, 'SACC_MARKET_SEGMENT_BDZ'), (0.010291762087645236, 'leading_bu_PP'), (0.009979426898654558, 'SACC_MARKET_SEGMENT_IT3')]

Each element of the the list is a tuple composed from feature and a importance value.
I have a list strings (suffix) :  "SACC_MARKET_SEGMENT", "country_code_destination", "leading_bu"
My objective is a count the sum of the element of list having the same suffix mentionned in the list of suffix cited abaove.
Here, for example i would have a result like this :
(0.14409883378622257, 'count_90')
(0.1274820635854658, 'count_60')
(0.10362930186446877, 'count_30')
(0.017066033814948037 + 0.014104260612047153 'country_code_destination)
(0.011414953372550486 + 0.009979426898654558 'SACC_MARKET_SEGMENT')
(0.010291762087645236, 'leading_bu')

Can you help to resolve this problem ?
thank you

A: Do you mean like this?

from collections import Counter
a = [(0.14409883378622257, 'count_90'), (0.1274820635854658, 'count_60'), (0.10362930186446877, 'count_30'), (0.017066033814948037, 'country_code_destination_ID'), (0.014104260612047153,
                                                                                'country_code_destination_US'), (0.011414953372550486, 'SACC_MARKET_SEGMENT_BDZ'), (0.010291762087645236, 'leading_bu_PP'), (0.009979426898654558, 'SACC_MARKET_SEGMENT_IT3')]
cnt = Counter()
for item in a:
    cnt[item[1]] += item[0]

A: This does not look pretty but It will get you the sums for each 'root', i.e.
d1 = []; d2 = []
for i in l1:
    v1 = i[1].split('_')[0]
    v2 = i[0]
    d1.append(v1)
    d2.append(v2)

d1
#['count', 'count', 'count', 'country', 'country', 'SACC', 'leading', 'SACC']
d2
#[0.14409883378622257, 0.1274820635854658, 0.10362930186446877, 0.017066033814948037, 0.014104260612047153, 0.011414953372550486, 0.010291762087645236, 0.009979426898654558]
df1 = pd.DataFrame({'root':d1, 'value':d2})
df1
#      root     value
#0    count  0.144099
#1    count  0.127482
#2    count  0.103629
#3  country  0.017066
#4  country  0.014104
#5     SACC  0.011415
#6  leading  0.010292
#7     SACC  0.009979

df1.groupby('root')['value'].sum()

which gives,

root
SACC       0.021394
count      0.375210
country    0.031170
leading    0.010292
Name: value, dtype: float64

A: Here is an implementation using sum and filter and lambda.
l = [(10, 'a'), (20, 'x'), (100, 'ab'), (200, 'ba')]
In[111]: l
Out[111]: [(10, 'a'), (20, 'x'), (100, 'ab'), (200, 'ba')]
In[112]: x = list(filter(lambda x:'a' in x[-1], l))
In[113]: x
Out[113]: [(10, 'a'), (100, 'ab'), (200, 'ba')]
In[114]: z = sum(p for p,q in x)
In[115]: z
Out[115]: 310

A: If the "roots" are always the same, you can catch them with regex.
With this solution, it changes the original list.
import re

l = [(0.14409883378622257, 'count_90'),
     (0.1274820635854658, 'count_60'),
     (0.10362930186446877, 'count_30'),
     (0.017066033814948037, 'country_code_destination_ID'),
     (0.014104260612047153, 'country_code_destination_US'),
     (0.011414953372550486, 'SACC_MARKET_SEGMENT_BDZ'),
     (0.010291762087645236, 'leading_bu_PP'),
     (0.009979426898654558, 'SACC_MARKET_SEGMENT_IT3')]

country_code_value = 0
sacc_market_value = 0

# Loop on the list with indexes and increment values when catch regex pattern.
for i, t in enumerate(l):
    if re.search(r"country_code_destination", t[1]):
        # remove the element of the list and keep value in variable
        country_code_value += l.pop(i)[0]
    elif re.search(r"SACC_MARKET_SEGMENT", t[1]):
        # remove the element of the list and keep value in variable
        sacc_market_value += l.pop(i)[0]

# Make tuples
country_code_destination = (country_code_value, "country_code_destination")
sacc_market_segment = (sacc_market_value, "SACC_MARKET_SEGMENT")

# And append to the original list
l.append(country_code_destination)
l.append(sacc_market_segment)


text:
Q: Rails 5.2 returning 406 with Axios Request I have a rails API in Rails 5.2 and a frontend in Vuejs, using Axios to request API.
When I request with postman on route

[GET] http://localhost:3000/foo

I get the expected JSON response.
But when I request with Axios :
import axios from 'axios'

export default {
  getAll () {
    return axios.get('http://localhost:3000/foo', {
      headers: { 'Content-Type': 'application/json' }
    })
  }
}

I got this response from the server :

CleanwalksController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

I have the following config/cors.rb :
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

I got the same issue when I try to access to http://localhost:3000/foo directly.
Here is my controller :
class FooController < ApplicationController

  def index
    @foo = foo.all
  end

end

A: I think your problem comes from your view, do you have a file named index.html.erb. Otherwise, you can define multiple response format as following :
class FooController < ApplicationController

def index
  @foo = foo.all
  respond_to do |format|
    format.html { render :index }
    format.json { render json: @foo, status: 200 }
  end
end

end

A: I was having the exact same issue. Everything worked perfectly in my specs and in postman, but for some reason I was getting a 406 with vue/axios.
After much hair pulling I discovered a typo in my routes file:
namespace :v1, default: { format: :json } do

It should have been defaults (plural)
namespace :v1, defaults: { format: :json } do


text:
Q: How can I improve the downvotes of a question as an author? I asked a question on StackOverflow yesterday: https://stackoverflow.com/questions/17396342/java-diffie-hellman-key-exchange-implementation-gotcha

*

*Before asking I searched almost a day for solutions, including StackOverflow

*I phrased the question well (I'm not a native speaker, but my grammar is OK)

*Provided concept code

*Explained my motivations well

*It's definitely not a homework questions

Then someone came along and without any explanation, feedback or guidance downvoted the question.  This probably made people ignore it, and as another result it certainly get out of sight of many people who maybe able to potentially answer the question which is the goal of this entire site.
My question: can I somehow challenge a downvote? It ruins the usefulness of the site. We come here to solve problems.
(I asked my friends if there's anything wrong with the question. It is certainly not too specific, you can see many people struggling with Java DH implementations. It is specific maybe if that area is out of your knowledge, but than any such area could be "too specific = you don't know it". The other thing we could think of is that the person didn't read well, and thought that I need SSL, but that's not the case).
I'd like to see who actually gave the downvote, so I can get a feedback from the person to improve the question.

A: No, you can't see who placed that downvote. Not even Community Moderators can do that. Votes are anonymous by design, and I don't ever see that changing.
People can vote up or down a question or answer for whatever reason they choose. Perhaps they thought your question was too easy. Perhaps they didn't like how you phrased it. Perhaps they don't like your avatar. People are encouraged to write comments to explain why think a post isn't up-to-snuff, but it isn't required.
All you can do is step back and see if there is a way to improve your question. If not, then just forget about it and move on. It's just one vote.
Of course, you've now brought attention to your question here on Meta. That may or may not work out for you. Good luck.

A: Answering your question...
As for your "question" portion... Any attempt to "play" the system to counteract the -1 is going to be considered a breach of terms of use. Don't do it. You're not suppose to be able to.
Moving Forward...
Having taken a very quick glance at your question, you almost certainly triggered someone's tl; dr. response. That may have been manifested in the form of a downvote. Some questions can be summarized better, some need a ton of detail.
I might try to break up big walls of text or code by writing inline explanations for small blocks of code (instead of code comments, which make for a longer code block).
Some people are going to vote down because it's not interesting to them; I certainly can sympathize. It's also entirely possible that your topic is very niche, and will only benefit from a bounty.
One final thought: don't become too concerned about a negative score causing people to steer clear of your question. I'm quite the opposite; negative scores attract me to questions, so it may end up working out in your favor, in the long run!

A:
can I somehow override/undo the -1?

No, you cannot.  Everyone has the right to vote however they want on any post, barring a few exceptions for cases of voting fraud.  You cannot undo the vote.

Such cases ruins the usefulness of the site. We come here to solve problems, and such ignorant actions jeopardize that.

While downvotes that may seem improper can be problematic at times, the voting system adds far more value than the problems it causes.  Allowing you to just invalidate a vote because you don't like it would effectively be the same as removing the voting system entirely.
The ability for users to be able to downvote poor quality content is essential to the success of the site.


text:
Q: High rate of InternalServerError when sending FCM We're receiving what seems to be an unreasonably high rate of Error 500 (Internal Server Error) when sending via FCM.
Some points :

*

*We use both the FCM legacy HTTP API as well as HTTP v1 API, both return an error around 3% of requests sent.

*We have implemented exponential backoff way more than is required (the first error we stop sending for 30 seconds, and increment up to 5 minutes).

*There is no "Retry-After" returned to us.

*We are removing any tokens that are returned as unregistered.

*We send over 500k messages per day. I'm sure by Google volume this is negligible.

*We have tried using batch sending using the endpoint - https://fcm.googleapis.com/batch this also returns the same error percentage and often higher.

*Have sent to Firebase support but (as usual) do not expect anything useful from them.

How can I resolve this?


text:
Q: Win7: Disable UAC/Secure Desktop video mode change
Possible Duplicate:
Stop UAC/Secure Desktop from dimming the screen

Just had to upgrade my office PC to Windows 7, and every time a program wants admin access it seems to enable a "secure desktop" which (for reasons that escape me) this involves telling the video card to shut off its output and then re-enable it, even though the screen resolution and other settings are entirely unchanged.
This process causes my monitor to lose sync and it takes about five seconds for the picture to return.  Needless to say this is very distracting and slows me down considerably.
I know it is possible to disable the secure desktop, but I would rather leave it on if possible.  I do however, want to stop Windows from resetting the video mode and to just leave the screen in its current mode.
So is it possible to leave UAC enabled, but prevent it from stuffing around with the video mode?

A: In the Start search box type UAC, then click the link "change user account control settings"
Or access it using Control Panel (icon view) > User Accounts
Set the UAC control down one notch, hit OK.
.

.
More on UAC settings
.


text:
Q: I cannot boot to the desktop because I filled the file system. How do I reclaim some space? My memory is completely full when I tried following the data recovery and copied the wrong file using command line tool Test Disk. As it was taking so long to copy, I turned it off and I realized I copied the wrong file. Now my laptop memory is now full and lead me to more problems.
I have had similar problems to :
Ubuntu boots on terminal only, how do I recover the GUI desktop?
"dev/sda1: clean, ..." This message appears after I startup my laptop, then it won't continue booting
Now my screen keeps blinking:
https://www.youtube.com/watch?v=BN4twl0V8JQ
Can anybody help?
Many thanks. Wish you all the best.


text:
Q: Telerik Error - Parameter name: panelsCreated[6] I have a simple page that uses telerik:RadAjaxManager.
For some reason on page load I'm getting this error in browser console:

I googled it, and found lots of articles where they say I need to switch off debug mode in web.config. So it would hide the error, but it doesn't solve it at all.
Any suggestions?


text:
Q: jQuery not pushing JSON-data I have the  following script which is supposed to pull data and display it in a HTML table:
$('#search_filter_button').click(function (e) {
    e.preventDefault(); // Stop form submission
    var county = $('#filter_county').val(),
        kp_type = $('#filter_kp_type').val(),
        getUrl = window.location,
        baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

    html_tr = '';
    $.ajax({
        type: 'GET',
        url: baseUrl + "/reports/get_report.php?county=" + county + "&kp_type=" + kp_type,
        dataType: "JSON",
        success: function (data) {
            console.log(data);
            for (i = 0; i < data.length; i++) {
                html_tr += '
\n\
                ' + data[i].name + '	\n\
                ' + data[i].Abbrv + '	\n\\n\
                ' + data[i].partner_name + '	\n\\n\
                ' + data[i].facility_name + '	\n\\n\
                ' + data[i].county + '	\n\\n\
                ' + data[i].no_kps + '	\n\\n\
                ' + data[i].activity_stamp + '	\n\
';
            }

            $('#tbody_append').empty();
            $('#tbody_append').append(html_tr);
        }, error: function (data) {
        }
    });
});

My get_report.php file looks like this:
include '../database/db_connect.php';

$mysqli = mysqli_connect($host_name, $user_name, $password, $database);

$county = $_GET['county'];
$kp_type = $_GET['kp_type'];

// get the records from the database
$result = mysqli_query($mysqli, "SELECT * FROM `no_individaul_kps_contacted` where county='$county'");

$count_row = mysqli_num_rows($result);
if ($count_row >= 1) {
    // display records if there are records to display

    while ($user_data = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        echo json_encode($user_data);
    }
} else {
    // show an error if there is an issue with the database query
    echo "Error: " . $mysqli->error;
}

// close database connection
mysqli_close($mysqli);

This pulls the information and echoes it back in JSON ENCODE format. But my JavaScript is not returning a success.
Please advise what am I doing wrong.

A: Collect the user data into array inside the while loop and move json_encode($data) outside the while loop:
$select = "SELECT * FROM `no_individaul_kps_contacted` where county='$county'";
$result = mysqli_query($mysqli, $select);
$data = [];

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $data[] = $row;
}

echo json_encode($data);


text:
Q: Как сделать  OBJECT ссылочным? Всем привет! Народ, помогите разобраться. На сайте имеется flash баннер, необходимо сделать его ссылочным, перепробовал всё, что знал, описываю варианты которые испробовал:
1ый вариант (атрибут onclick прописан самому элементу OBJECT) - не отрабатывает, редирект не происходит:
<object type="application/x-shockwave-flash" data="http://test.ru/banner.swf" height="150" width="200" onclick="'window.location = "http://ya.ru";'">
    <param name="allowFullScreen" value="true" />
    <param name="allowScriptAccess" value="always" />
    <param name="movie" value="http://test.ru/banner.swf" />
</object>

2ой вариант (сделал DIV-обертку для элемента OBJECT) - не отрабатывает, редирект не происходит::

<object type="application/x-shockwave-flash" data="http://test.ru/banner.swf" height="150" width="200" onclick="'window.location = "http://ya.ru";'">
    <param name="allowFullScreen" value="true" />
    <param name="allowScriptAccess" value="always" />
    <param name="movie" value="http://test.ru/banner.swf" />
</object>

3ий вариант (создал блок DIV и расположил его поверх элемента OBJECT, событие onclick прописал DIV`у) - работает только в Crhome, в остальных браузерах мой DIV находится под элементом OBJECT:

    <object type="application/x-shockwave-flash" data="http://test.ru/banner.swf" height="150" width="200" onclick="'window.location = "http://ya.ru";'">
        <param name="allowFullScreen" value="true" />
        <param name="allowScriptAccess" value="always" />
        <param name="movie" value="http://test.ru/banner.swf" />
    </object>

A: *

*флеш публиковать с параметром wmode=transparent — это позволит div-контейнеру принимать JS-события над флешем;

*ловить не onclick, а onmousedown, это в большем числе браузеров сработает.

Примерно так:

  <object>
    <param name="movie" value="3.swf">
    <param name="wmode" value="transparent" />
    <embed wmode=transparent allowfullscreen="true" allowscriptaccess="always" src="3.swf"></embed>
  </object>

Источник ответа.


text:
Q: jQuery post and .NET MVC action - returning partial results to end user I have a question in regards to a concept that I haven't had a chance to encounter before, but I have been thinking about it for a long time and I wanted to see if it's doable in .NET MVC 5 using jQuery...
So let's say we have an action  in controller which looks like this:
[ActionName("OurTestAction")]
[HttpPost]
public ActionResult OurTestAction()
{
 Method1();
//returning some sort of "signal" here to client side to notify that the method1 finished processing data.. ?
 Method2();
 Method3();
 return Json("Ok");
}

Where the action was triggered like this:
$(document).ready(function(){
$.post("/Controller/OurTestAction").done(function(response){
// displaying the result here
});
}):

So the idea that I had with this piece of code is that I could be able to tell end user when was the Method1() called and ended it's life cycle. Once the Method1(); finishes what it was supposed to do, I'd like to be able to tell the end user in his browser something like this (via jQuery): Method1() finished processing the data , moving onto the method2();
Is something like this doable with jQuery and .NET, and if so how?
Can someone help me out ?

A: Break your controller methods into different actions.
Controller
[HttpPost]
public ActionResult Method1()
{
  Method1();
  return Json("Ok");
}

[HttpPost]
public ActionResult Method2()
{
  Method2();
  return Json("Ok");
}

[HttpPost]
public ActionResult Method3()
{
  Method3();
  return Json("Ok");
}

Javascript
$.ajax({
    type: 'POST',
    url: 'controller/method1'
}).done(function(resp) {
   //do stuff to notify users method 1 is complete
    $.ajax({
        type: 'POST',
        url: 'controller/method2'
    }).done(function(resp2) {
        //do stuff to notify users method 2 is complete
    });
});


text:
Q: Outputting an image not working properly I'm trying to output an image with PHP, but when I do it, it won't look as the original image. The original image has transparent background, and the outputted image has some weird background which "kills" the image.
This is my code:
<?php
$image = imagecreatefrompng('./logo2.png');
$imagesize = getimagesize('./logo2.png');
header('Content-type: ' . $imagesize['mime']);
imagepng($image);
imagedestroy($image);

If you need anything else in order to determine the issue, please tell me.

A: Add alpha blending:
<?php
$image = imagecreatefrompng('./logo2.png');
$imagesize = getimagesize('./logo2.png');
header('Content-type: ' . $imagesize['mime']);

imagealphablending($image, true);
imagesavealpha( $image, true );

imagepng($image);
imagedestroy($image);

This was answered for example here:


text:
Q: Can the wrong refresh rate damage my monitor? I have a Samsung LCD monitor measuring 21 inches. The refresh rate is 60 Hz, but if I select a setting higher than that, I get an error.
I actually don't know the exact screen resolution of my PC, but it shows refresh rate around 60 - 72 Hz I think.
Right now, i set to 1600 x 900. Is it safe?
Can setting the wrong refresh rate damage my monitor?

A: Yes, incorrect settings can break a monitor.  Most significantly, refresh rate can cause serious problems.  An incorrect resolution (number of horizontal pixels x number of vertical pixels) may be less likely to cause damage.  But at least some monitors really dislike bad refresh rates.
Now, how likely is damage to occur?  That can vary based on factors like how good of quality the monitor is.  Ideally, if a monitor doesn't support certain settings, then it will just show a message saying "No signal", or something benign like that.  What will break some monitors might not break other monitors.
I'm basing this on third party information that I've heard or read multiple times over many years.  I have experienced some CRT monitors make interesting noises, like the snap of a spark.  I was sane enough to not tempt fate and try to create a fire hazard, so I would immediately do something (probably pressing Esc on the keyboard, to undo the change made in a GUI...  if that didn't have the desired effect, I probably turned off the monitor to try to prevent permanent damage.)
There may be a sticker on the back of the PC, near where the power cord goes, which may provide a list of officially acceptable refresh rates.  Deviating from that list is not recommended.  Often, newer video drivers try to only provide options specified by the monitor's driver.  When I first got into computing, there usually weren't specific drivers for monitors, so such protections were historically less common.

A: CRTs, yes, but not modern LCD displays.
Older tube displays were often dumb analog devices operating at the mercy of the VGA input and can be damaged by inputs that commanded the display to run beyond its limits. With an excessive refresh rate, the electron gun in a CRT that is directly controlled by the VGA input could be made to scan faster than designed, resulting in hardware failure.
LCD and other flat-panel monitors are digitally controlled and will simply reject out-of-range inputs, displaying an error message. It should not be possible to damage an LCD display with excessive refresh rates.

A: I believe the answer is "not any more." Back in the earliest days of the IBM PC, the 12" monochrome CRT reportedly vould be damaged by ... "creative" ... reprogramming of the matching display adapter. Several copyprotect schemes threatened to trigger that if you tampered with them, but I don't believe anyone ever risked the liability of implementing that.
I don't believe a similar vulnerability has existed since then.


text:
Q: ffplay startup time proportional to specified framerate I am playing a video over http using ffplay. The call I am using looks like this:
ffplay -framerate 30 -fflags nobuffer -flags low_delay -autoexit -i http://localhost:8880

The video is an H.264 encoding where (my understanding is a bit unclear here) it is something like a "raw" H.264 stream without timestamps.
My primary concern is to get video displayed with low latency. In that regard, the video is fine.
The issue is with the framerate and with the startup time.
The video source is emitting frames as soon as they are processed, so the frame rate is not constant. However, my experience is that as long as you specify a framerate larger than the max achievable frame rate of the source, then the viewer still looks fine. On the flipside, if the video source starts emitting frames at 60 fps, but I specify a framerate of 30, then the delay just sort of builds up in ffplay to the point where after 10 seconds, the video is 20 seconds behind. So the first question would be whether there is a way to get ffplay to use a variable framerate. The behavior I am looking for is "display a frame as soon as it is received over http".
In light of the aforementioned issue, the approach I have been taking is to simply specify a high framerate, which seems to work. However, there is an issue with this approach in the form of startup time. When I set the framerate to 10, the ffplay window starts in approx 3 seconds, but then quickly starts accruing a lag (so I can't do this). When I set the framerate to 100, the ffplay window takes 30 seconds (literally 30 seconds) to start, but then will not have any lag.
I have seen that ffmpeg has a vsync option that on the surface seems like it would allow you to set a variable framerate. However, ffplay doesn't seem to recognize this. I would also be willing to pipe the output of ffmpeg to a different window (I am running Ubuntu 18.04) if that is what must be done, but I would prefer not to have to recompile ffplay.


text:
Q: Changing toaster class from the controller toaster.pop() Im using toaster for angular:
https://github.com/jirikavi/AngularJS-Toaster

This is my directive:
<toaster-container toaster-options="{'time-out': 3000}"></toaster-container>

all good here, what i want to do is this, right now it shows me all the msgs in right top corner of the screen, which is what i want (it's also the default behavior), i want to do (for some particular msgs) this:
<toaster-container toaster-options="{'position-class': 'toast-top-full-width'}"></toaster-container>

Now i can't seem to find any option to change the position class from the pop() method:
https://github.com/jirikavi/AngularJS-Toaster/pull/40/files?short_path=04c6e90

What i currently have is simple msgs like:
toaster.pop('success','Redirecting to paypal');

And i need something like this:
   toaster.pop('success','Redirecting to paypal',{'position-class':'toast-top-full-width'});

What should i do?

A: I usually post the toaster configuration in my index page, since I'm using toaster to send notifications across the system that's a suitable place to write it and not repeat the configuration.
<toaster-container toaster-options="{
  'closeButton': false,
  'debug': false,
  'positionClass': 'toast-top-right',
  'onclick': null,
  'showDuration': '200',
  'hideDuration': '1000',
  'timeOut': '5000',
  'extendedTimeOut': '1000',
  'showEasing': 'swing',
  'hideEasing': 'linear',
  'showMethod': 'fadeIn',
  'hideMethod': 'fadeOut'
}"></toaster-container>

don't forget to include the file
AngularJS-Toaster/toaster.css to your index reference
then the signature for the pop is the following:
(type, title, body, timeout, bodyOutputType, clickHandler)

so you'll have to do something like
toaster.pop('success','Redirecting to paypal',null,'5000','toast-top-full-width');


text:
Q: Batch file to move contents of a folder with Subfolders to same structure on Partition drive I am wondering how to create a .bat file to move all files within a folder containing subfolders to an identical setup on a different volume.
For example, Folder called Support with Subfolders called Support1, Support2 etc. I want to move files greater than 5 days and update the existing files in the partition drive.
Support
    -> Support1 -> Contains files
    -> Support2 -> Contains files

A: Since you are asking about a batch file, I'll assume this is on Windows
xcopy /E /T /D:m-d-y <top level source dir> <destination>

/D:m-d-y will copy only files changed on or after the specified date.


text:
Q: 302 found issue codiginiter Hope you are doing well
I am having issue with one URL, https://www.example.com/dashboard
Here i have condition if user is not loggedin then it should redirect at home page , Due to this reasn my above url is showing 302 found error in seo , How can i allow this url in seo as 200 status beaucse url is correct but it reidirect beaucase user is not logged in
  public function index($id=1){
 if($this->input->cookie('country')) {
            $countryId = $this->input->cookie('country');
        }
        else{
            //$countryId = $id;
            redirect(base_url());
        }

Technology is in codiginiter

A: $agent = $this->request->getUserAgent();

if ($agent->isBrowser())
{
 if($this->input->cookie('country')) {

            $countryId = $this->input->cookie('country');

        }else{

            redirect(base_url());

        }
}

A: HTTP 302 response code means that the URL of requested resource has been changed temporarily. Further changes in the URL might be made in the future. Therefore, this same URI should be used by the client in future requests.You can check this out to learn more
Since you are actually redirecting Non-authenticated users (A category bots belong to), i think the error code is correct.
What you can do however, is to add the page to robots.txt file so the page does not get indexed at all.


text:
Q: JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences? I am writing a webservice that uses json to represent its resources, and I am a bit stuck thinking about the best way to encode the json. Reading the json rfc (http://www.ietf.org/rfc/rfc4627.txt) it is clear that the preferred encoding is utf-8. But the rfc also describes a string escaping mechanism for specifying characters. I assume this would generally be used to escape non-ascii characters, thereby making the resulting utf-8 valid ascii.
So let's say I have a json string that contains unicode characters (code-points) that are non-ascii. Should my webservice just utf-8 encoding that and return it, or should it escape all those non-ascii characters and return pure ascii?
I'd like browsers to be able to execute the results using jsonp or eval. Does that effect the decision? My knowledge of various browser's javascript support for utf-8 is lacking.
EDIT: I wanted to clarify that my main concern about how to encode the results is really about browser handling of the results. What I've read indicates that browsers may be sensitive to the encoding when using JSONP in particular. I haven't found any really good info on the subject, so I'll have to start doing some testing to see what happens. Ideally I'd like to only escape those few characters that are required and just utf-8 encode the results.

A: I was facing the same problem. It works for me. Please check this.
json_encode($array,JSON_UNESCAPED_UNICODE);

A:
Reading the json rfc (http://www.ietf.org/rfc/rfc4627.txt) it is clear that the preferred encoding is utf-8.

FYI, RFC 4627 is no longer the official JSON spec. It was obsoleted in 2014 by RFC 7159, which was then obsoleted in 2017 by RFC 8259, which is the current spec.
RFC 8259 states:

8.1.  Character Encoding
JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8 [RFC3629].
Previous specifications of JSON have not required the use of UTF-8 when transmitting JSON text.  However, the vast majority of JSON-based software implementations have chosen to use the UTF-8 encoding, to the extent that it is the only encoding that achieves interoperability.
Implementations MUST NOT add a byte order mark (U+FEFF) to the beginning of a networked-transmitted JSON text.  In the interests of interoperability, implementations that parse JSON texts MAY ignore the presence of a byte order mark rather than treating it as an error.

A: I had a problem there.
When I JSON encode a string with a character like "é", every browsers will return the same "é", except IE which will return "\u00e9".
Then with PHP json_decode(), it will fail if it find "é", so for Firefox, Opera, Safari and Chrome, I've to call utf8_encode() before json_decode().
Note : with my tests, IE and Firefox are using their native JSON object, others browsers are using json2.js.

A: ASCII isn't in it any more.  Using UTF-8 encoding means that you aren't using ASCII encoding.  What you should use the escaping mechanism for is what the RFC says:

All Unicode characters may be placed
  within the    quotation marks except
  for the characters that must be
  escaped:    quotation mark, reverse
  solidus, and the control characters
  (U+0000    through U+001F)

A: The JSON spec requires UTF-8 support by decoders. As a result, all JSON decoders can handle UTF-8 just as well as they can handle the numeric escape sequences.  This is also the case for Javascript interpreters, which means JSONP will handle the UTF-8 encoded JSON as well.
The ability for JSON encoders to use the numeric escape sequences instead just offers you more choice.  One reason you may choose the numeric escape sequences would be if a transport mechanism in between your encoder and the intended decoder is not binary-safe.
Another reason you may want to use numeric escape sequences is to prevent certain characters appearing in the stream, such as <, & and ", which may be interpreted as HTML sequences if the JSON code is placed without escaping into HTML or a browser wrongly interprets it as HTML. This can be a defence against HTML injection or cross-site scripting (note: some characters MUST be escaped in JSON, including " and \).
Some frameworks, including PHP's json_encode() (by default), always do the numeric escape sequences on the encoder side for any character outside of ASCII.  This is a mostly unnecessary extra step intended for maximum compatibility with limited transport mechanisms and the like.  However, this should not be interpreted as an indication that any JSON decoders have a problem with UTF-8.
So, I guess you just could decide which to use like this:

*

*Just use UTF-8, unless any software you are using for storage or transport between encoder and decoder isn't binary-safe.

*Otherwise, use the numeric escape sequences.

A: I had a similar problem with é char... I think the comment "it's possible that the text you're feeding it isn't UTF-8" is probably close to the mark here. I have a feeling the default collation in my instance was something else until I realized and changed to utf8... problem is the data was already there, so not sure if it converted the data or not when i changed it, displays fine in mysql workbench. End result is that php will not json encode the data, just returns false. Doesn't matter what browser you use as its the server causing my issue, php will not parse the data to utf8 if this char is present. Like i say not sure if it is due to converting the schema to utf8 after data was present or just a php bug. In this case use json_encode(utf8_encode($string));


text:
Q: Performance of updating row if content has changed I'm trying to make a website where there is a form that contains input type fields that are editable. In fact I get the elements from one of my tables (containing an id column and a string column) from my database, which I display via input with id as the id in this database and string as the string in this database. The user can edit the text in these fields and also there is the possibility to add a new 'row' (input with string, but which refers to no row in the database).
Finally, there is a button to save.
My question is do I directly modify the existing lines even if the user has not changed the string or should I check if the string has been updated? Which method is best in terms of performance?

A: If your business logic layer(s) know that there has been no change (i.e. it has already re-read the data and can compare it to the provided input then you can simply not send anything to the DB.
If you don't know before hitting the data layer if there has been any change or not then you can do something like:
UPDATE yourTable
SET    field1 = @input1
  ,    field2 = @input2
       ...   ...   ...
  ,    fieldN = @inputN
WHERE  idField = @ID
AND    (
           field1 <> @field1
        OR field2 <> @field2
           ...   ...   ...
        OR fieldN <> @fieldN
       )

This avoids any update if nothing has changed so it more efficient (the lookups needed to reject the update would be needed to perform it anyway and the extra CPU time for the comparison is vanishingly small unless you have huge data in any of the columns), but it is more work to maintain and more prone to errors so most of the time I would recommend keeping it simple and updating without checking every column, i.e. the standard:
UPDATE yourTable
SET    field1 = @input1
  ,    field2 = @input2
       ...   ...   ...
  ,    fieldN = @inputN
WHERE  idField = @ID
-- note no comparison, just update

The maintainability issue is even worse for NULLable columns as fieldN <> @fieldN has to be changed to (`fieldN <> @fieldN OR (fieldN IS NULL AND @fieldN IS NOT NULL) OR (fieldN IS NOT NULL AND @fieldN IS NULL) because comparisons between NULLs are always false (NULL is not equal to NULL, but it is also not not equal to NULL - NULL by definition is unknown so all comparisons (=, !=, <, >, ...) return false unless your DB supports non-ansi behaviour like https://stackoverflow.com/questions/9766717/). If this is all baked into you data access layer then fine, some ORMs for instance provide such optimisation as an option, but you don't want to be manually writing and maintaining it for every update statement in your application.
The DB (ever engine I'm aware of) will perform a full write of the relevant data pages even if no values have changed - they won't spend the few extra CPU cycles checking. Away from the efficiency of the update itself you need to consider knock-on effects and certain business requirements. If there are triggers that take action on updates to the table they will fire even if nothing has changed, this could be a significant consideration if you have any complex triggers to consider. From a business logic point of view do you need to log that the user actively saved the record with no changes? If you are relying on automated change capture of some sort (such as your own triggers, temporal table features in postgres and the upcoming MSSQL2016) to track changes then you (or your end users) need to decide if the data model should care that a no-change update happened or not. Of course if the record includes a "last saved" column this all becomes a moot point - there is always something to update upon save if only that one column.

A: It is more efficient to check if data has changed in the web application
Sending an update to myslq with the same value uses more resources
If there are no changes then send nothing
Better yet don't even have the button active until there are changes
If there are changes only send the changes and do so in one statement
UPDATE yourTable
SET    field1 = @input1
  ,    field2 = @input2
WHERE  idField = @ID

This also makes you application more scalable.  You could had multiple websites to the same mysql.

A: If I understand well then you read the information from the database and display it. The user has the possibility to change it. The fastest way is to compare the information that you read with the information that you get from the user. If there is a difference then you update the information in the database.


text:
Q: how to print array value in batch file I have written a batch file and tried to print array value inside loop. But the value is not echo.
i have tried as
    @echo off
setlocal EnableDelayedExpansion
REM value in allargu -count 100 -delay 100
REM I want a count value 100 in variable
set "allargu="
set n=0
for %%a in (%*) do (
   set /A n+=1
   set "allargu[!n!]=%%~a"
   pause
)

REM For example, to process the filenames:
set /a iter=1
for /L %%i in (1,1,%n%) do (
   echo %%i- !allargu[%%i]!
   set /a iter=%%i
   set eachelement=!allargu[%%i]!
   if "!eachelement!" EQU "-count" (
        set /a iter+=1
    REM here I want to print 100 if count found
        echo %allargu[!iter!]%
)
)

Thanks,