Q: Is the coefficient of linear combination always non-zero? Suppose that there is some vector. And the vector can be decomposed into linear combination of linearly independent vectors. If we set one of coefficients of these vectors to be zero, and we get the vector, would there be another linear combination with all coefficients non-zero that describes the vector?
Also, are all linear combinations usually set to have non-zero coefficients?

A: To answer your first question, no. A linear combination of linearly independent vectors uniquely describes a given vector. This is because two vectors are equal iff their components (i.e. the coefficients on whatever unit vectors you are using) are equal.
For your second question, the answer is also no. There is nothing wrong with having some coefficients as zero. For instance, representing the unit vectors (whatever you define them as) in your system requires each of the other coefficients to be zero.


Q: C# csproj file "Choose" element for assembly HintPaths Is it possible to use the Choose/When/Otherwise elements on a reference hintpath?
Something like this:
<ItemGroup>
  <Reference Include="SharedLib...">
<SpecificVersion>False</SpecificVersion>
<Choose>
  <When Condition="Exists('..\..\SharedLib\bin\Debug')">
        <HintPath>..\..\SharedLib\bin\Debug\SharedLib.dll</HintPath>
  </When>
  <Otherwise>
         <HintPath>.\SharedLib.dll</HintPath>
  </Otherwise>
</Choose>
  </Reference>
</ItemGroup>

But I get errors like ...required attribute "Include" is empty or missing from element "ItemGroup"
Other attempts/version have yielded similar errors such as ...The "Choose" item metadata name is reserved and cannot be used.
This makes me think I canNOT use the "Choose" element INSIDE of an ItemGroup element.
I welcome clarification. See attached samples of the errors.
Visual Studio csproj Errors when loading project

A: I don't think you can put just the HintPath in the Choose. You have to put the entire ItemGroup within the When and Otherwise. Like this:
<Choose>
  <When Condition="Exists('..\..\SharedLib\bin\Debug')">
    <ItemGroup>
      <Reference Include="SharedLib...">
        <SpecificVersion>False</SpecificVersion>
        <HintPath>..\..\SharedLib\bin\Debug\SharedLib.dll</HintPath>
      </Reference>
    </ItemGroup>
  </When>
  <Otherwise>
    <ItemGroup>
      <Reference Include="SharedLib...">
        <SpecificVersion>False</SpecificVersion>
        <HintPath>.\SharedLib.dll</HintPath>
      </Reference>
    </ItemGroup>
  </Otherwise>
</Choose>


Q: VS Code %USERNAME% Wild Card in JSON Settings In the Windows Command Prompt, I can enter:
cd \Users\%USERNAME%

And it takes me to my user's home directory, e.g.: C:\User\MyName.
But in Visual Studio Code's JSON settings, the following doesn't resolve:
{
    "jshint.config": "C:\\Users\\%USERNAME%\\JSHint.json",
}

Is there a trick to getting %USERNAME% to resolve in the JSON settings? Do I need to escape the percentage signs somehow? Or does the %USERNAME% wildcard simply doesn't work in VS Code?


Q: adding a number to a variable I am trying to get the contents of a txt file "usernum.txt", get the contents, add one to that number, and replace the current number with the new one.  Here is what I have so far
#!/bin/sh
ID=0
cat ''$pwd'usernum.txt' >> $ID
count1=1
IDB=$(($ID+$count1))
rm "usernum.txt"
touch "usernum.txt"
echo $IDB >> usernum.txt

It runs but when I open the file, it stays the same.  Any ideas?
Thanks,
Mike

A: You should store the output from cat into ID instead of using >>. The way you are doing that you always add to a file named '0'. To store the output of cat use:
ID=$( cat 'usernum.txt' )

I have also removed the 'pwd' as you do not need it and also it gets escaped by the single quotes.
EDIT: here is a complete working example. Note that if there is no usernum.txt file this will print some errors(cat and rm fail) but still will work(i.e. will print 1 in the file). You should perform a check to see if the file exists to avoid these errors:
ID=$( cat 'usernum.txt' )
count1=1
IDB=$(($ID+$count1))
rm "usernum.txt"
touch "usernum.txt"
echo $IDB >> usernum.txt


Q: Remove a dataframe from a list of dataframes conditionally I have a list of dataframes from which I would like to remove the dataframes that have a particular value in a specific column.
Code
library(tidyverse)

combi <- function(a=c(1,2,3), b=c(2,3,4,5)){
  return(expand.grid(a,b))
}

df <- pmap(list(a=c(1,2,3)), combi)

Output
df
[[1]]
 Var1 Var2
1    1    2
2    1    3
3    1    4
4    1    5

[[2]]
  Var1 Var2
1    2    2
2    2    3
3    2    4
4    2    5

[[3]]
  Var1 Var2
1    3    2
2    3    3
3    3    4
4    3    5

Let's say I would like to remove a dataframe, if Var1==2.
How do you tackle this problem in the Tidyverse?

A: You can use discard in purrr
purrr::discard(df, ~any(.x$Var1 == 2))
#Or using keep
#purrr::keep(df, ~any(.x$Var1 != 2))

#[[1]]
#  Var1 Var2
#1    1    2
#2    1    3
#3    1    4
#4    1    5

#[[2]]
#  Var1 Var2
#1    3    2
#2    3    3
#3    3    4
#4    3    5

Or Filter in base R :
Filter(function(x) any(x$Var1 != 2), df)

Some variations :
df[sapply(df, function(x) any(x$Var1 != 2))]
df[purrr::map_lgl(df, ~any(.x$Var1 != 2))]


Q: How to setup and run openpaas release version in ubuntu I am trying to setup openpaas: [https://github.com/linagora/openpaas-esn ] development on ubuntu system. i am unable to setup.
before seting up locally , i tried running with docker(as in http://docs.open-paas.org/getting-started/linux/ ) it works fine.i need to setup locally (as in https://github.com/linagora/openpaas-esn/blob/master/doc/develop.md), i am facing problem.
now I am following developer documentation: https://github.com/linagora/openpaas-esn/blob/master/doc/develop.md ,after setup installation is complete and point browser to http://localhost:8080 , i get login page But after logging as admin(admin@open-paas.org), i am getting blank screen. I can see error in chrome console.How can i setup locally and run openpaas .
In documentation it says front end is vue.js , but i am getting Angular js, ng route related error .
installed angular router but this did not help .
as in https://github.com/linagora/openpaas-esn/blob/master/docker/doc/known_issues.md , i tried
    docker exec esn_james java -jar /root/james-cli.jar -h localhost adddomain open-paas.org

I did checkout openpass : https://github.com/linagora/openpaas-esn to home folder.
then did
npm install

to run dependecy software as in documentation, i run docker-compose up as below. so redis,rabbitmq,mongo,elasticsearch,sabre,james,james_elastic,cassandra are running in docker,then tested , i am able to connect.
    ESN_HOST="172.17.0.1" ESN_PATH="$PWD" docker-compose -f ./docker/dockerfiles/dev/docker-compose.yml up

then as per documentation , to run openpaas with below command
    grunt dev

tried alternative ways
    node ./bin/cli.js

openpaas is up and running, on pointing browser to http://localhost:8080/ , i get login page , after login i get blank screen. and error in chrome console

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.20/$injector/modulerr?

how do i get it running.
need to setup openpaas locally for start development/customise to my needs.
since i cannot create tag, and openpaas tag is not already present, just added angularjs tag


Q: Не выводит изображение PHP Не получается вывести изображение. Изображение хранится в формате BLOB.

A: Вставка изображения в БД
$db = mysqli_connect("localhost","root","","DbName");
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));

$query = "INSERT INTO products (id,image) VALUES('','$image')";
$qry = mysqli_query($db, $query);

Вывод изображения из БД
$db = mysqli_connect("localhost","root","","DbName");
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';


Q: Swift: Implementing Find-or-Create Efficiently So I set up some data from an API to create a managed object, How do I determine whether the managed object already exists (in my example, every object has a unique id), and create it if it does not.
// set up core data
        var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        var context:NSManagedObjectContext = appDel.managedObjectContext!

        // Get data from API
        let urlPath = "http://www.example.com"
        let url = NSURL(string: urlPath)
        let session = NSURLSession.sharedSession()
        let getMovies = session.dataTaskWithURL(url!, completionHandler: {
            data, response, error -> Void in

            if error != nil {
                println(error)
            } else {

                // Parse the JSON data from API
                var moviesResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

                if let subjects = moviesResult["subjects"] as? [[NSObject:AnyObject]] {
                    var movies = [[String:NSString]()]
                    var movie:AnyObject
                    var newMovieItem:NSManagedObject
                    // Loop through the arrays returned by API to get each movie
                    for (var i = 0 ; i < subjects.count ; i++) {
                        // Initialize the movies array
                        movies.append([String:NSString]())
                        movie = subjects[i] as NSDictionary
                        movies[i]["title"] = movie["title"] as? NSString
                        movies[i]["id"] = movie["id"] as? NSString
                        newMovieItem = NSEntityDescription.insertNewObjectForEntityForName("Movies", inManagedObjectContext: context) as! NSManagedObject
                        newMovieItem.setValue(movies[i]["title"], forKey: "title")

                        newMovieItem.setValue(movies[i]["id"], forKey: "id")

                        context.save(nil)
                    }
                    var request = NSFetchRequest(entityName: "Movies")
                    request.returnsObjectsAsFaults = false
                    var results = context.executeFetchRequest(request, error: nil)
                }
            }
        })
        getMovies.resume()


Q: django how to check if a user is already exists on this app without making too much query? Assume these as django models:
class Question():

    question = charfield()
    choice = charfield(choices = answer_choice)

class Answer():

    question = models.foreignkey(Question, related_name = 'answers')
    answerer = models.foreignkey('auth.User')
    answer = models.charfield()

I'm building a page where i display 100 questions, and each User can answer, but cannot change the answer for each question. For each question, i have to check whether the User already exists or not on Answerer. Then i make templatetags:
    @register.filter
    def this_user_exists(user,obj):
        obj = obj.answers.filter(answerer_id = user.id)
        return obj
Then on the template:
# obj is list of question
{% if not user|this_user_exists:obj %}
    # can answer
{% else %}
    # cannot answer
{% endif %}

The problem is, for every question, it generate 1 query, so for 100 question it'll generate 100 query. I tried this query to generate question Question.objects.all()  and Question.objects.prefetch_related('answers'), still got the problem. Is there a better way to achieve this without making too many query?

A: To reduce queries, you can first query out your needed answers, and then fetch all related answerers,
answers = Answer.objects.select_related('answerer').filter(xxxx)

# fetch related user id's
userids_in_answer = [answer.answerer.id for answer in answers]

# fetch user ids
user_id_set = set(User.objects.filter(id__in=userids_in_answer).values('id', flat=True)

after that, you can easily know whether user exists by,
for answer in answers:
  if answer.answerer.id in user_id_set:
      xxx

The query num is reduced, you can check whether this helps.

A: In your view:
answered_ids = [ans.question_id for ans in Answer.objects.filter(answerer=request.user)]

In your template:
{% if not obj.id in answered_ids %}
    # can answer
{% else %}
    # cannot answer
{% endif %}


Q: retrieving data from play-scala server We want to use REACT in a scala-play project. We'll, also, use AXIOS to send request from REACT (web browser) to the server. The question is, how could be a great way to create services on the play-scala server to respond to the requests coming from the web browser which could be using React?
Thx

A: A great way would be to use the HTTP programming features of Play.


Q: Most secure method of authentication for an API user? We have a need for an external site to call services exposed from our Salesforce org via APEX REST. In previous projects I would leverage a connected app with username/password flow and create an API user to authenticate as. They would call OAuth endpoint providing grant_type of "password" and client_id, client_secret, username, and password.
With this new integration I am looking for something more secure. Is there a better OAuth flow to use other than username/password flow? I still want to create an API user to authenticate as, but wondering if there's a better way to authenticate.
Thanks

A: It depends on your use case. You can use JWT if you don't use a browser environment, or the Web Server Flow for a server experience, or the User Client Flow for mobile or desktop apps.


Q: Why does a insertion/extraction operator's overloaded function need ostream/istream argument? Consider the following code with overloaded insertion & extraction operators.
#include <iostream>

using namespace std;

class CTest
{
    string d_name;
public:
    friend ostream & operator<<(ostream & out, CTest & test);
    friend istream & operator>>(istream & in, CTest & test);
};

ostream & operator<<(ostream & out, CTest & test)
{
    out << "Name: " << test.d_name;
    return out;
}

istream & operator>>(istream & in, CTest & test)
{
    cout << "Enter your name: ";
    string name;
    if(in >> name)
        test.d_name = name;

    return in;
}

int main()
{
    CTest test;
    cin >> test;   // (1)
    cout << test;  // (2)
}

Following the question, what's the significance of arguments ostream & out and istream & in?
Since we can see only one argument (cin >> test or cout << test), where in the caller is the ostream/istream references passed at (1) or (2)?

A: Because in both cin >> test and cout << test, two arguments exist.
cin is of type istream.
cout is of type ostream.
These types could be other things than cout and cin. For example, they could be cerr, clog, or stringstream.
That's why you need two arguments, since the one is the variable for the stream and the other is the object to be streamed.

A: cin >> test;

Here, left operand is the cin object of type std::istream, and the right operand is your CTest class object.
Prototype of >> operator
friend istream& operator >> (istream& s, Your class &);

So, internally we have passed two arguments.

A: In order to get a better understanding where the two arguments come from, you may rewrite your main() function as follows:
int main()
{
    CTest test;
    operator>>(std::cin, test);
    operator<<(std::cout, test);
}


Q: Word 2010 Interop: Show the "Save As" dialog I need a way to always show the save as dialog when the user performs a certain action on a Word document.  Currently, the dialog only shows when an unsaved document is saving.  These documents I am working on have already been saved in one location with a particular name, but users will need to be able to change the name and the location.

A: Figured it out.  Very simple, in case someone else runs into the same issue:
var wordDialog =
Globals.ThisDocument.ThisApplication.Dialogs[Word.WdWordDialog.wdDialogFileSaveAs];
wordDialog.Show();


Q: LiDAR derived streams - map scale Historically, streams were defined by the map scale. For example, for a map with a scale of 1:24,000 would mean that the streams identified on that map would be 1:24,000 streams.
With streams that are identified from LiDAR with a nominal pulse spacing (NPS) of 0.35 meters, resulting in a 1-ft DEM, what would be the equivalent scale of this?
Are there any resources that anyone can share that discusses the comparability? Has anyone tackled this issue?


Q: Why animation can be reusable after change display why animation can be reusable after im changing elemets display property with js
can some one explain i couldnt find any answer for this
can someone explain me this
my codes downbelow
`

    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      aside {
        display: none;
        position: relative;
        left: -100%;
        height: 100vh;
        background-color: red;
        width: 20%;
        animation: openit 800ms ease-in forwards ;
      }
      @keyframes openit {
        to{
            left: 0;
        }
      }
      aside a {
        display: block;
      }
      .open {
        position: absolute;
        z-index: -1;
      }
    </style>

`

A: I found this:
When we want to use transition for display:none to display:block, transition properties do not work. The reason for this is, display:none property is used for removing block and display:block property is used for displaying block. A block cannot be partly displayed. Either it is available or unavailable. That is why the transition property does not work.
form this link. I hope this help.


Q: Android Capturing an image From Camera Returns Empty Data While Capturing image in android app intent return null each time. Please see below the code which I am using. I have tried multiple ways to get the permission as well as intent set but still I am unable to get data.
Action For Camera
 private void takePhotoFromCamera() {

    if(ActivityCompat.checkSelfPermission(ObservationsView.this,
    Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    File file = new File(getExternalCacheDir(),
                String.valueOf(System.currentTimeMillis()) + ".jpg");fileUri = Uri.fromFile(file);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivityForResult(cameraIntent, CAMERA_REQUEST);
    }else {
    String[] permissionRequest = {Manifest.permission.CAMERA};
    requestPermissions(permissionRequest, 8675309);
    checkPermission();
    }
}

And Here is the Response Code
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(resultCode == RESULT_OK ) {
        Uri selectedImg = null;
        Bitmap bmp = null;
        Bundle extras;
        if (requestCode == CAMERA_REQUEST) {
            selectedImg = data.getData();
            extras = data.getExtras();

            bmp = (Bitmap) extras.get("data");

        }

        else if (requestCode == CAMERA_REQUEST) {

            selectedImg = fileUri;

            // Bitmap mphoto = (Bitmap) data.getExtras().get("data");
            try {
                bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), fileUri);
                if (bmp != null) {
                    bmp = getBitmapFromUri(fileUri);
                }
            }catch (IOException e) {
                e.printStackTrace();
            }

            Uri tempUri = getImageUri(getApplicationContext(), bmp);

            Intent passPhoto = new Intent(this, Photo.class);
            passPhoto.putExtra("image",tempUri);

            passPhoto.putExtra("Caller", getIntent().getComponent().getClassName());
            startActivity(passPhoto);

        }

A: Try to use the following code for getting the image in all APIs -
 public void takePicture() {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            file = FileProvider.getUriForFile(mContext,
                    BuildConfig.APPLICATION_ID + ".provider",
                    getOutputMediaFile());
            intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
            startActivityForResult(intent, TAKE_IMAGE_REQUEST);
        }

 private File getOutputMediaFile() {
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), getString(R.string.app_folder_name));

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        return new File(mediaStorageDir.getPath() + File.separator +
                PROFILE_PIC + getString(R.string.pic_type));
    }

And on your onActivityResult -
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_IMAGE_REQUEST:
                if (resultCode == RESULT_OK) {
                    imageView.setImageURI(file);
                }
                break;

            default:
                break;

        }
    }

Also, you need to define the Provider in your Manifest.xml file -
  <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

And finally the provider_paths.xml will be as follows -
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Let me know in case you need any clarification.


Q: Get the data from previous month in sql query I have a data of all the cost for each month. For example,
I have table of cost for each month
+--------+--------+-----+--------+--------+
| Jan    | Feb    | Mar | Apr    | May    |
+--------+--------+-----+--------+--------+
| 899.20 | 0      | 0   | 0      | 899.20 |
| 439.38 | 485.29 | 0   | 0      | 482.29 |
+--------+--------+-----+--------+--------+

Then what I want in the output for every month that is = '0', it will get the data in the previous month and so on until it's not equal = '0'
Is this possible using oracle sql or using xml.
I tried the oracle sql query below, for example is I want the value of April to be = 899.20
I used the case when condition,
case
    when Apr = '0' then Mar
    when Mar = '0' then Feb
    when Feb = '0' then Jan
    else Apr
end

and in XML is the if else condition
<?xdofx:if apr = '0' then mar
        else if mar = '0' then feb
        else if feb = '0' then jan
        else apr
end if?>

But both conditions I know didn't work. Please help
Thank you

A: You can use:
SELECT Jan,
       CASE WHEN Feb > 0 THEN Feb
            ELSE Jan END
         AS Feb,
       CASE WHEN Mar > 0 THEN Mar
            WHEN Feb > 0 THEN Feb
            ELSE Jan END
         AS Mar,
       CASE WHEN Apr > 0 THEN Apr
            WHEN Mar > 0 THEN Mar
            WHEN Feb > 0 THEN Feb
            ELSE Jan END
         AS Apr,
       CASE WHEN May > 0 THEN May
            WHEN Apr > 0 THEN Apr
            WHEN Mar > 0 THEN Mar
            WHEN Feb > 0 THEN Feb
            ELSE Jan END
         AS May
FROM   table_name

Which, for the sample data:
CREATE TABLE table_name ( Jan, Feb, Mar, Apr, May ) AS
SELECT 899.20,   0,    0, 0, 899.20 FROM DUAL UNION ALL
SELECT 439.38, 485.29, 0, 0, 482.29 FROM DUAL;

Outputs:

   JAN |    FEB |    MAR |    APR |    MAY
-----: | -----: | -----: | -----: | -----:
 899.2 |  899.2 |  899.2 |  899.2 |  899.2
439.38 | 485.29 | 485.29 | 485.29 | 482.29

db<>fiddle here


Q: How to mass / bulk PutObjectAcl in Amazon S3? I am looking for a way to update several objects ACL in one (of few request) to the AWS API.
My web application contains several sensitive objects stored in AWS S3. This object have a default ACL to "private". I sometimes need to update several objects ACL to "public-read" for some time (a couple of minutes) before going back to "private".
For a couple of objects, one request per object to PutObjectAcl is ok. But when dealing with several objects (hundreds), the operation requires to much time.
My question is : how can I "mass put object acl" or "bulk put object acl" ? The AWS API doesn't contain a specific answer, like DeleteObjects (which allows to delete several objects at once). But may be I didn't look in the right place ?!
Any tricks or way to work around that would be of great value !

A: Mixing private and public objects inside a bucket is usually a bad idea. If you only need those objects to be public for a couple of minutes, you can create a pre-signed GET URL and set a desired expiration time.


Q: Catch a html tag value with javascript I have a div tag like

Now I wanna save the value of the reference. I tried it with
var reference = document.getElementbyName("reference");

Didnt work. Any ideas?
Thanks :)

A: getElementbyName gets an element by its name.
The reference attribute:

*

*Is not a name attribute

*Is not valid HTML at all

So start by writing valid HTML:

Then get a reference to that element:
const div = document.getElementById('123');

Then get the data from it using the dataset API:
console.log(div.dataset.reference);

Live demo

const div = document.getElementById('123');
console.log(div.dataset.reference);

A: You can use document.querySelectorAll('[reference]') if you have multiple div with same attribute.

var reference = document.querySelectorAll('[reference]');
console.log(reference);

But if you have only one div with reference attribute then use querySelector:

var reference = document.querySelector('[reference]');
console.log(reference);

A: var reference = document.getElementById("123").getAttribute("reference");

A:

var x = document.getElementById("123").getAttribute("reference");
 console.log(x);


Q: Fill drop down list on selection of another drop down list I am using MVC and I am still new with MVC. Can anyone tell me if you can fill a drop down list with data on selection of another drop down list.
I want to use Jquery to avoid postbacks and therefore making the page smoother.

A:

Model:
namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}

Controller:
public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }

        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:
@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

 MVC Cascading Dropdown List Using Jquery

@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })

    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

  }


Q: Macro to copy values only from one sheet to another I've this VBA code
Sheets("log").Range("A125:f1000").Copy _
Sheets("data").Cells(Rows.Count, "A").End(xlUp).Offset(1)

and it copies perfectly from sheet log to data. The only problem I'm facing is that it copies formulas with it as well whereas I only want values. I want to use same VBA code with some modifications to paste values only.

A: Need to add PasteSpecial Paste:=xlPasteValues
Next time try Recording a macro and modifying the code
Sheets("log").Range("A125:f1000").Copy
Sheets("data").Cells(Rows.Count, "A").End(xlUp).Offset(1). _
PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False

A: Without using clipboard:
Sheets("data").Cells(Rows.Count, "A").End(xlUp).Offset(1).Value = Sheets("log").Range("A125:f1000").Value


Q: Testing chef data bags I need to test chef recipe. This is using a data bag.
kitchen is using chef_zero in order to provision the machine. So, it's not able to get my data bag hosted on server. Then it's telling me that my data bag is not available.
How could I get a data bag available on test kitchen?
I've created a aws.json file on test\integration\data_bags:
{
  "id": "dev",
  "aws_access_key_id": "----",
  "aws_secret_access_key": "----"
}

When I perform my converge I'm getting this message:

INFO: HTTP Request Returned 404 Not Found: Object not found: chefzero://localhost:8889/data/aws/dev
ERROR: Failed to load data bag item: "aws" "dev"

.kitchen.yml file content:
---
driver:
  name: vagrant

provisioner:
  name: chef_zero
  always_update_cookbooks: true

verifier:
  name: inspec

platforms:
  - name: ubuntu-16.04
  - name: centos-7.2

suites:
  - name: default
    data_bags_path: "test/integration/data_bags"
    run_list:
      - recipe[living-development::default]
    verifier:
      inspec_tests:
        - test/smoke/default
    attributes:

Versions:
$ vagrant -v
1.9.2

$ chef -v
Chef Development Kit Version: 1.2.22
chef-client version: 12.18.31
delivery version: master (0b746cafed65a9ea1a79de3cc546e7922de9187c)
berks version: 2017-03-08T11:19:04.643719 5824] 2017-03-08T11:19:04.643719 5824] 2017-03-08T11:19:04.643719 5824] 2017-03-08T11:19:04.643719 5824] 2017-03-08T11:19:04.700789 5824] 2017-03-08T11:19:04.700789 5824] 5.6.0
kitchen version: 1.15.0

A: The server error indicates that is searching something called aws/dev (where aws is the data bag's name and dev is the name of the item within that data bag).
So you would have to place your JSON file under test/integration/data_bags/aws/dev.json.
Btw. you don't have to manually specify the data_bags_path, as test-kitchen will search for items at exactly this path.


Q: Having Problems Dynamically Displaying a Nested List Using Core Data Hereafter is the Problem I'm Dealing with:

*

*I am permanently storing information using iOS Core Data

*I would like to (dynamically) display the information stored in core data in a UITableView (as later described)

*I am considering the use of Core Data´s Fetched Results Controller (FRC) and the FRC Delegate in order to more efficiently handle the bridge between the permanently stored data and updates in the UI

*

*I have a Person entity with name as an attribute.

*I have two "to-many" relationships pointing from a Person to an
Employment Entity and two "to-one" inverse relationships pointing back, such that any person can have any number (0 to ∞) of employer(s) and any number of employee(s), simultaneously:
employee <—>> employmentTaken
employer <—>> employmentGiven

*

*Every Employment has a rank (Int) attribute used to display a Person´s employer(s) - if any - to the user in an order defined by the relative income generated by each Employment of that Person (each income level being subject to  changes at any time).

*For the program to keep track of persons shown in the UITableView, each Employment also comes with a show (boolean) attribute where true = show on the table and false = don't show on the table.

I would like to list Persons in a UITableView, such that when the user presses on a a Person as many rows are introduced in the UITableView under the Person´s name as is needed to display the Person´s Employer(s),  and so recursively (since any Person may both be an Employer and an Employee), the final view being a nested list.
Example as Follows:

Initial UI State:
Name of Person 1
Name of Person 2
Name of Person 3

...

UI State After the User Presses on Person 2, assuming that Person 2 simultaneously works for Person 4, 5, and 6:
Name of Person 1
Name of Person 2
________Name of Person 4 *   // 1st Source of Income by Size of Person 2*
________Name of Person 5 *   // 2nd Source of Income by Size of Person 2*
________Name of Person 6 *   // 3rd Source of Income by Size of Person 2*
Name of Person 3

I am currently using NSFetchedResultsController, fetching all employments which have show = true and trying to sort them using two keys:
let rank = NSSortDescriptor(key: #keyPath(Employment.rank), ascending: true)
let employee = NSSortDescriptor(key: #keyPath(Employment.employee), ascending: true)
(Displaying the Name of the Person in the cell, I use the dot notation: employment.employer?.name)
Using those keys the order is not the desired and I'm trying to figure out if I can get the right sorting using sortDescriptor and the FRC.
Should I use the FRC at all or instead just create an array of arrays and write some extra code to take care of updating the UI myself?
(I am still somewhat fresh to coding and any help would be tremendously appreciated!)


Q: How to crop a selected picture in Outlook mail body with VBA I need VBA Code for crop picture in outlook mail body
Does anyone have code please share with me

A: After a 5 minute search on Google I found the following link https://www.experts-exchange.com/questions/27768384/Outlook-macro-to-resize-picture-s.html
to summarise though this should help you (untested):
This macro will resize all pictures, including those in your signature (if any), in the currently open message to 75% of their height and width.
Follow these instructions to add the code to Outlook.

*

*Start Outlook

*Press ALT+F11 to open the Visual Basic Editor

*If not already expanded, expand Microsoft Office Outlook Objects

*If not already expanded, expand Modules

*Select an existing module (e.g. Module1) by double-clicking on it or create a new module by right-clicking Modules and selecting Insert > Module.

*Copy the code from the code snippet box and paste it into the right-hand pane of Outlook's VB Editor window

*Click the diskette icon on the toolbar to save the changes

*Close the VB Editor

Here's how to add a button to the QAT for running the macro with a single click.
Outlook 2010.  http://www.howto-outlook.com/howto/macrobutton.htm#qat
Sub ResizeAllPicsTo75Pct()
    Const wdInlineShapePicture = 3
    Dim olkMsg As Outlook.MailItem, wrdDoc As Object, wrdShp As Object
    Set olkMsg = Application.ActiveInspector.CurrentItem
    Set wrdDoc = olkMsg.GetInspector.WordEditor
    For Each wrdShp In wrdDoc.InlineShapes
        If wrdShp.Type = wdInlineShapePicture Then
            wrdShp.ScaleHeight = 75
            wrdShp.ScaleWidth = 75
        End If
    Next
    Set olkMsg = Nothing
    Set wrdDoc = Nothing
    Set wrdShp = Nothing
End Sub


Q: setting up XmlConfigurator Common Logging with log4net I have been looking at creating a common logging library for the company I work for, based on a blog by Daniel Cazzulino. so we can switch one out for another without to much disruption.
The first library I looked to use is log4net, but I cannot work out how or where you would setup a call to the XmlConfigurator.
I have tried adding an assembly on the project being logged, which kind of defeats the object of the exercise I feel, but that doesn't appear to work any way.
I have tried adding it as an assembly of the log4net Logging library, but that doesn't appear to work.
I have also tried calling log4net.Config.XmlConfigurator.Configure(); from the TraceManager.Get method, but all the log options (IsDebugEnabled, IsWarnEnabled, ...) are  disabled.
public partial class TracerManager : ITracerManager
{
    /// <summary>
    /// Gets a tracer instance with the specified name.
    /// </summary>
    public ITracer Get(string name)
    {
        log4net.Config.XmlConfigurator.Configure();
        var logger = LogManager.GetLogger(name);
        return new Log4NetAdapter(logger);
    }
    /// The rest
}

Do I need to do something else?
Does the app config need to be in in the logging library?
[Edit 1]
Feel very silly....
I'd added [assembly: XmlConfigurator(Watch = true)] to my Logging.Log4Net library, but I wasnt instantiating the TracerManager in my application on the tests I was performing... ID-10Tango issue

A: I'd added [assembly: XmlConfigurator(Watch = true)] to my Logging.Log4Net library, but I wasnt instantiating the TracerManager in my application on the tests I was performing...
ID-10Tango issue


Q: mySQLdb import error I am following this guide: How do I connect to a MySQL Database in Python?
running jupyter notebook.
I am running windws 10 operating system and I have installed MySQLdb from this link https://sourceforge.net/projects/mysql-python/files/ "MySQL for python"
I have MySQL Workbench installed.
When running I get an error
ImportErrorTraceback (most recent call last)
<ipython-input-5-a07af86e2020> in <module>()
---> 12 import MySQLdb

ImportError: No module named MySQLdb

I am not sure what I am doing wrong.
I tried things such as
pip install mysqlclient
pip install mysql-python

Running mysqlclient gives me following:
Collecting mysqlclient
  Using cached mysqlclient-1.3.10.tar.gz
    Complete output from command python setup.py egg_info:
    sh: 1: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-TH5iAY/mysqlclient/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 44, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 26, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found

Running mysql-python gives me following:
Collecting mysql-python
  Using cached MySQL-python-1.2.5.zip
    Complete output from command python setup.py egg_info:
    sh: 1: mysql_config: not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-anTaSr/mysql-python/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "setup_posix.py", line 25, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found

When looking up the error on stack, it tells me to install MySQLdb, but I have that installed already.


Q: How to compare two columns in separate spreadsheets and if the columns match, output related data in from one spreadsheet to the other Had a search and sadly couldn't find a related question
Im trying to compare two columns in separate spreadsheets and if the columns match, output related data in from one spreadsheet to the other. In the Screenshot below, I am trying to compare the two "required functionality description" fields which are in separate spreadsheets. Then If the two fields match, output the Importance field from one to the other.

I really appreciate any help/guidance on this! Thanks!

A: Try:
=IFERROR(VLOOKUP(G6,[SO31165136a.xlsx]Sheet1!$G:$H,2,0),"")

adjusted for your sheet and workbook names.


Q: AWS S3 - How to stop images from force downloading instead of displaying. I am currently trying to load images from my website to AWS S3. I have the functionality working where it uploads the image to the server but when i try to view the images they download instead of displaying. I read there is a way to set the file type so this would not happen. I am not sure how to do that. Any help would be great.
                router.post('/heroes/createNewHeroes', function(req,res) {
                    var formidable = require('formidable'),
                    http = require('http'),
                    util = require('util');

                    var form = new formidable.IncomingForm();

                    form.parse(req, function(err, fields, files) {
                        console.log(fields);
                        console.log(files);

                        // Load the AWS SDK for Node.js
                        var AWS = require('aws-sdk');
                        var shortid = require('shortid');
                        var fs = require('fs');
                        var fileStream = fs.createReadStream(files.asset.path);
                        var newFilename = shortid.generate()+"_"+files.asset.name;

                        // Set your region for future requests.
                        AWS.config.region = 'us-west-2';
                        AWS.config.accessKeyId = 'access Key';
                        AWS.config.secretAccessKey = 'secret Key';

                        console.log(newFilename);

                        fileStream.on('error', function (err) {
                          if (err) { throw err; }
                        });

                        fileStream.on('open', function () {
                            var s3bucket = new AWS.S3({params: {Bucket: ' '}});
                            s3bucket.createBucket(function() {
                              var params = {Key: newFilename, Body: fileStream};
                              s3bucket.upload(params, function(err, data) {
                                if (err) {
                                    console.log("Error uploading data: ", err);
                                } else {
                                    console.log("Successfully uploaded data");

                                    projectX.createHeroes(['plantTypes', 'asset', 'cost', 'energy', 'isSunProducer', 'isShooter', 'isExploding', 'sunFrequency', 'shootingFrequency', 'damage'], [fields.plantTypes, newFilename, fields.cost, fields.energy, fields.isSunProducer, fields.isShooter, fields.isExploding, fields.sunFrequency, fields.shootingFrequency, fields.damage], function(data){
                                        res.redirect('/heroes')
                                    });
                                }
                              });
                            });

                        });

                    });
                });

A: var params = {Key: newFilename, ContentType: 'image/png', Body: fileStream};

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property

A: Just put "contentType: multerS3.AUTO_CONTENT_TYPE " . It will work .
Ex:
var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'some-bucket',
    contentType: multerS3.AUTO_CONTENT_TYPE,
    key: function (req, file, cb) {
      cb(null, Date.now().toString())
    }
  })
})

Visit this link for more details https://github.com/badunk/multer-s3

A: This Helped me
storage: multerS3({
s3: s3,
bucket: "bucketname",
acl: "public-read",
contentType: multerS3.AUTO_CONTENT_TYPE,
key: function(req, file, cb) {
  console.log("req.file", file);
  cb(null, `${Date.now()}-${file.originalname}`);
}
})


Q: WPF - When TextBox inside DateTemplate is focused change datatemplate child property I have a listview with a Border wrapping a textbox (and other elements not shown in sample code). I want when the textbox is keyboard focused to change a property of the border that wraps it.
<ListView ItemsSource="{Binding activeLists}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Border x:Name="border">
                    <TextBox Text="something">
                        <TextBox.Style>
                            <Style>
                                <Style.Triggers>
                                    <Trigger Property="TextBox.IsFocused" Value="True">
                                        <Setter TargetName="border" Property="TextBox.Background" Value="Red"></Setter>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </TextBox.Style>
                    </TextBox>
                </Border>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

If using inside the trigger TargetName="border" the item is not found.
If possible to do this from XAML only.

A: When I tried running this, I also got the error "TargetName property cannot be set on a Style Setter". Which indicates that you can't set a property of the Border control inside a style setter for the TextBox control (which doesn't honestly surprise me.)
What you can do instead is set it in the style of the border control itself, using a DataTrigger to bind to the IsFocused property of the textbox:
<Border>
    <Border.Style>
        <Style TargetType="Border">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=IsFocused, ElementName=textBox}" Value="true">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
    <TextBox Name="textBox" Text="something"/>
</Border>


Q: Hibernate str() function using Criteria API How can I use HQL str() function which is using for converting numeric value to readable string with Criteria API?

A: I think, you won't need str() function with Criteria API, since you can first convert numerics into Strings with API functions like: Integer.toString() then set as Parameter like;
List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("age", Integer.toString(age) ) )
    .list();


Q: Is the sum of a uniformly convergent series and a non-uniformly convergent series, uniformly convergent? Consider the series sigma (from k=1 to infinity) (-1)^k.(x+k/k^2) for x within [0,1].
I deduce that the series (-1)^k.(x/k^2) is uniformly convergent from using the M-test for convergence, and I assume that the series (-1)^k.(1/k) is not uniformly convergent because it has no x term so isn't a series of functions satisfying the definition of uniform convergence of series. (I know that it is conditionally convergent, however.)
Thus is the original series uniformly convergent?

A: Hint. One has
$$
\sup_{x \in [0,1]}\left|(-1)^k\frac{x+k}{k^2} \right|=\frac1{k^2}+\frac1k\qquad (k\ge1)
$$ thus the given series does not converge uniformly over $[0,1]$.


Q: Get the row values as column in SQL I have below table,and need to get row values as an output.
This is a part of a view in Oracle Database.

I need to get the output using SQL as below.name,address,regionare taking from another table by referringID .

Looking for much simple way since full query have more than 15 columns and below also need to be added as columns.
Thanks.

A:
"Looking for much simple way since full query have more than 15 columns"

Sorry, you can have a complex query or no query at all :)
The problem is the structure of the posted table mandates a complex query. That's because it uses a so-called "generic data model", which is actually a data anti-model. The time saved in not modelling the requirement and just smashing values into the table is time you will have to spend writing horrible queries to get those values out again.
I assume you need to drive off the other table you referred to, and the posted table contains attributes supplementary to the core record.
select ano.id
       , ano.name
       , ano.address
       , ano.region
       , t1.value as alt_id
       , t2.value as birth_date
       , t3.value as contact_no
from another_table ano
     left outer join ( select id, value
                       from generic_table
                       where key = 'alt_id' ) t1
          on ano.id = t1.id
     left outer join ( select id, value
                       from generic_table
                       where key = 'birth_date' ) t2
          on ano.id = t2.id
     left outer join ( select id, value
                       from generic_table
                       where key = 'contact_no' ) t3
          on ano.id = t3.id

Note the need to use outer joins: one of the problems with generic data models is the enforcement of integrity constraints. Weak data typing can also be an issue (say if you wanted to convert the birth_date string into an actual date).

A: PIVOT concept fits well for these types of problems :
SQL> create table person_info(id int, key varchar2(25), value varchar2(25));
SQL> create table person_info2(id int, name varchar2(25), address varchar2(125), region varchar2(25));
SQL> insert into person_info values(4150521,'contact_no',772289317);
SQL> insert into person_info values(4150522,'alt_id','98745612V');
SQL> insert into person_info values(4150522,'birth_date',date '1990-04-21');
SQL> insert into person_info values(4150522,'contact_no',777894561);

SQL> insert into person_info2 values(4150521,'ABC','AAAAAA','ASD');
SQL> insert into person_info2 values(4150522,'XYZ','BBBBB','WER');

SQL> select p1.id, name, address, region, alt_id, birth_date, contact_no
  from person_info
 pivot
(
 max(value) for key in ('alt_id' as alt_id,'birth_date' as birth_date,'contact_no' as contact_no)
) p1 join person_info2 p2 on (p1.id = p2.id);

ID      NAME    ADDRESS REGION  ALT_ID      BIRTH_DATE  CONTACT_NO
------- ------- ------- ------  ---------   ----------  ----------
4150521 ABC     AAAAAA  ASD     12345678V   21-APR-89   772289317
4150522 XYZ     BBBBB   WER     98745612V   21-APR-90   777894561


Q: Creating Custom IconFactory in Gtkmm I have a small application, where I want to create some buttons, toolbars, etc. but I do not want to use a pre-existing GTK icon theme, I want to create my own. So I looked for tutorials and whatnot, but as it turned out, it was not very well discussed online. So I tried to do something on my own:
Header File:
#include <gtkmm.h>
#include <string>
#include <iostream>
#include <errno.h>

class IconFactoryBuilder
{
public:
    IconFactoryBuilder();

    ~IconFactoryBuilder();

    void RegisterNewIcons(std::string pPath);

private:

    Glib::RefPtr<Gtk::IconFactory> mCustomFactory;
};

Cpp File:
#include <IconFactoryBuilder.h>

IconFactoryBuilder::IconFactoryBuilder() {
    mCustomFactory = Gtk::IconFactory::create();
}

IconFactoryBuilder::~IconFactoryBuilder() {
}

void IconFactoryBuilder::RegisterNewIcons(std::string pPath) {

    Glib::RefPtr<Gtk::IconSet> iconSet = Gtk::IconSet::create();
    Gtk::IconSource someSource;
    try{
        Gtk::Image  *someImage=Gtk::manage(new Gtk::Image(pPath+"appbar.at.png"));
        someImage->set_pixel_size(Gtk::IconSize(48));
        someSource.set_pixbuf(someImage->get_pixbuf());
        someSource.set_size(Gtk::ICON_SIZE_DIALOG);
        someSource.set_size_wildcarded();
    }
    catch(const Glib::Exception &ex) {
        std::cerr << "An error occurred while opening the icon file!" << strerror(errno) << std::endl;
    }
    catch(...) {
        std::cerr << "Unknown Error!" << std::endl;
    }
    iconSet->add_source(someSource);
    const Gtk::StockID somestock("MyNewIcon");
    Gtk::Stock::add(Gtk::StockItem(somestock, "somelabel"));
    mCustomFactory->add(somestock, iconSet);
    mCustomFactory->add_default();
}

But now I am quite stuck, because I do not really know how to call this new icon I have created. I also do not know if the above written code is enough to actually find the icon or not.

A: You created an icon factory... factory?
;-)
The serious answer to your question is that you don't need Gtk::IconFactory. Unfortunately the GTK 2 documentation doesn't tell you that it's unnecessary. What you do need is the freedesktop.org Standard Icon Naming Specification. Create your icons, give them simple names, organize according to the directory structure described there, install it to the appropriate place, and your icons will "just work" when you create a Pixbuf or Image using the ...from_icon_name() functions. (example: Gtk::Image::set_from_icon_name())
Here is a page from the Gnome developer wiki on how to provide your own icons:
http://developer.gnome.org/integration-guide/stable/icons.html.en
And here is a page from a tutorial I wrote about installing custom icons: http://ptomato.name/advanced-gtk-techniques/html/desktop-file.html


Q: Options to securely authenticate mobile access using OAuth2 We're currently in the process of implementing OAuth2 to secure our new API and not sure how to securely provide required functionality. We need to allow the following from a mobile device:

Immediately after downloading the app the user is able to take a picture and submit it without having to first log in.

While we want to allow anonymous user access, where a user does not need to log in or register to use certain functionality, we do not want to allow unauthenticated access to the API. This would normally be accomplished using the client credentials authorization flow to obtain and app access token, however this requires knowing the client secret. From what I've read, a mobile device is not considered a trusted client and should not contain the client secret, and hence should not be able to generate an app access token on its own.
We've come up with a few options to accomplish this requirement, but would like some input on them:

*

*Embed the client secret in the app. Doesn't seem ideal from a security standpoint, but maybe we're missing an obvious way to secure it? We're targeting at least iOS and Android.

*Generate an app access token offline and embed that in the app. Still not very secure, but at least the secret isn't exposed.

*Allow access to certain functionality using only the client ID instead of an access token. This may be the simplest, but it introduces an inconsistency and requires multiple ways of authenticating the client.

*Build and use a companion web app to generate app access tokens for the mobile app. On the surface seems like a winner, but now you have to secure access to the companion app!

How would you securely authenticate access to an API using OAuth2 from a mobile device without requiring the user to first log in?

A: Agree with the comments on the Q.  Either:
1.) Use Client Credentials grant type in OAuth 2 - with an embedded secret in your App.  Understand that this isn't super secure and someone will reverse engineer it eventually.  Ideally each client would get a unique secret - so you could revoke a client if they're abusing its use.
2.) Live with that API being open - thereby not requiring an OAuth 2 access token at all.  Maybe that API would be known only to your app - but again, it would only be a matter of time before someone reverse engineers it.

A: My group is having a similar discussion. Users can get the app and browse a catalog without having to sign-in.  The catalog and other data is accessed via an API and we would like to force users to have an access_token for all calls.
Our current thinking is to

*

*Always force the App to exchange a common clientId/secret for an access_token. So the app would get an access_token even for anonymous users.  This would be via the client_credentials oAuth flow.

*If the user signs in, use the oAuth password flow.  They would pass in clientId, secret, username, and password.  We would additionally allow them to pass in their anonymous token so that we could transfer any history from their anonymous session.

So for example...
access_token = api.oAuth.client_credentials(clientId, secret)
catalog = api.getCatalog(access_token)
authenticated_access_token = api.oAuth.password(clientId, secret, username, password, access_token)


Q: How to hide/unhide desktop icons in Python? Is it possible to hide/unhide icons on your desktop with Python? I know a way of doing it by editing registry but changes take place after you log off and log back on. If you have any suggestion, I'd appreciate your help.


Q: How do DNS servers respond to missing glue records? I am currently doing some benchmarking on the DNS service at my place of work. One of the bigger anomalies this is throwing up is a significant number of domains where, in some cases the lookup is returning a NXDOMAIN response while in others I am getting a valid response to an MX lookup.
(The domains in question are external)
While its possible that this may be due to a difference in config between a pair of authoritative servers, I realized I don't know which response to expect when I try to resolve a domain with no glue records. (links to authoritative sources would be appreciated).

A: Strictly speaking, glue is only necessary in one scenario: nameservers falling within a zone cut defined by the same zone. RFC 1034 §4.2.1 makes this explicit, emphasis mine:

One of the goals of the zone structure is that any zone have all the
data required to set up communications with the name servers for any
subzones.  That is, parent zones have all the information needed to
access servers for their children zones.  The NS RRs that name the
servers for subzones are often not enough for this task since they
name the servers, but do not give their addresses.  In particular, if
the name of the name server is itself in the subzone, we could be
faced with the situation where the NS RRs tell us that in order to
learn a name server's address, we should contact the server using the
address we wish to learn.  To fix this problem, a zone contains "glue"
RRs which are not part of the authoritative data, and are address RRs
for the servers. These RRs are only necessary if the name server's
name is "below" the cut, and are only used as part of a referral
response.

The idea that glue is "required" at the registry/registrar level is a widespread fallacy, mostly emerging from the the days when there were a scant few gGTLDs to choose from. As the number of TLDs to choose from has steadily increased over the years, it's becoming increasingly more common to encounter glueless TLD referrals. Take goo.gl for example:
$ dig @d.nic.gl +noall +authority +additional goo.gl
goo.gl.                 86400   IN      NS      ns4.google.com.
goo.gl.                 86400   IN      NS      ns3.google.com.
goo.gl.                 86400   IN      NS      ns1.google.com.
goo.gl.                 86400   IN      NS      ns2.google.com.

Note the conspicuous lack of ADDITIONAL data here. gl does not not need to provide glue for anything inside of com. When this scenario is encountered, it becomes necessary to recurse through the com TLD in order to obtain the IP address of one of those nameservers. Any glue encountered along the way will be followed as normal. I won't quote RFC 1034 §4.3.2 here as it's somewhat silly to restate basic operation fundamentals.
In short, glue is only mandatory where both the standards or the policy of specific registrars (or registries) require it. The latter requiring it is not necessarily an indication of the former. In cases where a glueless delegation from the TLDs is encountered, it's simply business as usual.
If glue were to be missing in a scenario where it is required (your actual question I suspect), and no other nameservers were available to provide the authoritative response, that would be a clear case of SERVFAIL. NXDOMAIN would imply that an authoritative server could be reached, which is not the case here. The server which defines the zone cut is not authoritative for data beneath the cut (RFC 2181 §6.1), and an inability to reach the authoritative servers means that you've arrived at a dead end.


Q: Golang: what's the point of interfaces when you have multiple inheritence I'm a Java programmer, learning to program in Go. So far I really like the language. A LOT more than Java.
But there's one thing I'm a bit confused about. Java has interfaces because classes can inherit only from one class. Since Go allows multiple inheritance, what's the point of interfaces?

A: Interfaces in Go are very different from interfaces in Java.
In Java a class has to formally agree to implement an interface:
public class Foo implements iFoo

In Go a user type implements an interface by simply doing so.
A function or property can then define what is expected:
func DoSomething(r io.Reader) {
    buf := make([]byte, 128)
    n, err := r.Read(buf)
    ...
}

The DoSomething function can be passed anything that implements the Read function found in the io.Reader interface, without the thing knowing or caring about the interface. It is the responsibility of the caller to make sure it is passing in something that implements the interface. This is checked at compile time.
We can take this a step further. We can define our own interface:
type MyInterface interface {
    io.Reader // Include Reader interface
    Seek(int) error // Include my own function
}
func DoSomething(r MyInterface) {
    buf := make([]byte, 128)
    n, err := r.Read(buf)
    ...
}

Go is also different in that it doesn't have a class or object type. Any user declared type, whether it be based on an integer, string, struct, array, slice, channel,  etc. can have methods attached to it.
Go also doesn't have typical class-like inheritance you're normally used to, but it does have a couple of things that are pretty close.
Redeclared type:
type Num int

func (n Num) Print() {
    print(n)
}

type Number Num

func (n Number) Print() {
    Num(n).Print()
}

Anonymous fields:
type Foo struct {
    sync.Mutex
}

func main() {
    f := Foo{}
    f.Lock()
    // ...
    f.Unlock()
}

A: Polymorphism
Interfaces enable functions to have a 'placeholder' parameter which can take different structs as an argument. For example, if structs Man, Woman, Child implement interface Human, then a method with the parameter Human can take any of the structs Man, Woman, Child as an argument. Hence, the interface parameter can 'morph' into any struct passed as an argument as long as it implements all functions defined in the interface.
This is important because interfaces are the only way of achieving Polymorphism in Go, since it doesn't have inheritance. So if Man 'extended' Human (by having it as an anonymous field), any method that used Human as an argument, would not be able to take Man as an argument.
My confusion stemmed from the fact that inheritance is also a way of achieving Polymorphism in Java, and I assumed that was the case here as well. I stand corrected!

A: If supertype X is an interface, whoever is maintaining the code knows at once that it has no method implementations.  If supertype Y is an abstract class, whoever is maintaining the code has to check whether there are method implementations.  So it's a documentation/maintenance/readability thing.

A: Classes can inherit and implement from multiple class files.
Unless I misinterpreted:
public class MyClass extends MySuperClass implements MyInterface, MySecondInterface

The point of interfaces is to allow for a completely abstract class. So abstract that there isn't a single method defined.
I would use an interface when I need to create several abstract classes with the same basic structure. I would then be able to create instances of classes which extend the abstract class, which in turn would implement the interface.
This is done with the interface java.util.Collection and some classes like java.util.ArrayList and java.util.Stack implement that interface. This way you can store all kinds of lists' items in a Collection. This is why ArrayList has a method to addAll(Collection<? extends E> c).
You could say it is like being backwards compatible with simpler objects.


Q: Is it possible to prevent JSX comment from adding a 'children' element, potentially breaking types? Let's say I have a third party library like this:
declare var SomeComponentFromLibrary: React.FC<{
    children?: React.ReactElement
}>;

Where children is defined to be a React.ReactElement, and I can't change that fact.
Now, let's say I use it, with a component <MyComponent /> that happens to generate a type error, and I wish to suppress the error for the timebeing:
<SomeComponentFromLibrary>
    {/* @ts-expect-error */}
    <MyComponent />
</SomeComponentFromLibrary>

This creates 2 items in SomeComponentFromLibrary's children, (the comment {} and <MyComponent), while SomeComponentFromLibrary's type definition expects only one child, yielding this:
Type '{ children: any[]; }' is not assignable to type '{ children?: ReactElement.... }'.

Is it possible at all to use typescript @ts- comments (well, or any other comments) in ~~JSX without creating actual children?~~
EDIT:
Looks like when I add the comment, it doesn't change the resulting JavaScript ((React.createElement(SomeComponentFromLibrary, null, React.createElement(MyComponent, null)))) -- But for some reason, TypeScript still complains (things that children is any[]). I think this could be a bug in TS -- maybe it parses JSX differently?

A: Typescript comment directives are not very JSX friendly, sadly. But you can definitely make it work.
Give it one child, in braces, { }, with the comment in those braces.
<SomeComponentFromLibrary>
    {/* @ts-expect-error */
        <MyComponent />
    }
</SomeComponentFromLibrary>

Playground

Also, side note: The typings of SomeComponentFromLibrary are probably just wrong. In nearly all cases I've ever seen, children should be typed as React.ReactNode. And when you type this function as such, it now works exactly like you expect.
So I'd probably create a pull request for whatever this library is to fix that.

A: Looks like this is a bug: https://github.com/microsoft/TypeScript/issues/41125
It's fixed here: https://github.com/microsoft/TypeScript/pull/41166 and should be released either in 4.1 or 4.2


Q: PhpStorm make grouping like Xcode Can I make a grouping my php pages like Xcode group in PhpStorm ? Is there any suggestion ?

There are two types of folders in Xcode: groups and folder references.
  You can use groups to organize files in your project without affecting
  their structure on the actual file system. This is great for code,
  because you’re only going to be working with your code in Xcode.

referance


Q: Check Box makes Label Visible I have three Combo Boxes - When they are selected i would like it to check the tick box.
if the check box is ticked the Text box will then become Enabled, i currently have it set as disabled.
my question is how would i set the check box to be true when the three Combos are selected.
and how would i make it so that when the tick box is true it will enable the tex box

A: When all 3 combo boxes are set it will enable the checkbox. Once the value for any combo box is updated it calls a common function which checks whether all combo boxes have a value assigned and accordingly set the checkbox.
Private Sub cmbClientContact_AfterUpdate()
   Call SetCheckBox
End Sub

Private Sub cmbClientName_AfterUpdate()
    Call SetCheckBox
End Sub

Private Sub cmbProjectManager_AfterUpdate()
    Call SetCheckBox
End Sub

Private Sub SetCheckBox()
     If Nz(Me.cmbClientContact, "") <> "" And Nz(Me.cmbClientName, "") <> "" And Nz(Me.cmbProjectManager, "") <> "" Then
        Me.Check25 = True
        Me.Text27.Enabled = True
     Else
        Me.Check25 = False
     End If
End Sub

Enable/disable textbox basis value of the checkbox
Private Sub Check25_AfterUpdate()
    If Nz(Me.Check25, False) Then
        Me.Text27.Enabled = True
    Else
        Me.Text27.Enabled = False
    End If
End Sub

A: I would reccomend using the AfterUpdate event of all 3 combo boxes. Since the code is going to be the same (you're checking if all 3 combo boxes have a value), you can create one function to handle the check, and set that function to the AfterUpdate event of all 3 combo boxes when the form loads.
The function to update the controls (both the text box and check box) would be something like this:
  Private Function UpdateControls()
     Me.Text1.Enabled = Not (IsNull(Me.Combo1) Or IsNull(Me.Combo2) Or IsNull(Me.Combo3))
     Me.Check1.Value = Not (IsNull(Me.Combo1) Or IsNull(Me.Combo2) Or IsNull(Me.Combo3))
  End Function

You can call this function when the form initially loads, so the checkbox will be unchecked and the textbox will be disabled:
  Private Sub Form_Load()
     ' update controls initially when the form loads
     UpdateControls
  End Sub

To make sure the same update happens whenever one of the combo box's values are updated, you can set each combobox's AfterUpdate event to the same function, like this:
  Private Sub Form_Load()
     ' set each combo box's AfterUpdate event to run the check
     Me.Combo1.AfterUpdate = "=UpdateControls()"
     Me.Combo2.AfterUpdate = "=UpdateControls()"
     Me.Combo3.AfterUpdate = "=UpdateControls()"
  End Sub

So your final code might be something like this:
  Private Sub Form_Load()
     ' set each combo box's AfterUpdate event to run the check
     Me.Combo1.AfterUpdate = "=UpdateControls()"
     Me.Combo2.AfterUpdate = "=UpdateControls()"
     Me.Combo3.AfterUpdate = "=UpdateControls()"

     ' update controls initially when the form loads
     UpdateControls
  End Sub

  Private Function UpdateControls()
     Me.Text1.Enabled = Not (IsNull(Me.Combo1) Or IsNull(Me.Combo2) Or IsNull(Me.Combo3))
     Me.Check1.Value = Not (IsNull(Me.Combo1) Or IsNull(Me.Combo2) Or IsNull(Me.Combo3))
  End Function

A: Without knowing more specifics about the name schemas of your objects, this is my semi-vague answer:
One option (of many) is to use an On Click event procedure with the following:
If Not IsNull(Me.Combo1) _
And Not IsNull(Me.Combo2) _
And Not IsNull(Me.Combo3) Then
    Me.Check1 = True
    Me.Text1.Enabled = True
Else
    Me.Check1 = False
    Me.Text1.Enabled = False
End If

This assumes that the checkbox is named Check1 and the textbox is named Text1 and the comboboxes are Combo1, Combo2, and Combo3
It is a little confusing whether you meant Enabled or Visible, but if you meant Visible, just change the lines that say .Enabled to .Visible


Q: put random image on uibutton I'm new to Objetive-C and need some help,
I have an Array with 22 UIImage's and 4 UIButtons on the view.
I want to take an image from the array with ObjectAtIndex:somecounter and place this image randomly in one of the 4 UIButton's, than I want to take another 3 UIImages from the Array (random images) and locate them randomly in the other 3 UIButtons that I have left.
so in each time that the counter is in a number, take the UIImage that stored in this index, locate it randomly in one of the UIButtons, than take other 3 random UIImages from the Array and locate them randomly on the 3 UIButton that I have left.
how can I do that?
after using basvk answer came up with this:

-(void)PlaceWordAndPictueOnScreen
{
    NSArray *buttons = [NSArray arrayWithObjects:btnLetter1, btnLetter2, btnLetter3, btnLetter4, nil];
    for (UIButton *btn in buttons) {
        int randomIndex= random() % [LettersArray count];
        UIImage *img = [LettersArray objectAtIndex:randomIndex];
        [btn setImage:img forState:UIControlStateNormal];
        [LettersArray removeObjectAtIndex:randomIndex];
    }
}

so I did exactly as he said and it worked like charm, but, I do have a problem.
I have this counter called 'imgcounter', lets say he's value is '4', I want to take the image that located at index 4 and put it in one of the 'btnLetter' UIButton, but in a random button, than in the other 3 'btnLetter' buttons that left, to put another 3 random UIImage's, how can I do that?
Thanks..

A: Out the top of my head, something like this:
  -(void)placeImages {
        NSMutableArray *images = [NSMutableArray arrayWithObjects:@"image1.png", @"image2.png", @"image3.png", @"image4.png", @"image5.png", @"image6.png", @"image7.png", @"image8.png", nil]; // etc...
        NSArray *buttons = [NSArray arrayWithObjects:btn1, btn2, btn3, btn4, nil];
        for (UIButton *btn in buttons) {
              int randomIndex= random() % images.length;
              UIImage *img = [images objectAtIndex:randomIndex];
              [btn setImage:img forState:UIControlStateNormal];
              [images removeObjectAtIndex:randomIndex];
        }

A: -(void)randomizeArray:(NSMutableArray *)array
{
    int i, n = [array count];
    for(i = 0; i < n; i++) {
        int destinationIndex = random() % (n - i) + i;
        [array exchangeObjectAtIndex:i withObjectAtIndex:destinationIndex];
    }
}

this is a answer for your question

A: btnLetter1, btnLetter2, btnLetter3, btnLetter4 = UIButtons that should present an image.
LatterArray = the array that containes all of the images.
imgcounter = the current counter index
if the 'imgcounter' is on '2' so one of the 'btnLetters' buttons (random one between 1-4) should containe an image from 'LettersArray' that located in index number '2' equal to the 'imgcounter'. all the other remining 3 'btnLetter' should containe a random image from 'LettersArray'.
when the function called again the 'imgcounter' will be '3', now one of the 'btnLetters' (random one) should containe another image from 'LettersArray that is located at index number '3', again, equal to the 'imgcounter'. the other remining 3 'btnLetter' should containe again randome image from 'Letters Array' and so on..
-(void)PlaceWordAndPictueOnScreen2
{
    NSMutableArray * ButtonArray = [[NSMutableArray alloc] initWithObjects:btnLetter1,btnLetter2,btnLetter3,btnLetter4, nil];
    int CorrectImg = random() % [ButtonArray count];

    UIImage * img = [UIImage imageNamed:[LettersArray objectAtIndex:imgcounter]];
    UIButton * btn = [ButtonArray objectAtIndex:CorrectImg];
    [btn setImage:img forState:UIControlStateNormal];
    [ButtonArray removeObjectAtIndex:CorrectImg];

    NSLog(@"img correct: %i",CorrectImg);

    while ([ButtonArray count] != 0)// how many times u want to run this
    {
        int imgRand = random() % [LettersArray count]; //number for random image
        int btnRand = random() % [ButtonArray count]; //number for random button
        //get that random image
        UIImage * img = [UIImage imageNamed:[LettersArray objectAtIndex:imgRand]];
        //get that random button
        UIButton * button = [ButtonArray objectAtIndex:btnRand];
        //put image on that button
        [button setImage:img forState:UIControlStateNormal];
        [ButtonArray removeObjectAtIndex:btnRand];

        NSLog(@"btnrnd: %i",btnRand);
        NSLog(@"imgrnd: %i",imgRand);
    }
}


Q: Correct handling of exception: "getParameters failed (empty parameters)" I have a camera app in the Google Play store with Google Analytics installed.  I keep getting the following crash report:

getParameters failed (empty parameters)

My question is: What is the correct way to handle this?
Looking into the Android source of where it happens didn't give me any extra details.  The error is thrown in android_hardware_Camera.cpp:
String8 params8 = camera->getParameters();
if (params8.isEmpty()) {
    jniThrowRuntimeException(env, "getParameters failed (empty parameters)");
    return 0;
}

Looking into open source Android camera to see how it handles the situation was also not very helpful.  That code doesn't appear to catch the RuntimeException when calling getParameters.  (Except in one case where they catch it, close the camera, then rethrow it).
Is there a correct way to handle this?
If not, is there a reason this happens so often?
Note:
On any given day I have between 5k - 8k active users.  With somewhere between 40-70 of these exceptions.  That seems really high to me.  I know there are legit instances where a camera may fail to initialize.  But 1% of users seems unreasonable.  Also, since the Android camera app doesn't handle the exception it really makes me wonder if there is some other root cause.

A: In my case I was getting this error :

getParameters failed (empty parameters)

when I called getParameters() after unlocking the camera. So, please call getParameters() before you call camera.unlock().

A: Is there a specific Android device that experiences this error? Or do you see it across many devices.
In general, you should not see this kind of an error.  It's possible your application has some sort of race condition which results in this, but it'd have to involve trying to call getParameters on an uninitialized or already-released camera.
It could also be an error in the device-specific camera code, or a rare race condition somewhere in the camera code stack. Without more detail (logcat or Android bugreport from such a crash), it's impossible to tell - the error itself just says that the device-specific camera code returned an empty set of parameters.
But once you get this error, there's not a lot you can do - the camera subsystem is in some odd state. If you want to try to deal with it, all I can suggest is to close and reopen the camera device.

A: As +Eddy Talvala mentioned, this happens when the camera is in a bad state.
How does the camera get in a bad state?
1) Probably the most common reason would be closing/releasing the camera while still using it afterward.  This can be especially problematic if you are using the Camera object on multiple threads without synchronizing access to the Camera.  Make sure you only ever have a single thread accessing the Camera at a time.
2) In my case it was a bit more tricky. I use a SurfaceTexture so that I can use the camera output as an OpenGL texture. In Android 4.0 (ICS), there is a new method SurfaceTexture.release(). This method is important to use when using SurfaceTextures as it cleans up the memory quicker than it previously did.
The problem is that I was calling SurfaceTexture.release() while the camera preview was still active.  This was crashing the Camera service, which was causing the issue explained in the question.
In my case I fixed it by delaying the call to SurfaceTexture.release() until after I had replaced it with a new SurfaceTexture. This way I was certain the SurfaceTexture could be cleaned up without any bad side-effects.

A: camera objects are always locked by default
so when you can unlock method then you allow to other procceses to use your parameters
so make sure that you re locked the camera before getting parameters


Q: Can't write data into Excel-Sheet using openpyxl Workbook I'm trying to write to specific cells in a Excel-Sheet using openpyxl Workbook. At first I couldn't write to cells that already had data in them and now I can't write at all (or I'm just going crazy).
Here's my code:
    wb = load_workbook("..\\..\\Decision Tree Classifier  TPS\\Decision Tree Classifier  TPS\\TestData.xlsx")
    ws1 = wb.get_sheet_by_name("Sheet1")

    #this works
    print(ws1.cell(row=1, column=1).value)

    #these do not
    ws1['D3'] = 5
    ws1.cell(row=5, column=1).value = "SomeValue2"
    ws1.cell(row=7, column=1,value='Hey')
    ws1.cell(row=6, column=1).value = 'TEST'

    wb.save("TestData.xlsx")

I get no errors, the print line works, the write lines do not.
Similar problem here Writing data into Excel-Sheet using openpyxl isn't working, except I have the save function.
What gives?

A: When you're saving workbook, provide full path, otherwise you will save it in a Python folder. I'm pretty sure that's where your Excel workbook with new data resides.
wb.save("..\\..\\Decision Tree Classifier  TPS\\Decision Tree Classifier  TPS\\TestData.xlsx")

Also, don't forget to close your workbook when you're done with it.
wb.close()

Hope this helps!


Q: How Scroll RecyclerView With MediaPlayer I have recyclerview in activity and mediaplayer. I want when play mediaplayer and when seekbar change position my recycleview scroll with him.befor i do for scrollbar and rigth work.but i can not do for recycler .
Please help me!?
recyclerView = (RecyclerView) findViewById(R.id.recycler_view_matn);

public static void setAdapterLyric(List<Matn> matn) {
    adapterLyrics = new AdapterLyrics(matn);
    recyclerView.setAdapter(adapterLyrics);
  }

and this my seekbar:
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
      @Override
      public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        if (b) {
          G.mediaPlayer.seekTo(i);
        }
      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {

      }

      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {

      }
    });


Q: Calculate position of projector I am projecting a rectangle on a table with a beamer and I want to calculate the absolute position of the beamer in the space from the destortion of this rectangle. I know the absolute position (in 3D) of all the corners of the rectangle that is projected on the table.
I dont know how to get started with this and cannot find much usefull info on the internet.
Can someone provide some tips please?

A: It depends on what you know.  I'll choose the easiest:
If you know the position of the original rectangle, just find the intersection of the lines that go through the matching corners.


Q: Understanding Gauss's law Here there are Maxwell equations https://en.wikipedia.org/wiki/Maxwell%27s_equations . Let's take the first in particular, Gauss's law. In its integral form, the left side is equal to the integral over the volume $\Omega$ of $\nabla \cdot E$ (because of Stokes's theorem). So I have a triple integral of $\nabla \cdot E$ on the left side, and a triple integral (over the same volume) of $\frac{\rho}{\epsilon_0}$ on the other side. I can't see what they mean by "differential equations". This equation in particoular becomes $\nabla \cdot E= \frac{\rho}{\epsilon_0}$. I just don't understand what this means. It seems like that if two integrals are equal, then their integrands are also equal, which is obviously false.

A: Let's break this down into pieces.
A differential equation just means an equation that uses differentiation. ∇⋅E=ρ/ϵ0 is a differential equation because it involves a gradient.
You're mostly right. Both sides become a triple integral over the same volume (for any volume) which implies that the integrands of both are the same thing. You'll notice that the differential equation is simply stating this.


Q: Animation/transition for Shiny conditionalPanel Shiny conditionalPanels just abruptly appear then disappear. Is there any way to make them slide or fade or otherwise gently transition?

A: Here is a way to fade the element when it is shown:
js <- "
$(document).ready(function(){
  $('#plotContainer').on('show', function(event){
    $(this).css('opacity', 0).animate({opacity: 1}, {duration: 1000});
  });
});
"

ui <- fluidPage(
  tags$head(tags$script(HTML(js))),
  sidebarPanel(
    actionButton("showplot", "Show")
  ),
  mainPanel(
    conditionalPanel(
      condition = "input.showplot > 0",
      id = "plotContainer",
      plotOutput("plot")
    )
  )
)

server <- function(input, output) {
  x <- rnorm(100)
  y <- rnorm(100)

  output$plot <- renderPlot({
    plot(x, y)
  })
}

shinyApp(ui, server)

EDIT
And also an effect on the hide event:
js <- "
$(document).ready(function(){
  $('#plotContainer').on('show', function(){
    $(this).css('opacity', 0).animate({opacity: 1}, {duration: 1000});
  }).on('hide', function(){
    var $this = $(this);
    setTimeout(function(){
      $this.show().hide(1000);
    })
  });
});
"

ui <- fluidPage(
  tags$head(tags$script(HTML(js))),
  sidebarPanel(
    actionButton("showplot", "Show/Hide")
  ),
  mainPanel(
    conditionalPanel(
      condition = "input.showplot % 2 == 1",
      id = "plotContainer",
      plotOutput("plot")
    )
  )
)

server <- function(input, output) {
  x <- rnorm(100)
  y <- rnorm(100)

  output$plot <- renderPlot({
    plot(x, y)
  })
}

shinyApp(ui, server)

EDIT
Funny effects with the libraries Animate.css and jQuery-animateCSS:
js <- "
$(document).ready(function(){
  $('#plotContainer').on('show', function(){
    var $this = $(this);
    $this.css('opacity', 0).
      animate({opacity: 1}, 500, function(){
        $this.animateCSS('jello', {
          delay: 0,
          duration: 2000
        });
      });
  }).on('hide', function(){
    var $this = $(this);
    setTimeout(function(){
      $this.show().animateCSS('heartBeat', {
        delay: 0,
        duration: 2000,
        callback: function(){$this.hide(500);}
      });
    }, 0);
  });
});
"

ui <- fluidPage(
  tags$head(
    tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.0/animate.compat.min.css"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/animateCSS/1.2.2/jquery.animatecss.min.js"),
    tags$script(HTML(js))
  ),
  sidebarPanel(
    actionButton("showplot", "Show/Hide")
  ),
  mainPanel(
    conditionalPanel(
      condition = "input.showplot % 2 == 1",
      id = "plotContainer",
      plotOutput("plot")
    )
  )
)

server <- function(input, output) {
  x <- rnorm(100)
  y <- rnorm(100)

  output$plot <- renderPlot({
    plot(x, y)
  })
}

shinyApp(ui, server)

EDIT
I've done some convenient R functions to bind these animations in a Shiny app. Here is the code:
library(shiny)

animateCSS <- function(effect, delay = 0, duration = 500, then = NULL){
  effect <- match.arg(effect, c(
    "bounce",
    "flash",
    "pulse",
    "rubberBand",
    "shakeX",
    "shakeY",
    "headShake",
    "swing",
    "tada",
    "wobble",
    "jello",
    "heartBeat",
    "backInDown",
    "backInLeft",
    "backInRight",
    "backInUp",
    "backOutDown",
    "backOutLeft",
    "backOutRight",
    "backOutUp",
    "bounceIn",
    "bounceInDown",
    "bounceInLeft",
    "bounceInRight",
    "bounceInUp",
    "bounceOut",
    "bounceOutDown",
    "bounceOutLeft",
    "bounceOutRight",
    "bounceOutUp",
    "fadeIn",
    "fadeInDown",
    "fadeInDownBig",
    "fadeInLeft",
    "fadeInLeftBig",
    "fadeInRight",
    "fadeInRightBig",
    "fadeInUp",
    "fadeInUpBig",
    "fadeInTopLeft",
    "fadeInTopRight",
    "fadeInBottomLeft",
    "fadeInBottomRight",
    "fadeOut",
    "fadeOutDown",
    "fadeOutDownBig",
    "fadeOutLeft",
    "fadeOutLeftBig",
    "fadeOutRight",
    "fadeOutRightBig",
    "fadeOutUp",
    "fadeOutUpBig",
    "fadeOutTopLeft",
    "fadeOutTopRight",
    "fadeOutBottomRight",
    "fadeOutBottomLeft",
    "flip",
    "flipInX",
    "flipInY",
    "flipOutX",
    "flipOutY",
    "lightSpeedInRight",
    "lightSpeedInLeft",
    "lightSpeedOutRight",
    "lightSpeedOutLeft",
    "rotateIn",
    "rotateInDownLeft",
    "rotateInDownRight",
    "rotateInUpLeft",
    "rotateInUpRight",
    "rotateOut",
    "rotateOutDownLeft",
    "rotateOutDownRight",
    "rotateOutUpLeft",
    "rotateOutUpRight",
    "hinge",
    "jackInTheBox",
    "rollIn",
    "rollOut",
    "zoomIn",
    "zoomInDown",
    "zoomInLeft",
    "zoomInRight",
    "zoomInUp",
    "zoomOut",
    "zoomOutDown",
    "zoomOutLeft",
    "zoomOutRight",
    "zoomOutUp",
    "slideInDown",
    "slideInLeft",
    "slideInRight",
    "slideInUp",
    "slideOutDown",
    "slideOutLeft",
    "slideOutRight",
    "slideOutUp"
  ))
  js <- paste(
    "    $this.animateCSS('%s', {",
    "      delay: %d,",
    "      duration: %d,",
    "      callback: function(){",
    "        %s",
    "      }",
    "    });",
    sep = "\n"
  )
  sprintf(js, effect, delay, duration, ifelse(is.null(then), "", then))
}

onShowJS <- function(animation, fadeDuration){
  sprintf(paste(
    "$('#%%s>div').on('show', function(){",
    "  var $this = $(this);",
    "  $this.css('opacity', 0).animate({opacity: 1}, %d, function(){",
    animation,
    "  });",
    "});",
    sep = "\n"
  ), fadeDuration)
}

onHideJS <- function(animation, fadeDuration){
  paste(
    "$('#%s>div').on('hide', function(){",
    "  var $this = $(this);",
    "  setTimeout(function(){",
    sub(
      "^(\\s.*?\\$this\\.animateCSS)",
      "$this.show().animateCSS",
      sub(
        "\\{\n        \n      \\}",
        sprintf("{$this.hide(%d);}", fadeDuration),
        animation
      )
    ),
    "  }, 0);",
    "});",
    sep = "\n"
  )
}

animatedConditionalPanel <-
  function(condition, ..., onShow = NULL, fadeIn = 600, onHide = NULL, fadeOut = 400){
    id <- paste0("animateCSS-", stringi::stri_rand_strings(1, 15))
    jsShow <- ifelse(!is.null(onShow), sprintf(onShowJS(onShow, fadeIn), id), "")
    jsHide <- ifelse(!is.null(onHide), sprintf(onHideJS(onHide, fadeOut), id), "")
    script <- tags$script(HTML(paste(jsShow,jsHide,sep="\n")))
    condPanel <- conditionalPanel(condition, ...)
    tags$div(id=id, tagList(condPanel, script))
  }

You have to use animateCSS and animatedConditionalPanel only. The animateCSS function defines an animation. You can chain the animations with the then argument. The animatedConditionalPanel functions replaces conditionalPanel. Here is an example:
ui <- fluidPage(
  tags$head(
    tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.0/animate.compat.min.css"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/animateCSS/1.2.2/jquery.animatecss.min.js")
  ),
  sidebarPanel(
    actionButton("showplot", "Show/Hide")
  ),
  mainPanel(
    animatedConditionalPanel(
      condition = "input.showplot % 2 == 0",
      onShow = animateCSS("swing", duration = 1000, then = animateCSS("jello")),
      fadeIn = 400,
      onHide = animateCSS("pulse", then = animateCSS("bounce")),
      plotOutput("plot")
    )
  )
)

server <- function(input, output) {
  x <- rnorm(100)
  y <- rnorm(100)

  output$plot <- renderPlot({
    plot(x, y)
  })
}

shinyApp(ui, server)

UPDATE JUNE 2022
These animations will be available in the next version of the shinyGizmo package.
library(shiny)
library(shinyGizmo)

ui <- fluidPage(
  sidebarPanel(
    actionButton("showplot", "Show/Hide")
  ),
  mainPanel(
    fluidRow(
      column(
        10,
        conditionalJS(
          plotOutput("plot"),
          condition = "input.showplot % 2 === 1",
          jsCalls$animateVisibility("jello", "tada", duration = 1500)
        )
      ),
      column(2)
    )
  )
)

server <- function(input, output) {
  x <- rnorm(100)
  y <- rnorm(100)
  output[["plot"]] <- renderPlot({
    plot(x, y, pch = 19)
  })
}

shinyApp(ui, server)


Q: Java List I have the following method:
public static List<Integer> gradingStudents(List<Integer> grades) {
    for(int i = 0; i < grades.size(); i++){
        if(grades.get(i) < 40)
            continue;
        else if(grades.get(i) % 5 < 3)
            grades.get(i) = grades.get(i) + (Math.abs(grades.get(i)%5-5));
        else
            continue;
    }
    return grades;
}

I get an unexpected type error at else if part. Why can't I change the element of grades, like I wrote in the code, above?

A: You cannot assign to grades.get(i).
I suggest you simplify your code as follows:
public static List<Integer> gradingStudents(List<Integer> grades) {
    for(int i = 0; i < grades.size(); i++){
        int grade = grades.get(i);
        if (grade >= 40 && grade % 5 < 3) {
            grades.set(i, grade + Math.abs(grade%5-5));
        }
    }
    return grades;
}

A: It is because you are trying to modify the list like how you try to modify a list or dict in python as shown here. You have to use the inbuilt method .set() or .get(). set is used to add element by replacing it in the given index, add method adds the element to given index by pushing rest of the elements. You can understand more about the set and get method here
To this particular problem, as @Eran mentioned here, you can use the .set() method.


Q: pandas str.replace is not working properly I want to replace specific Strings within another String in my .csv file.
While
import pandas
df = pandas.read_csv("file.csv", sep=";",encoding='iso-8859-1')
df['Column'] = df['Column'].str.replace('Corona', '')

is correctly removing the word Corona from Coronavirus,
df['Column'] = df['Column'].str.replace('\xc3\xa4', 'ä')

ist not working to replace the given String.
Where is the mistake?

A: Try this
data["column_name"] = data["column_name"].apply(lambda x: x.replace("characters_need_to_replace", "new_characters"))


Q: When I store a bytearray with more than 100,000 index into the sqlite, I can only get 20 index of it while I select it from the table Here's what happen:
When I convert a bitmap into a bytearray, the bytearray stores more than 100,000 index, but when I use the SELECT function to get the bytearray, the bytearray have only 20 index left. What happen?
My field is using BLOB to store the bytearray, and the following code is what I'm trying to get the bytearray:
private void insertAttachmentRecord(int parentid) {

    for(int k = 0; k < attachmentarray.size(); k++) {
        byte[] claimAttachmentByteArray;
        newAttachmentRecord = new ContentValues();
        claimAttachmentByteArray = attachmentarray.get(k).getImageByteArray();
        newAttachmentRecord.put("claimattachmentimage", claimAttachmentByteArray);
        newAttachmentRecord.put("parent_id", parentid);
        claiminfoDB.insert(DBATTACHMENT_TABLE, null, newAttachmentRecord);
    }
}

And the query to get the bytearray:
private ArrayList<ClaimViewResult> GetClaimViewResult() {
    ArrayList<ClaimViewResult> results = new ArrayList<>();

    Cursor c2 = claiminfoDB.rawQuery("SELECT 'claimattachmentimage' FROM 'claimattachment' WHERE parent_id = "+bundletableId, null);

    if (c2.getCount() != 0) {
        c2.moveToFirst();

        ClaimViewResult cvr = new ClaimViewResult();
        byte[] imagebytearray = c2.getBlob(0);
        Bitmap bitmap = BitmapFactory.decodeByteArray(imagebytearray, 0, imagebytearray.length);
        cvr.setBitmap(bitmap);
        cvr.setFilename(getFilename());
        results.add(cvr);
        while (c2.moveToNext()) {
            cvr = new ClaimViewResult();
            imagebytearray = c2.getBlob(0);
            bitmap = BitmapFactory.decodeByteArray(imagebytearray, 0, imagebytearray.length);
            cvr.setBitmap(bitmap);
            cvr.setFilename(getFilename());

            results.add(cvr);
        }
    }
    return results;
}

Please help.

A: May be you need to change scheme for saving your bitmaps? For example, you can store bitmaps in inner app's directory and saving path to this image in database.
Also, you can try to change your select query like this:
SELECT * FROM your_table;

I think, you can receive only 20 bytes because you select word, not a column (I mean 'claimattachmentimage' in your query)


Q: SL5 In Browser WebBrowser Control error "Trying to revoke a drop target that has not been registered" when re-navigating to another PDF Finally bit the bullet and replaced my hack for displaying PDF content inside a silverlight app with a proper SL5 Trusted In-Browser WebBrowser that navigates to a .pdf.
When i try to RE-navigate the WebBrowser to another PDF I am seeing the error "Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100)"
This only happens when I deploy to IIS (localhost IIS and another server IIS 7.5) ... NOT while running in VS2010.
Details:
UI is extremely simple. 1 Grid w/ 2 columns:
Column 1    Column2
========    ====================================================================
Treeview    <WebBrowser x:Name="ContentWebBrowser" Grid.Column="1"></WebBrowser>
When user selects an item in the treeview, I simply call:
Uri serverUri = new Uri(string.Format("http://{0}:{1}/",
Application.Current.Host.Source.DnsSafeHost,
Application.Current.Host.Source.Port));

var relative= "/Content/x/y/z.pdf"; //This is dynamiclly pulled from Treeview, EDITED FOR SO
Uri relativeUri = new Uri(relative, UriKind.Relative);

ContentWebBrowser.Navigate(new Uri(serverUri, relativeUri));

With Cassini running silverlight both w/ and w/o debugger via VS2010 i can Select item after item in my list view and my WebBrowser will "re-navigate" calling this same code above.
BUT, once i deploy to my local iis, any time i end up calling Navigate for the 2nd time I am getting this error:
System.Exception: Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100)
   at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
   at MS.Internal.XcpImports.WebBrowser_Navigate(DependencyObject obj, Uri source)
   at System.Windows.Controls.WebBrowser.Navigate(Uri source)
   at SystemUtilities.Views.WebContentListView.TreeViewItem_Selected(Object sender, RoutedEventArgs e)

Other oddities: Sometimes i can "re-navigate" 3 or 4 times before i see this exception. Sometimes when i load another page in my SL application this error gets thrown.  Happens whether PDF is cached or not cached when I load it into the WebBrowser.  If i display standard html or an image instead of a PDF this does not happen.
Edit: I added logic to check to make sure LoadCompleted event fires before i try to re-navigate the WebBrowser but it does not seem to matter. (not 100% sure but i think that it ignores the fact that the PDF might still be loading and just signals that the DOM is ready).  Although, even if I want a long time (30 seconds) after it looks like the 1st pdf is done loading, i still get the error.
Any suggestions?

New I posted my sample on skydrive.. check out the readme in order to repro!: http://sdrv.ms/JSn1KB