text:
Q: Overloading ** in C++ In Python, we have nice simple syntax to take an arbitrary int/float to a power. Namely, for you non-Python programmers, we can have the following statement:
y = 2 ** 3
print y

This will print 8 to the console, and has nice syntax as there is a built in "power" operator. Is it possible to overload "**" as a single operator in C++? Specifically, I want to accomplish something like this:
int a = 2;
int b = 3;
cout << (a**b) << endl;

or, if this isn't possible, something like this:
MyInt a = new MyInt(2); // Wrapper class around ints to play nicely with **
MyInt b = new MyInt(3);
cout << (a**b) << end; // Assume ostream overridden for MyInt

These should also print 8 to console. I understand that it would be much easier to override the "^" operator to do the same thing, but I'm mostly interested to see whether or not I can overload "**". Would the operator "*" (for the MyInt class case, if it were a member function) have to look to see if the argument was another "*", as I don't know of a way to specify "**" as a single operator? Is it even possible to pass an operator as an argument?
Additional/bonus stipulation if possible (as if I haven't already said enough): No macros!!!

A: Short answer: No.  There is no way to "overload" arbitrary character/token sequences in C++.
Longer answer: a**b is equivalent to a * (*b), so you could overload both binary * (i.e. multiply) and unary * (i.e. dereference) in some gross way. But that would be completely opaque/unexpected to anyone reading your code, and painful to debug/maintain in future.
Just write a function called pow()!

A: You mean something like this?
#include <iostream>
#include <cmath>

struct MyInt {
    int val;
    struct MyProxy { int val; };

    MyProxy operator *() const{ return MyProxy{val}; }
    MyInt operator * (const MyProxy& b) { return MyInt{ static_cast<int>(std::pow(val, b.val)) }; }

};

std::ostream& operator << (std::ostream& o, const MyInt& m) { return o << m.val; }

int main(){
    MyInt a{5}, b{3};
    std::cout << a**b << std::endl;
}

See it live here http://coliru.stacked-crooked.com/a/ab56b9cd6e422e12
Explanation:

*

*Overload the unary * operator to return a proxy object

*Overload the binary * operator to use the proxy... Simple :-)

*I used a proxy class to avoid subtle bugs..

C++ is fun... I want to believe you are doing this for fun AND not in production... Cause its a very bad idea in production, just call std::pow


text:
Q: Proof of sign of $\cos(x)$ and $\sin(x)$. I would like to know if there is a way to proof that $\cos(x)\geq0$ if $x \in [\frac{-\pi}{2};\frac{\pi}{2}]$ and $\cos(x) \leq 0$ if $x \in [\frac{\pi}{2};\frac{3\pi}{2}]$ knowing only that $f :(\mathbb R, +) \to (\mathbb C(1), \times)$ that from an angle $\theta$ gives the complex number $e^{i\theta}$ is a morphism so $\operatorname{ker} f = 2\pi \mathbb Z$, also knowing $\cos(\theta) = \Re(e^{i\theta})$, $\sin(\theta) = \Im(e^{i\theta})$, knowing $e^{i\pi}=-1$ all summation and duplication rules of $\cos$ and $\sin$. We are also allowed to use derivative formulas.
I really don't see any way to do it. My final goal is to show that $\cos(2\pi/3)$ is negative only with this tools...

redpajama_set_name: RedPajamaStackExchange


text:
Q: adding a new column to pandas slow without reset_index I have data1 which contains about 20,000 rows:
data2=data1[data1.column=="ABC"] #about 100 rows

data1["temp"]=1  #takes no time even though it has 20k rows

data2["temp"]=1 #takes a second!

If I call the following, it executes quickly.
data2 = data2.reset_index(drop=True);
data2["temp"]=1

What am I missing here?  I clearly don't understand what index thing is for in pandas and how to use it.


text:
Q: Android Emulator is not starting in Ubuntu I have Ubuntu 11.04 and i downloaded latest eclipse ADT bundle, i also have installed all ia32libs, i dont know why the emulator is not starting, i have tried various device configurations, i have 4 platforms 2.2, 2.3 , 4.0 ,4.2. i have tried various permutation and combination, but virtual device does not show up-none of them.
I have also tried various solutions in other SO'questions, they do not solve my problem. i have been stuck in these for weeks, still i have reached no where?Please Help
FYI: I also have eclipse Helios, in that it works fine but, i cannot get/download platform above 3.0/Honeycomb in that, and in the Helios the virtual devices work fine. i dont know whether its relevant or not, but still..

A: Ubuntu Android Emulator Problem [Solved]
The issue with android emulator is not the hardware drivers. It is OpenGL drivers. To solve it please go through these steps:

*

*Open synaptic package manager (If not please install it from Ubuntu software center)

*In Quick filter type "opengl" and press search.

*Select the following packages:
libgles1-mesa-dev
libgles2-mesa-dev
libgles1-mesa
libgles2-mesa
libqt4-opengl [Update/Upgrade]
glmark2
glmark2-es2
libgles1-mesa-dbg
libgles2-mesa-dbg
freeglut3
libhugs-opengl-bundled

*Selection procedure
    Right click on the package and select as 'Mark for Installation".

*And click 'Apply'.

*Enjoy the ANDROID PROGRAMMING WITH THE EMULATOR.

A: Run your emulator in Command Line Parameters
To start an instance of the emulator from the command line, navigate to the tools/ folder of the SDK. Enter emulator command like this:
emulator -avd <avd_name>

more about emulator link here:

A: On Ubuntu 14.04 64bit with a NVidia graphics card I had to do the following:

*

*Install the SDK and ADT plugin for Eclipse

*Install 32-bit libraries sudo apt-get install lib32stdc++6 lib32z1

*Install OpenGL libraries sudo apt-get install libgl1-mesa-dev

*Install proprietary drivers for the graphics card: System Settings > Software & Updates > Additional Drivers NVIDIA binary driver version 331.38

*From Eclipse, run the Android Virtual Device Manager and edit a device. Enable "Use Host GPU" & save.

It then worked.

A: on Ubuntu 12.04 LTS 64-Bit (installed the 32-bit libraries),
My Case was :
1- downloaded and installed the SDK properly
2- download ADT plug in to Eclipse and restart it
3- set the SDK directory properly
4- create an Android project, and click RUN AS > Android application
5- asked me for an Emulator, so i created one from the AVD (after some steps from the Run Configurations)
6- then i Right-Click that application again, RUN AS > Android Application
7- a message appears > ERROR : Couldn's start Emulator ... install SDK properly (something like that)
8- Restart Eclipse ... every thing is fine !!!!!!!!!!!!!!!!!!

A: You need to change the following option:
Edit your avd and change the "emulated performance" option to "software".
It will work.

A: I am using Bumblebee to disable my nvidia card...
It seems like Android Studio does not like that.
optirun /opt/android-studio/bin/studio.sh

And then open AVD Manager in Android Studio made it work.

A: Source: https://cialu.net/solve-android-studio-avd-issue-with-ubuntu-16-10/
   sudo apt-get install lib64stdc++6:i386

   sudo apt-get install mesa-utils

(look for the path of the sdk)
  cd YOURPATH/Android/Sdk/emulator/lib64

  mv libstdc++/ libstdc++.bak

  ln -s /usr/lib64/libstdc++.so.6  libstdc++

Finally, run your application again using emulator.

A:
If you are getting error like above then please update/upgrade your Linux Machine(Ubuntu) as for example

*

*sudo apt-get update

*sudo apt-get upgrade

and make sure that all as per Android Developer website all the required software are  installed.
 If Still you are facing same issue as per image then use su mode in your terminal before starting emulator.
sudo su -  Use this command to be Su user

A: Since Neither Ubuntu Support 32 bit nor Android Developers tools support 32 bit (Now and Legally) and also some having low end pc(s) like 512 mb ram, and for casually playing games for pc the best option for running android is Android X86  . Its fast and always working android emulator(actually not emulator but an OS) you can use it for any thing even 20 years old pc can run it very very smoothly .
To Run it in your any computer follow the below steps:-

*

*Go to https://www.android-x86.org/

*Download any iso from there (i recommend for pc more than 512 mb ram =4.4 kitkat, and latest for more than 2gb ram(android 9.*) )

*Download Rufus or Etcher (Etcher is recommended, Download Portable)

*Flash to Your Pen-drive or SD card

*Keep it Inserted and Restart

*You Will be On landing page (back to your pc ,Click here)

*Click on Live CD (if Dosen't work click on more option or VESA mode)


text:
Q: UITableView.automaticDimension not working I've got a problem with a prototype cell (which is populated from Firebase), where the cell height is not being set correctly despite constraints being set.
I've tried setting the following:
override func viewDidLoad() {
    super.viewDidLoad()

    TableViewPVV.rowHeight = UITableView.automaticDimension
    TableViewPVV.estimatedRowHeight = 100

}

This does not work.  When using UITableView.automaticDimension, the cell height defaults to 44.
However, if the cell height can be expanded if I set TableViewPVV.rowHeight explicitly to a value like 100.
NOTE:  I also need to explicitly define the label's desired width or the rowHeight value specified is ignored.
ALSO NOTE: I have the following constraints set on the label: Trailing Space to Superview = 2, leading space = 2, Bottom space >= 2, Top Space >= 2.
Some screenshots as follows:

Nayem: edited to add a new image for you of what the content looks like without setting a desired width, and with the height set to 100.

import UIKit
import Firebase

class PVVViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var PVVList = [PVVModel]()

    @IBOutlet weak var TableViewPVV: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        LoadDataFromPVV()

         // TableViewPVV.rowHeight = 100
        TableViewPVV.rowHeight = UITableView.automaticDimension
        TableViewPVV.estimatedRowHeight = 100

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

        return PVVList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        //creating a cell using the custom class

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PVVViewControllerTableViewCell

        //the PVV object
        let PVV: PVVModel

        //getting PVV for selected position
        PVV = PVVList[indexPath.row]

        //adding values to labels
        cell.PVVData.text = PVV.BodyText

        //returning cell
        return cell
    }

     func LoadDataFromPVV() {

        databaseReference = Database.database().reference()

        let refPVV = Database.database().reference(withPath: "PVV").queryOrdered(byChild: "Status").queryEqual(toValue: "Active")

        refPVV.observeSingleEvent(of: .value, with: { (snapshot) in

            //if the reference have some values
            if snapshot.childrenCount > 0 {

                //clearing the list
                self.PVVList.removeAll()

                //iterating through all the values
                for PVV in snapshot.children.allObjects as! [DataSnapshot] {
                    //getting values
                    let PVVObject = PVV.value as? [String: AnyObject]
                    let PVVText  = PVVObject?["BodyText"]

                    //creating PVV object with model and fetched values
                    let PVV = PVVModel(BodyText: PVVText as! String?)

                    //appending it to list
                    self.PVVList.append(PVV)
                 }

                //reloading the tableview
                self.TableViewPVV.reloadData()
            }

        })
    }
}

I'm hoping to be able to dynamically adjust the height of my label (PVVData) to fit the text as captured from Firebase.

A: In most cases it's the issue of constraints .... Please make sure that your top label is top aligned with contenview and your bottom most label is aligned with bottom constraint of the contentView.
see this example

A: Just try the below method :
set constraints as shown in the image below (without minimum height).

set constraints as shown in the image below (with a minimum height).
for a minimum height you requiure a height constraint.

Set number of lines to 0.

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

A: Please add this method in your class
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

Make sure label attribute like this:

And Set proper constraint for label.


text:
Q: Store values from dynamically generated text boxes into array I'm creating a Time table generating website as a part of my project and I am stuck at one point.
Using for loop, I am generating user selected text boxes for subjects and faculties. Now the problem is that I cannot get the values of those dynamically generated text boxes. I want to get the values and store it into array so that I can then later on store it to database
If I am using localstorage, then it sometimes shows NaN or undefined. Please help me out.
Following is my Jquery code
$.fn.CreateDynamicTextBoxes = function()
        {
            $('#DynamicTextBoxContainer, #DynamicTextBoxContainer2').css('display','block');

            InputtedValue = $('#SemesterSubjectsSelection').val();

            SubjectsNames = [];

            for (i = 0; i < InputtedValue; i++)
            {
                TextBoxContainer1 = $('#DynamicTextBoxContainer');
                TextBoxContainer2 = $('#DynamicTextBoxContainer2');

                $('<input type="text" class="InputBoxes" id="SubjectTextBoxes'+i+'" placeholder="Subject '+i+' Name" style="margin:5px;" value="">
').appendTo(TextBoxContainer1);
                $('<input type="text" class="InputBoxes" id="FacultyTextBoxes'+i+'" placeholder="Subject '+i+' Faculty Name" style="margin:5px;" value="">
').appendTo(TextBoxContainer2);
                SubjectsNames['SubjectTextBoxes'+i];
            }

            $('#DynamicTextBoxContainer, #UnusedContainer, #DynamicTextBoxContainer2').css('border-top','1px solid #DDD');
        }

        $.fn.CreateTimeTable = function()
        {
            for (x = 0; x < i; x++)
            {
                localStorage.setItem("Main"+x, +SubjectsNames[i]);
            }
        }

I am also posting screenshot for better understanding

A: I understand you create 2 text boxes for each subject, one for subject, and second one for faculty. And you want it as a jQuery plugin.
First of all, I think you should create single plugin instead of two, and expose what you need from the plugin.
You should avoid global variables, right now you have InputtedValue, i, SubjectsNames, etc. declared as a global variables, and I believe you should not do that, but keep these variables inside you plugin and expose only what you really need.
You declare your SubjectNames, but later in first for loop you try to access its properties, and actually do nothing with this. In second for loop you try to access it as an array, but it's empty, as you did not assign any values in it.
Take a look at the snippet I created. I do not play much with jQuery, and especially with custom plugins, so the code is not perfect and can be optimized, but I believe it shows the idea. I pass some selectors as in configuration object to make it more reusable. I added 2 buttons to make it more "playable", but you can change it as you prefer. Prepare button creates your dynamic text boxes, and button Generate takes their values and "print" them in result div. generate method is exposed from the plugin to take the values outside the plugin, so you can do it whatever you want with them (e.g. store them in local storage).

$(function() {
  $.fn.timeTables = function(config) {
    // prepare variables with jQuery objects, based on selectors provided in config object
    var numberOfSubjectsTextBox = $(config.numberOfSubjects);
    var subjectsDiv = $(config.subjects);
    var facultiesDiv = $(config.faculties);
    var prepareButton = $(config.prepareButton);
    var numberOfSubjects = 0;

    prepareButton.click(function() {
      // read number of subjects from the textbox - some validation should be added here
      numberOfSubjects = +numberOfSubjectsTextBox.val();

      // clear subjects and faculties div from any text boxes there
      subjectsDiv.empty();
      facultiesDiv.empty();

      // create new text boxes for each subject and append them to proper div
      // TODO: these inputs could be stored in arrays and used later
      for (var i = 0; i < numberOfSubjects; i++) {
        $('<input type="text" placeholder="Subject ' + i + '" />').appendTo(subjectsDiv);
        $('<input type="text" placeholder="Faculty ' + i + '" />').appendTo(facultiesDiv);
      }
    });

    function generate() {
      // prepare result array
      var result = [];

      // get all text boxes from subjects and faculties divs
      var subjectTextBoxes = subjectsDiv.find('input');
      var facultiesTextBoxes = facultiesDiv.find('input');

      // read subject and faculty for each subject - numberOfSubjects variable stores proper value
      for (var i = 0; i < numberOfSubjects; i++) {
        result.push({
          subject: $(subjectTextBoxes[i]).val(),
          faculty: $(facultiesTextBoxes[i]).val()
        });
      }

      return result;
    }

    // expose generate function outside the plugin
    return {
      generate: generate
    };
  };

  var tt = $('#container').timeTables({
    numberOfSubjects: '#numberOfSubjects',
    subjects: '#subjects',
    faculties: '#faculties',
    prepareButton: '#prepare'
  });

  $('#generate').click(function() {
    // generate result and 'print' it to result div
    var times = tt.generate();
    var result = $('#result');
    result.empty();

    for (var i = 0; i < times.length; i++) {
      $('
' + times[i].subject + ': ' + times[i].faculty + '
').appendTo(result);
    }
  });
});
#content div {
  float: left;
}

#content div input {
  display: block;
}

#footer {
  clear: both;
}

    <input type="text" id="numberOfSubjects" placeholder="Number of subjects" />
    <button id="prepare">
      Prepare
    </button>

  <button id="generate">Generate</button>


text:
Q: Wcf returning ususual response I am trying to return a list

public List<tblcourse> GetData(string value)
{
    testEntities1 db = new testEntities1();

    int v = Convert.ToInt32(value);
    testEntities1 t = new testEntities1();
    var u = (from g in t.tblcourses
             select new  { g.C_Id,  g.C_Name }).ToList();

    List<tblcourse> lisstt = new List<tblcourse>();

    foreach (var item in u)
    {
        tblcourse b = new tblcourse();
        b.C_Id = item.C_Id;
        b.C_Name = item.C_Name;
        lisstt.Add(b);
    }

    return lisstt;
}

From client when I consume this service , I get the following response from the service when I execute client code
string strServiceUrl1 = "htttp://localhost:1967/Service1.svc/GetData/" + id;

HttpWebRequest objHttpWebRequest1 = WebRequest.Create(strServiceUrl1) as HttpWebRequest;
objHttpWebRequest1.Method = "GET";
objHttpWebRequest1.ContentType = "application/json-urlencoded";

StreamReader onjStreamReader1 = new StreamReader(objHttpWebRequest1.GetResponse().GetResponseStream());
string strResponse1 = onjStreamReader1.ReadToEnd().ToString();

List<Course> cc = JsonConvert.DeserializeObject<List<Course>>(strResponse1);
return View(cc);

The following is the response I am getting as response and because of that I am not able to deserialize the response into a list.
<ArrayOftblcourse xmlns="htttp://schemas.datacontract.org/2004/07/app2"
                  xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
   <tblcourse>
      <C_Id>1</C_Id>
      <C_Name>DOt Net</C_Name>
   </tblcourse>
   <tblcourse>
      <C_Id>2</C_Id>
      <C_Name>EF</C_Name>
   </tblcourse>
   <tblcourse>
      <C_Id>3</C_Id>
      <C_Name>MVC</C_Name>
   </tblcourse>
   <tblcourse>
      <C_Id>4</C_Id>
      <C_Name>MS SQL</C_Name>
   </tblcourse>
</ArrayOftblcourse>

Contract
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetData/{value}") ]
List<tblcourse> GetData(string value);

Error while deserializing is

Additional information: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

Autogenerated class file of tbclcourses
[DataContract]
[KnownType(typeof(tblstudent))]
public partial class tblcourse
{
        public tblcourse()
        {
            this.tblstudents = new HashSet<tblstudent>();
        }

        [DataMember]
        public int C_Id { get; set; }

        [DataMember]
        public string C_Name { get; set; }

        public virtual ICollection<tblstudent> tblstudents { get; set; }
}

web.config files webHttpBinding:
<webHttpBinding>
    <binding name="webHttpBinding"
             maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
             transferMode="StreamedResponse">
       <security mode="None">
           <transport clientCredentialType="Basic"></transport>
       </security>
       <readerQuotas maxArrayLength="100000" maxStringContentLength="2147483647" />
   </binding>
</webHttpBinding>

A: I think your webinvoke should look like this. ( Specify response format)
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetData/{value}",ResponseFormat = WebMessageFormat.Json) ]
List<tblcourse> GetData(string value);


text:
Q: Ocurre ERROR SIGSEGV Se trata del inicio del código para Djikstra Shortest Paths, pero me da el error SIGSEGV...
¿A que debiera inicializar Graph?
El programa no se ejecuta hasta llegar a  esta línea (sin haber dado el error):
for (int j=0; j < Nodes; ++j)

Este es mi código:
int main() {

    int Nodes, Start_Node;
    double Density;
    vector <int> Output_Distances(Nodes);
    // input Number of Nodos, Densidad, to generate random matrix
    cout << "Enter number of Nodes: " << endl;
    cin >>  Nodes;
    cout << "Enter Graph Edges Density: " << endl ;
    cin >>  Density;
    cout << "Enter Start Node: "  << endl;
    cin >> Start_Node;

    vector <int>* graph; // Declares graph to fill out with edges

    srand(time(0)); // seed rand

    for (int i=0; i < Nodes; ++i) // loop to fill the matrix with false or true, randomly with probability less than Density
        for (int j=0; j < Nodes; ++j)
            if (i==j) graph[i][j]=false; //diagonal - no loop edge

Gracias!

A: No has inicializado el vector:
Eso, en ese punto es nulo.
vector <int>* graph;

Aquí estás accediendo a la posición i, j de un vector, en vez de una matriz.
if (i==j) graph[i][j]=false


text:
Q: Apache2 server video streaming compatibility with mobile devices and PC I am experiencing troubles trying some server admin and web dev stuffs, as I am a C/C++ dev...
What I want to do is to be able to view some videos, by accessing link like http://www.mywebsite.com/username/video_001.mp4
I am running an Ubuntu 16.04.4 LTS server on a VPS Cloud from OVH.
I installed apache2 and put a .htpasswd file to restrict the access to specific valid user.
On my website .conf file, I then put some redirections to my videos folder :
Alias /username/ "/home/path/to/videos/username/"
<Directory "/home/path/to/videos/">
    AuthType Basic
    AuthName "Restricted Content"
    AuthUserFile /etc/apache2/.htpasswd
    Require user username
    Options Indexes
</Directory>

My videos are MP4 / H.264, 1080p / 5fps, 1Mb/s bitrate formatted.
Everything works fine on Windows Chrome and Android (Chrome, Samsung browser).
But on iDevices, the player of the browser starts the video but displayes a black image for the duration of the video (tried iPhone and iPad with Safari, Chrome and Firefox / and on iMac, Safari and Chrome doesn't works, but I can download the video and view it using VLC not QuickTime).
I read somewhere that for compatibility reasons, I must keep the raw file and let the device/browser's player read it. That's why I don't really want to devlop a HTML5 player.
But, if I want to get the most compatibilty possible, what is the best solution ?
I thought I'd convert my .mp4 file to .ogv and .webm, put everything in a directory, and make a small html page that will list the directory content, hidding non compatible files.
Like if I detect the HTTP_AGENT / browser, I'll know which file i'll put a like in my webpage (for example : for Android, my page will serve as an "Index Of", only displaying .mp4 file / on iDevices something else).
But doesn't seems really reliable...
EDIT :
I discovered that the native video player inside iDevices and Windows Microsoft Edge can't read MP4 videos (1920x1072, 5fps, 1Mb/s) recorded using openRTSP. But, if I use FFMPEG to convert the file, it is readable.
Maybe I'm doing something wrong with the options of openRTSP, but I'd like to keep using it and not FFMPEG (we switched from it to resolve lot of artefacts).
Feel free to ask for complement !

A: Videos recorded with openRTSP are not playable on iDevices.
It seems that Live555 (openRTSP team) indicates it in its FAQ and has already transfered the information to Apple without any news.


text:
Q: Find the Thévenin equivalent between terminals A and B Can you help me find the Thévenin equivalent between terminals A and B with all the steps?

$$R_{eq}=\frac{4}{3}~\Omega\\
V_{eq}=\frac{5}{3}~\mathrm{V}$$
In the first image is the circuit, and below there are the solutions. I need the calculations for the solution of Req.
Here is my attempt:
Req = ((2//3)+3)//1 = 21/26
Veq =
$$\left[\begin{matrix}
2+1+3+3&-3
\\\\
-3&3
\\\\
\end{matrix}\right]
\left[\begin{matrix}
I_1\vphantom{\frac{-1}{R_3}}
\\\\
I_2\vphantom{\frac{-1}{R_3}}
\\\\
\end{matrix}\right]
=
\left[\begin{matrix}
2\:\text{V}\vphantom{\frac{-1}{R_3}}
\\\\
3\:\text{V}\vphantom{\frac{-1}{R_3}}
\\\\
\end{matrix}\right]$$
This solves to:
$$
\left[\begin{matrix}
I_1=\frac56\:\text{A}
\\\\
I_2=\frac{11}{6}\:\text{A}
\\\\
\end{matrix}\right]$$
So
$$V_{eq}=\frac{5}{6}\times2=\frac{5}{3}V$$
Req =

A: These are just hints to get the OP down the right path

The problem is to find the Req

Start like this: -

The resistance (\$R_{AB}\$) is easy now.


text:
Q: I have a spinner that gets its items dynamically with an EditText. It is stored into SQLite. How do I add a single item on the start? I am trying to add a single item that holds no value to the Spinner.  I want the users to see , "Choose an Item" whenever the activity is started.  How do I add a single item to the spinner in onCreate? Keep in mind the users can add items to the spinner dynamically with a button and edit text.  Rite now the first thing in the spinner is the first item added to the database. If nothing is added to the database, the spinner is blank.
Here is my code
MainActivty
public class MainActivity extends Activity implements OnItemSelectedListener {

Button AddBtn;
EditText et;
EditText cal;
Spinner spn;

SQLController SQLcon;
ProgressDialog PD;

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

    AddBtn = (Button) findViewById(R.id.addbtn_id);
    et = (EditText) findViewById(R.id.et_id);
    cal = (EditText) findViewById(R.id.et_cal);
    spn = (Spinner) findViewById(R.id.spinner_id);
    spn.setOnItemSelectedListener(this);
    SQLcon = new SQLController(this);
    // opening database
    SQLcon.open();

    loadtospinner();

    AddBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            new MyAsync().execute();

        }
    });
}

public void loadtospinner() {

    Cursor c = SQLcon.readData();
    ArrayList<String> al = new ArrayList<String>();

    c.moveToFirst();
    while (!c.isAfterLast()) {

        String name = c.getString(c.getColumnIndex(DBhelper.MEMBER_NAME));

        al.add(name);

        c.moveToNext();
    }

    ArrayAdapter<String> aa1 = new ArrayAdapter<String>(
            getApplicationContext(), R.layout.spinner_item, R.id.textView1,
            al);

    spn.setAdapter(aa1);

    // closing database
    SQLcon.close();

}

private class MyAsync extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        PD = new ProgressDialog(MainActivity.this);
        PD.setTitle("Please Wait..");
        PD.setMessage("Loading...");
        PD.setCancelable(false);
        PD.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        String name = et.getText().toString();
        String calories = cal.getText().toString();
        // opening database
        SQLcon.open();
        // insert data into table
        SQLcon.insertData(name, calories);

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        loadtospinner();
        PD.dismiss();
    }
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {

    String getName;
    getName = "";
    String getCalories;
    getCalories = "";

    SQLController handlerInfo = new SQLController(getBaseContext());
    handlerInfo.open();
    Cursor cursor = handlerInfo.readData();
    if (cursor.moveToFirst()) {
        do {
            getName = cursor.getString(1);
            getCalories = cursor.getString(2);

        } while (cursor.moveToNext());
    }

    handlerInfo.close();

    // Showing selected spinner item
    Toast.makeText(parent.getContext(), "You selected: " + getCalories,
            Toast.LENGTH_LONG).show();

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

}

Database and helper
public class DBhelper extends SQLiteOpenHelper {

// TABLE INFORMATTION
public static final String TABLE_MEMBER = "member";
public static final String MEMBER_ID = "_id";
public static final String MEMBER_NAME = "name";
public static final String KEY_CALORIES = "calories";

// DATABASE INFORMATION
static final String DB_NAME = "MEMBER.DB";
static final int DB_VERSION = 2;

// TABLE CREATION STATEMENT
private static final String CREATE_TABLE = "create table " + TABLE_MEMBER
        + "(" + MEMBER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + MEMBER_NAME + " TEXT NOT NULL," + KEY_CALORIES
        + " INT NOT NULL);";

public DBhelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
    onCreate(db);
}
}

Database and helper
public class SQLController {
private DBhelper dbhelper;
private Context ourcontext;
private SQLiteDatabase database;

public SQLController(Context c) {
    ourcontext = c;
}

public SQLController open() throws SQLException {
    dbhelper = new DBhelper(ourcontext);
    database = dbhelper.getWritableDatabase();
    return this;

}

public void close() {
    dbhelper.close();
}

public void insertData(String name, String calories) {
    ContentValues cv = new ContentValues();
    cv.put(DBhelper.MEMBER_NAME, name);
    cv.put(DBhelper.KEY_CALORIES, calories);
    database.insert(DBhelper.TABLE_MEMBER, null, cv);
}

public Cursor readData() {
    String[] allColumns = new String[] { DBhelper.MEMBER_ID,
            DBhelper.MEMBER_NAME, DBhelper.KEY_CALORIES };
    Cursor c = database.query(DBhelper.TABLE_MEMBER, allColumns, null,
            null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

}


text:
Q: Caching data in ASP.net MVC A friend asked me to use Output Cache to cache data, that works good, but the thing is that I want to get data from the database and then interact with that data, I mean, I want to grab a huge data from the database, and then get only some data from that huge data according to the user activity dynamically.
 [OutputCache(Duration =600, VaryByParam ="none")]
public ActionResult GetData()
{
var result = context.People.ToList();
return View(result);
}

That's an example, but let's say that I want to use pagination for that data in my view, and I want to show every person according to the date birth, for example default page current week, with a link called 'Next' and other one called 'Previous' . When 'Next' link is clicked I want to display only the people which birthday is the next week, same thing with 'Previous', showing just people with birthday on the previous week..
But using Output Cache I'm displaying the same data all the time... Is it possible to do this interacting with the database only the first time, caching that data, and then interacting with that data and not read against the database again during the time I set on the duration?? Do you advise me to use another Caching Tool different than Output Cache?

A: Instead of caching the entire view, maybe you could just add the result to the session state?
public ActionResult GetData()
{
    if (HttpContext.Current.Session["peopleList"] != null)
    {
        return View((List<People>)HttpContext.Current.Session["peopleList"]);
    }
    else
    {
        var result = context.People.ToList();
        HttpContext.Current.Session["peopleList"] = result;
        return View(result);
    }
}

You can control how long session state lasts in your Web.config or through IIS.


text:
Q: MongoDB group retrieves null in the key I'm using this to get the result I want, basically I need the total revenue from each supplier.
db.lineitems.group(
{
    key : {"$partsupp.supplier.suppkey" : 1},
    cond : { "shipdate" : {"$gte":19960101,"$lt":19960401}},
    reduce : function (curr, result) {
        result.totalgroup+=curr.extendedprice*1-curr.discount;
    },
    initial : {totalgroup : 0}
}
)

And the result is this:
[
    {
    "$partsupp.supplier.suppkey" : null,
    "totalgroup" : 208208820.8400005
    }
]

This return the sum of all suppliers revenue.

A: var red2 = function(doc, out) {
out.revenue+=doc.extendedprice*(1-doc.discount);
};

var eachsupp = db.lineitems.group( {
    key : { "partsupp.supplier.suppkey" : true},
    cond : { "shipdate" : {$gte: 19960101, $lt: 19960401}},
    initial: { revenue : 0},
    reduce : red2,
});


text:
Q: How to avoid selected list item moving to top of the list? I have RecyclerView which contains 50 items in it. I will navigate one by one using Remote control unit up and down buttons. To select any item (e.g 25th) I'm using recyclerview.scrollToPosition(position) method. After this selection the item automatically moves to top position of the list. I don't want my selected item to go top of the position. I wanted to be the same selected position. How do I achieve this?
Thanks,
K. Rajesh

A: If you're using an up and down control, that are complete separate from the actual ViewHolders of the RecyclerView, you could just use RecyclerView.scrollBy(x, y).
Assuming all of your items are the same size, you don't even have to take the "selected item" index into account, since there's no possibility of variability in item height.  Just use the View at the first position and scroll by either a positive or negative height on each up or down button click.
A partial example in Kotlin would look something like this if you're using a LinearLayoutManager or GridLayoutManager:
    view.findViewById<Button>(R.id.up).setOnClickListener {
        val temp = recyclerView.layoutManager.findViewByPosition((recyclerView.layoutManager as LinearLayoutManager).findFirstCompletelyVisibleItemPosition())
        temp?.let {
            recyclerView?.scrollBy(0, -it.height)
        }
    }

    view.findViewById<Button>(R.id.down).setOnClickListener {
        val temp = recyclerView.layoutManager.findViewByPosition((recyclerView.layoutManager as LinearLayoutManager).findFirstCompletelyVisibleItemPosition())
        temp?.let {
            recyclerView?.scrollBy(0, it.height)
        }
    }

Also, note that if you added in ItemDecorations to your RecyclerView, you would need to take those extra spacings into account when doing the scroll by.


text:
Q: FAB on pre-lollipop devices with the new support lib The support library doc states that the version 22.2 supports FloatingActionButton on Pre-Lollipop devices.
I have implemented a demo app to show a FAB on KitKat.
The FAB is shown but I still can't set the elevation neither in the xml nor in the code.
In the xml I get the warning and I need to use tools:ignore="NewApi". If I call setElevation programmatically I get an exception because the method does not exist.
I have added this to my layout
<android.support.design.widget.FloatingActionButton
    android:id="@+id/add_button"
    style="@style/FAB"
    android:src="@drawable/ic_add_white_24dp"
    android:contentDescription="@string/add_ringtone" />

where the style is defined like this:
<resources
    xmlns:tools="http://schemas.android.com/tools">
    <style name="FAB" tools:ignore="NewApi">
       <item name="android:layout_width">@dimen/fab_width</item>
       <item name="android:layout_height">@dimen/fab_height</item>
       <item name="android:background">@drawable/fab_background</item>
       <item name="android:layout_alignParentBottom">true</item>
       <item name="android:layout_alignParentRight">true</item>
       <item name="android:layout_marginBottom">@dimen/fab_margin</item>
       <item name="android:layout_marginRight">@dimen/fab_margin</item>
       <item name="android:elevation" >@dimen/fab_elevation</item>
       <item name="android:stateListAnimator">@anim/rise</item>

    </style>

</resources>

What should I do to set the elevation on KitKat with the new support library?

A: Since the new FAB is now part of the support library, you'll probably need to replace
<item name="android:elevation">@dimen/fab_elevation</item>

by
<item name="app:elevation">@dimen/fab_elevation</item>

in your style.

A: This is the solution:
In the gradle file:
dependencies {
    compile 'com.android.support:support-v4:22.2.0'
    compile 'com.android.support:design:22.2.0'
}

In the layout file:
<android.support.design.widget.FloatingActionButton
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:id="@+id/add_button"
    style="@style/FAB"
    app:elevation="@dimen/fab_elevation"
    android:src="@drawable/ic_add_white_24dp"
    android:contentDescription="@string/add_ringtone" />

In the styles.xml under values folder:
<style name="FAB">
    <item name="android:layout_width">@dimen/fab_size</item>
    <item name="android:layout_height">@dimen/fab_size</item>
    <item name="android:background">@drawable/fab_background</item>
    <item name="android:layout_alignParentBottom">true</item>
    <item name="android:layout_alignParentRight">true</item>
    <item name="android:layout_marginBottom">@dimen/fab_edge_distance</item>
    <item name="android:layout_marginRight">@dimen/fab_edge_distance</item>

In the styles.xml under values-21 folder:
<resources
    xmlns:tools="http://schemas.android.com/tools">
    <style name="FAB" tools:ignore="NewApi">
       <item name="android:layout_width">@dimen/fab_width</item>
       <item name="android:layout_height">@dimen/fab_height</item>
       <item name="android:background">@drawable/fab_background</item>
       <item name="android:layout_alignParentBottom">true</item>
       <item name="android:layout_alignParentRight">true</item>
       <item name="android:layout_marginBottom">@dimen/fab_margin</item>
       <item name="android:layout_marginRight">@dimen/fab_margin</item>
       <item name="android:stateListAnimator">@anim/rise</item>

    </style>

</resources>


text:
Q: Blank space between main and footer Screenshot of the problem
Hey,
I have a problem, there is a lot of blank space between the main section and the footer. How do I fix this?
I tried to add padding and margins but that didn't helped. I also looked it up on the internet of course, and I found out that every HTML and CSS is different, so that's the reason that I ask it again.

footer {
  position: absolute;
  width: 100%;
  height: 30px;
  background-color: lightblue;
}

html,
body {
  overflow-x: hidden;
}

@media only screen and (max-width: 480px) {
  html,
  body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow-x: hidden;
  }
}

.container {
  position: relative;
  display: flex;
  align-items: center;
  margin: 0;
}

.text-block {
  position: relative;
  bottom: 300px;
  background-color: #ffffff;
  opacity: 0.8;
  color: blue;
  padding-left: 20px;
  padding-right: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;
  font-size: 20px;
  text-align: center;
}

#footer-tekst {
  position: relative;
  top: 5px;
  left: 8px;
}

#footer-link {
  position: relative;
  float: right;
  margin-right: 20px;
  bottom: 15px;
  color: black;
}

```

Home

Over ons

Contact

Account

Doe mee!

Schoon is cool: help mee om ons wereld een stukje beter te maken!

2023 © Colossal Recycle

Algemene voorwaarden

Privacy policy


text:
Q: Webpack config node_modules outside dist I'm trying to find the best solution for my project setup:
At the moment my folder structure look like this:

*

*dist

*node_modules

*src

*|- components

*|- styles

*|-- app.scss

My Webpack config works and compiles everything from 'src' to 'dist'.

*

*I'm going to deploy content of 'dist' to the server so should I move node_modules inside 'dist' with webpack when I run build?

*My app.scss reference dependencies from node_modules so if I move node_ modules inside 'dist' I will have to change paths in scss? How to do it?

*The same issue with index.html and dynamic paths...

Is this the best practice?
Thanks

A: When you compile everything with Webpack, it imports the parts needed from the node_modules inside your compiled code. So the files outputted in your dist folder are "standalone". You don't need your node_modules anywhere except when you develop.
Regarding your app.scss, it will be transformed into CSS and node_modules @imports will be integrated inside your app.css.


text:
Q: How would I convert a macOS IPSW to a macOS Installer app? I've been messing around on the internet looking for the older, first Big Sur installers and I've come across an IPSW for macOS Big Sur 10.16 (20A5299w), the first arm64 build of macOS that only shipped with the Development Transition Kit macs. As far as I know, no "Install macOS app" exists for this build.
My question: Is it possible to convert that IPSW to a working macOS Installer app? How?
Theoretically, IPSWs have enough data to be used as restore files for machines, so I wouldn't doubt if it was possible to make an installer app out of it. I don't have one on hand right now (I deleted it), but I recall a 12 GB DMG file that essentially has a copy of "Macintosh HD", or what a drive looks like with macOS installed (nothing else). It also has another DMG file with what I presume was the Base System (had 12 MB Installer app I could use).
This only really matters when you have the IPSW, but not the corresponding macOS Installer app, but even then, when would a mac need a version so specific? - I'm mostly interested to see if it's possible...


text:
Q: When upgrading IIS a 800a0001 Request.BinaryRead fails When a IIS was upgraded to IIS 6.0 or higher, large files (specifically larger than 204,800 bytes) uploaded via ASP get the following error:

error '800a0001'
Request.BinaryRead failed

What will fix this error?

A: By default IIS6 limits the file upload side to 204,800 bytes.  To increase this maximum size edit the metabase file entry: AspMaxRequestEntityAllowed.
Set the value to the maximum size you want to allow.
ex (for a maximum of one gig):
AspMaxRequestEntityAllowed = "1000000000"

(Thanks to Internet Software Services)


text:
Q: How to pass data "controller" instead of "app.js" in Nodejs I am working on Nodejs(Express.js),I am sending Form data to controller but not working for me,I am getting error "TypeError: Cannot read property 'name' of undefined in Nodejs", But Main problem is my code is working/getting data in "app.js" but i want to get data in "userController" because i want to use MVC strtucre,Here is my root.js
var express=require('express');
var router= express.Router();
var controllers= require('../controllers');
router.get('/', controllers.homeController.index);
router.get('/signup', controllers.userController.signup);
router.post('/signup', controllers.userController.save);
router.get('/login', controllers.userController.login);
router.get('/dash', controllers.userController.dash);
module.exports = router;

Here is my userController.js file
userController.save = function (req, res, next) {
    var name = req.body.name;
    console.log(name);
}

Here is my app.js, How can i get data in "userController" instead of "app.js",Thank you in advance.
const express = require('express');
const mysql = require('mysql');
const expressValidator = require('express-validator');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', routes);
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(__dirname + '/public'));
app.use(cookieParser('keyboard cat'));
const PORT = 4000
app.listen(PORT, function (err) {
  if (err) console.log(err);
  console.log("App started on PORT", PORT);
});

A: I have reorganized your codes. Please make sure your filte path declaration is correct.
    var express=require('express');
    var router = express.Router();
    var controllers= require('../controllers/userController'); // if userController.js in controller folder.
    router.get('/', controllers.homeController_index);
    router.get('/signup', controllers.userController_signup);
    router.post('/signup', controllers.userController_save);
    router.get('/login', controllers.userController_login);
    router.get('/dash', controllers.userController_dash);
    module.exports = router;

userController.js
const userController_save = function (req, res, next) {
    var name = req.body.name;
    console.log(name);
}

app.js
    const express = require('express');
    const mysql = require('mysql');
    const expressValidator = require('express-validator');
    const bodyParser = require('body-parser');
    const cookieParser = require('cookie-parser');
    const session = require('express-session');
    const flash = require('connect-flash');
    const path = require("path");
    const app = express();

    const routes = require('./routes/root'); // If your root.js inside a routes folder

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());

    app.set('view engine', 'pug');
    app.set('views', path.join(__dirname, 'views'));
    app.use(express.static(__dirname + '/public'));
    app.use(cookieParser('keyboard cat'));

    app.use('/', routes);

    const PORT = 4000
    app.listen(PORT, function (err) {
      if (err) console.log(err);
      console.log("App started on PORT", PORT);
    });


text:
Q: I dont know how to go out from the loop When I press this button:
case R.id.btlento:
    Timer timers = new Timer();
    timers.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        cameraOn();
    },deloy1,poriod1);
        Timer timers2 = new Timer();
        timers2.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            cameraOff();
        }
    },deloy,poriod);

The methods cameraOn and cameraOff are:
private void cameraOff() {
    // TODO Auto-generated method stub
    parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
    camera.setParameters(parameters);
    camera.release();
    camera = null;
}

private void cameraOn() {
    // TODO Auto-generated method stub
    camera = Camera.open();
    parameters = camera.getParameters();
    parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
    camera.setParameters(parameters);
}

and the variables are:
int deloy = 2000;
int poriod = 2000;
int deloy1 = 1000;
int poriod1 = 2000;

All this is to make the camera flash blink, but I don't know how break the loop, because never stops.
How can i stop the loop?

A: Use a flag,
// member variables

private boolean cameraIsFlashing = false;
private Timer onTimer;
private Timer offTimer;

// constructor & other stuff

// button click method
case R.id.btlento:
     toggleCameraFlash();
   break;

private void toggleCameraFlash(){
    if(cameraIsFlashing){
        stopFlashing();
    } else {
        startFlashing();
    }
}

private void startFlashing(){
  cameraIsFlashing = true;
  // Start your timers
  onTimer = new Timer();
  onTimer.scheduleAtFixedRate(new TimerTask() {

  @Override
  public void run() {
      cameraOn();
  },deloy1,poriod1);
}

private void stopFlashing(){
  cameraIsFlashing = false;
  // Cancel / Stop your timers
  onTimer.cancel;
}

A: call cancel() and purge() on thread timer to stop the thread.
as shown below.
private void cameraOff() {
// TODO Auto-generated method stub
if(timer != null){
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;

timer.cancel();// cancel and releases
timer.purge();
}
}

A: Make a variable for timer task instead of using anonymous class. First cancel timer task then cancel timer.


text:
Q: How to scroll a nested scroll view programmatically I am using AppBarLayout and NestedScrollView inside a CoordinatorLayout to have CollapsingToolbar effect in my app. My problem is to display the imageview 40% initially and once user scroll down i need to expand the imageview to display full image(Like Whatsapp Profile).
I have tried below links for reference.
Programmatically scroll to the top of a NestedScrollView
top-of-a-nestedscrollview

Here is the xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleMarginEnd="50dp"
        app:expandedTitleMarginStart="35dp"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/userProfilePicture"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:scaleType="centerCrop"
            app:layout_collapseMode="parallax"
            app:layout_collapseParallaxMultiplier="1.0"/>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:id="@+id/nestedScroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Dr Srikant Reddy"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"/>

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp">

            <LinearLayout
                style="@style/Widget.CardContent"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Info"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/cheese_ipsum" />

            </LinearLayout>

        </android.support.v7.widget.CardView>

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>


text:
Q: MUI Form Control Label to display label only on the first index I'll like to display a label only on the first index. So in a way it looks like the title is on the top of all the checkbox.

I know that I can move it to the top by using the labelPlacement="top".
In my case, the chekbox are in a for loop so I can add more with a click, but I'll like to limit it to the first only and display title on top of it like on the image.
<FormControlLabel
              label="Title"
              labelPlacement="top"
              control={
                <Checkbox ...

I have tried adding the labelPlacement on top and tried to combine both label and labelPlacement prosp to make it work together. Since what I am trying to achieve is for the only the first index to have title and the rest to be label="".


text:
Q: Get empty response data when variable not defined I try to use following code to check response of a HTTP Request, which is called from another Thread Group by a Module Controller.
File myfile = new File(FileServer.resolveBaseRelativeName("results/" + filen + "-report.xml"));

if(${__isVarDefined(vars.get("myvar"))} == true){
        FileUtils.writeByteArrayToFile(myfile,bytes);
} else {
        FileUtils.writeStringToFile(myfile, prev.getResponseDataAsString(), "UTF-8");
}

Empty xml is created when myvar variable is empty, it doesn't contains response data of request.

A: You can write byte[] in both cases using getResponseData() (and removed function call)
if(vars.get("myvar") ! null){
    FileUtils.writeByteArrayToFile(myfile, bytes);
} else {
    FileUtils.writeByteArrayToFile(myfile, prev.getResponseData());
}

A: *

*You cannot use vars shorthand to retrieve values from the different Thread Group as JMeter Variables are local to the Thread hence they cannot be accessed from another Thread Group. You need to use props instead. See the documentation:

Properties are not the same as variables. Variables are local to a thread; properties are common to all threads, and need to be referenced using the __P or __property function.

*Don't inline JMeter Functions or Variables in Groovy scripts, if you need to check whether variable is defined or not - attempt to get it and see if it is null:
if (vars.get('myvar') != null) {
    //the code will be executed if the var is defined
}

Check out Transferring Data and Objects (like List, Maps, Array etc.) Between Samplers and Threads chapter of The Groovy Templates Cheat Sheet for JMeter for more details.

In the absolute majority of cases it's easier to use Inter-Thread Communication Plugin


text:
Q: как поставить содержимое Bootstrap по центру?

Choose your language

RUS

ENG

GER

UKR

KZ

JP

CN

*

*Может в Bootstrap есть класс, который может отцентрировать всё содержимое?

*Как лучше сделать выбор языков на сайте? Что использовать? JavaScript или jQuery?

A: Вопрос не понятен. Да, в бутстрап есть такой класс, и вы его используете. Но пример не доверстан и не воспроизводим относительно вашего скрина, ваши стили не дописаны, бутстраповские не подключены, зачем-то подключены скрипты, хотя они в примере не имеют никакого значения. + есть не закрытый див:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Choose your language

RUS

ENG

GER

UKR

KZ

JP

CN


text:
Q: Identifying the most representative observation in a sample Given a multidimensional X, is there a standard way of identifying the most representative observation? A few options come to mind:

*

*Minimum average distance (e.g. cosine, Mahalanobis) from all other observations.

*Minimum distance from multidimensional center of sample (for certain distance measures I think this would be equivalent to (1)).

*Maximum centrality (e.g. PageRank) from a social network analysis, where edge weights are inverse to some distance measure.


text:
Q: If $n$ is a prime power, is there an isomorphism between $Z_n [x] /f_1$ and $Z_n [x] /f_2$? Suppose $n =p^r$ is not prime and $Z_n$ is a ring.
Consider two irreducible polynomial $f_1$ and $f_2$ of degree $d$ over $Z_n$.
Can we find an isomorphism between $Z_n [x] /f_1$ and $Z_n [x] /f_2$ ??
I think that is impossible, However that is only feel.
Thanks.

A: If $n$ is not a prime, then the ring $\mathbb{Z}/n\mathbb{Z}$ is not an integral domain, so $(\mathbb{Z}/n\mathbb{Z})[x]$ is not either. Unfortunately, it's unclear what "irreducible element" means in a ring that is not an integral domain - look on Wikipedia.
However, perhaps an example such as the following would still be satisfactory to you: let $n=4$, and let $f_1=1+x$ and $f_2=1+3x$. Then
$$(\mathbb{Z}/4\mathbb{Z})[x]/(f_1)\cong\mathbb{Z}/4\mathbb{Z}\cong(\mathbb{Z}/4\mathbb{Z})[x]/(f_2)$$


text:
Q: Is using a const method from one object thread safe? I am not sure if this is a duplicate, I have looked through many posts but they do not seem to be close enough to my question.
I want to use a const method from one object to change other objects concurrently. The program basically needs me to move a particle under the influence of gravity and I want to run this in parallel for all particles.  I made a physics class and in that class I have a const method to move a particle object.
Here are some example classes to understand me better.
/**
 * Particle.h
 */
#ifndef __Particle__sim__
#define __Particle__sim__

class Particle {
  private:
    double height;
    double velocity;
  public:
    const double getHeight() const;
    const double getVelocity() const;
    void setHeight(const double&);
    void setVelocity(const double&);
};

#endif

/**
 * Physics.h
 */
#ifndef __physics__sim__
#define __physics__sim__

#include <thread>
#include <vector>

#include "Particle.h"

class Physics {
  private:
    double gravity;
    double timeStep;
    void moveParticle(Particle&, const double) const;

  public:
    Physics(const double g, const double t);
    void moveParticles(std::vector<Particle>&, const double) const;
};

#endif

/**
 * Physics.cpp
 */
#include "Physics.h"

using namespace std;

Physics::Physics(const double g, const double t) : gravity(g), timeStep(t) {}

void Physics::moveParticle(Particle& particle, const double time) const {
  // move particle under gravity
}

void Physics::moveParticles(vector<Particles>& particles, const double time) const {
  vector<thread> threads;
  threads.reserve(particles.size());

  for (auto& p : particles) {
    threads.push_back(thread(Physics::moveParticle&, this, std::ref(p), time));
  }
  for (auto& t : threads) {
    t.join();
  }
}

Here is essentially my main
/**
 * main.cpp
 */

#include <vector>

#include "Physics.h"
#include "Particle.h"

using namespace std;

int main() {
  vector<Particle> particles;
  // insert 100,000 particles

  Physics physics = Physics(-9.81, 0.01);

  physics.moveParticles(particles, 5.0);

  return 0;
}

So is physics.moveParticle(Particle&, const double) thread safe here?
Short & Sweet:
I want to use a method from one Physics object to make multiple threads to move all the Particles in my program and I am not sure if the const method I wrote is thread safe. I can't see why not but I can't justify it.

A: At first sight, this should be thread safe.
We need to see the implementation of Particle::setHeight to be absolutely sure. What if it did something like write to a global array? Which would be silly but we can't tell for sure.
However, your Particle looks very simple. What would be even more thread safe is to not mutate it at all. Make them immutable and create a new one with each calculation.
You can still change them by assigning the new Particle back to the old Particle.
However if you really want to get into threading, a great technique here is to have two world states: previous and next. These swap with each update step. Each update step reads from previous and writes into next. This lets other threads like graphics display read from previous without constantly locking on little things like Particles.
With that, a immutable Particle does not slow anything down at all. In fact, the compiler will rewrite the machine code for nextParticles[i] = updateParticle(prevParticles[i]) into direct assignments to its final position in memory. That's RVO or NRVO.

A: It looks thread-safe to me.  In particular, if the only (non-immutable) data read or written by each of the spawned threads is the thread's own corresponding Particle object, then there is no shared data as far as the threads are concerned.  (The Physics object itself is shared, of course, but since you are not modifying the Physics object during the sub-threads' lifetime, the Physics object is effectively immutable/read-only during the operation, and any read-only access to the Physics object by the spawned threads will not be a source of race conditions)


text:
Q: Get object with specific value in ID variable I'm reading a CSV file and creating objects based on the values on each line. I can't really name each object something unique so I do:
new User(x, y, z);

But how can I then find that newly created object? Is there a way to loop through all objects of a specific class (i.e. User)? Or at least find one based on the ID? (e.g. user(1))
In SQL I could simply
select * from X where ID=1

but how can I do this in Java after creating several nameless objects based on the data parsed from a text file?

A:
Or at least find one based on the ID?

You have an identifier by created User?
So you should just store the objects in a Map where the key is the User id and the value is the User object.
With an Integer as id, it would give :
Map<Integer, User> usersById = new HashMap<>();

for (...){
   usersById.put(userId, new User(userId, x, y, z));
}

Then you can retrieve the user in this way :
User user = usersById.get(1);

A: First, store the objects into a list.
List<User> usersList = new ArrayList<>();
...
...  // add each object to usersList

Later on, to imitate your SQL query, you can do something along the lines of:
Optional<User> result = usersList.stream().filter(x -> x.getId() == 1).findFirst();

This solution assumes you have an id field within your User class and a getter called getId().
reading
 - Optional<T>.


text:
Q: Uncaught (in promise) DOMException: Failed to execute 'texImage2D' on 'WebGL2RenderingContext': Tainted canvases may not be loaded '''

<meta charset="UTF-8">

'''

Above is html file using which I am trying out posenet from tensorflow js.
Following is the error which I received when I tried to open the above file in google chrome.
Uncaught (in promise) DOMException: Failed to execute 'texImage2D' on 'WebGL2RenderingContext': Tainted canvases may not be loaded.
at https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:176404
at qt (https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:55726)
at vi (https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:176377)
at t.uploadPixelDataToTexture (https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:181200)
at Object.kernelFunc (https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:480876)
at h (https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:42226)
at https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:42907
at t.scopedRun (https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:40845)
at t.runKernelFunc (https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:42726)
at t.runKernel (https://cdn.jsdelivr.net/npm/@tensorflow/tfjs:2:41280)

Following is the error when the html file is opened in firefox
'''
SecurityError: The operation is insecure.
Source map error: Error: request failed with status 404
Resource URL: https://cdn.jsdelivr.net/npm/@tensorflow/tfjs
Source Map URL: tf.min.js.map
'''

I am a beginner and I am not able to understand the above error. I am trying to get the pose coordinates from the console in the browser but I just keep getting this error.
Any help would be appreciated and thanks in advance.

A: crossorigin='anonymous' needs to be added to the image tag

  <meta charset="UTF-8">

To use an image locally, the image needs to be served by a server allowing cors. http-server can be used with the command line
http-server -c1 --cors .

    <meta charset="UTF-8">

A: I was having the same problem with my react app and tensorflow.js but i only realised that i was missing the crossOrigin prop or attribute as edkeveked mentioned. So i solved my problem by modifying the img tag and put the attribute or property crossOrigin  as follows:

edkeveked's answer is the best
Good luck ✔✔✨✨


text:
Q: Do Android proxy settings apply to all apps on the device? If you set up proxy settings for an android device, do they apply to all apps on the device including the browser? Or do they only apply to the browser?
The reason I ask is that when you go to change the proxy settings on an android device there is this message, and it is confusing me:
"HTTP proxy use by browser but may not be used by other applications"

A: No, they do not apply globally and without root there is no way to force a proxy to be used by all applications. The reason the message you found is worded that way is that it is up to the app creator to respect the proxy settings and use them or do the wrong thing and ignore them.
If you happen to be rooted, you can use this app which will apply the proxy settings to all apps and activities.
The reason that this is not the default behavior is because it could present some security risks. If all traffic could be redirected, users could have all of their traffic be going through some bad proxy server that snoops on them so they default to only allowing apps to use proxy if they explicitly ask for it.

A: Not sure what apps will or won't use the proxy. I have a couple of Android apps and they ignored it.
I got around this by using an app called drony, which doesn't require the device to be rooted. I have a few apps and they all happily proxied to drony without having to do anything to the app. I then set drony to proxy to fiddler on my local machine. Instructions to set this up are all here:
Setup global proxy in your android device without rooting!

A: as Julian said, some apps or SDKs inside apps are not Proxy aware.
I experienced this first hand with an SDK.  I couldn't understand why it was not showing up my Burp tool. I eventually found out that it was proxy unaware.
As Julian said, you can use an Android app to fix this. An alternative - I used - invisible proxying.  Have a look at: https://portswigger.net/burp/help/proxy_options_invisible.html

A: Try postern. It redirect all the traffic to a local vpn and support:

*

*SSH Tunnel

*Shadowsocks

*SOCKS5 Proxy

*HTTPS/HTTP CONNECT

You can find it here:
https://play.google.com/store/apps/details?id=com.tunnelworkshop.postern
and more similar apps like it here:
https://android.izzysoft.de/applists.php?topic=cat;id=109

A: If you change the proxy settings via Wifi->Settings->Proxy(Manual) , as informed by your device, it is clearly not possible to apply in all applications. Despite this, it is possible to achieve the result, without rooting your device, with the Drony application.
Drony is being updated until today (23 Jan 2023) and even allows filtering urls as desired.

*

*Before opening Drony, configure your wifi network and set the proxy hostname to localhost and the port to a free one like 2000.

*Download Drony from the playstore and accept all permissions required for its use;

*In the settings tab, change the proxy port to the port defined in step 1 2000;

*Under Networks, click Wi-Fi, select the network you configured the port on in step 0.

*Change hostname, port, username, and other settings as desired.

*Go back to the Log tab, click On and that's it!

You can check filtered connections in the FILTER tab and connections in the CONNECTIONS tab.
Good luck fellas!

A: This isn't correct. Nearly all apps will respect HTTP proxy settings. Xamarin.Android often doesn't but you can override this in your webclient.
PS: If this fails you can use wireshark in all cases to do this.


text:
Q: Why is there a 4-layouts limit for keyboards? I just discovered that I couldn't add more than 4 layouts for my keyboard. Googling revealed that it was a universal limit (at least for GNU/Linux) and the only way(s) to get around it was to use some hackish way with scripts. Is there really a technical reason behind this? If yes, what is it?

A: I frequently write in English, German, Swedish and Chinese.  This is four, but I am learning Russian as well and would appreciate the extra toggle via the GUI.  Scripts is a workable resolution in the meantime:
http://ubuntuforums.org/showthread.php?p=10333055#post10333055
One might note that with Russian, one has the option of either the 'standard' Russian keyboard layout, or a much more convenient (for those of us learning) phonetic layout paired to QWERTY.
Also, many of us use some form of Dvorak, which also takes a position.
Hence, my computer looks like this:
Keyboard layouts:
USA
Dvorak (programmer)
Swedish
German
Russian
Russian phonetic
and there is an additional keyboard icon with an ibus toggle for Chinese Pinyin.

A: Quoting Peter Hutterer (Red Hat employee working on X.Org):

Some information about this feature and why it hasn't been implemented yet:
  Te 4 group limit is forced by the protocol wire format. support for more than
  4 groups can only be added by adding additional requests and events to XKB and
  rewriting clients to switch to this new XKB version.
  In addition, compatibility to the old protocol must be ensured so that current
  XKB clients will still function correctly with the new XKB version.
This is both complex and very time-consuming. Volunteers to tackle this problem
  are of course very welcome.
[...]
It's encoded in some bits on the protocol, with the other bits being used for
  other information. so you need extra bytes in the requests/events for anything
  above 4, and adding extra bytes requires bumping the protocol. And then you
  have to deal with those clients that only understand 4 groups and what to do
  with them if a keyboard is on group 5.

Why we don't have a hack above this layer - I don't know... this must be the lamest limitation ever. :D

A: The protocol sets aside two bits for keyboard switching.  This is two more than many people need.  Most of the users I have seen switching keyboard layouts use two; a local layout and and international layout.  The international layout usually handles composition of all require keys.  This leaves one excess bit.  I have seen users with three layouts, but usually one is never used.
I would be interested in what you are doing that requires more than four layouts, and how you work with constantly changing keymapping.  I find it difficult to get users used to two layouts, even when it solved problems they have with internationalization.


text:
Q: How to return a matchCollection from function in Visual Basic, Excel I'm trying to return a matchCollection from a function to be able to loop through my matches and write them to excel cells outside the function.
I get the run-time error 91: Object variable or With block variable not set, when my code comes to:
If matches1.Count <> 0 Then
This is my code:
Sub simpleRegex()

  Dim ShortRange As range
  Set ShortRange = ActiveSheet.range("A2:A505")
  Dim strInput1 As String
  Dim matches1 As MatchCollection

  For Each cell In ShortRange

    strInput1 = cell.Value

    Set matches1 = CheckMatch(strInput1)

    If matches1.Count <> 0 Then
        cell(1, 3).Value = matches1(0).SubMatches(2)
        cell(1, 4).Value = matches1(0).SubMatches(3)
    End If

  Next

End Sub

Public Function CheckMatch(str As String) As MatchCollection

  Dim strPattern1 As String
  Dim strInput As String

  Dim regEx As New RegExp
  Dim matches As MatchCollection
  Dim Match As Boolean

  Match = False

  strPattern1 = "((storlek|strl|stl|strlk|storleken|storl|size|storleksmärkt|storl|storlk|st).{0,2}?(?:[^\s]+)?.{0,2}?)?(30|32|34|36|38|40|42|44|46|48|50).?(30|32|34|36|38|40|42|44|46|48|50)?"

   strInput = str

   With regEx
     .Global = True
     .MultiLine = False
     .IgnoreCase = True
     .Pattern = strPattern1
   End With

   If regEx.test(strInput) Then
     Match = True
     Set matches = regEx.Execute(strInput)
   End If

   Set CheckMatch = matches

End Function

Anyone who knows how this can be fixed?


text:
Q: iOS 9 New Launch Images and Icons Sizes, has anyone found the new sizes for the upcoming devices yet? For iOS 9 has anyone been able to discover what the new launch image and icon sizes will be for the new upcoming iOS devices?
I checked the Human Interface Guidelines but they have not listed anything yet https://developer.apple.com/library/prerelease/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html#//apple_ref/doc/uid/TP40006556-CH27-SW1
In Xcode 7 I tried adding a new asset catalog in hopes of discovering them but that was without success.
I'm not sure when we found out the sizes for the iOS 8 releases new iPhone 6 and 6+ but I thought we knew them around early August last year. Maybe there are no new icons to be made this year.

A: There are new icons for the iPad Pro and new splash screens as well. For the iPad pro you will now need an App Icon 167x167 and 2 splash screens measuring:
2048 x 2732 (portrait)
2732 x 2048 (landscape)
They just updated the doc at:
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html


text:
Q: Javascript: how can I append variables to the url? how can I append variables to an URL with javascript without navigating to the url ?
thanks

A: To append variables to the hash (as Matthew suggested), you can do the following in plain JavaScript:
window.location.hash = 'varA=some_value;varB=some_value';

This will add #varA=some_value;varB=some_value to your URL. It will not refresh the page unless the hash value is equal to an anchor name or an element id within the document.
Then to check if a hash value is present, simply do the following:
var i, variables = window.location.hash.split(';');

if (variables.length > 0) {
    // Variables present in hash
    for (i = 0; i < variables.length; i++) {
       keyValuePair = variables.split('=');
       // keyValuePair[0] would be the key (variable name)
       // keyValuePair[1] would be the value
    }
}
else {
    // No variables in the hash
}

You may also want to check out the following Stack Overflow post on issues related to the URL encoding of the hash part in different browsers:

*

*Encoding of window.location.hash

A: You can modify window.location.hash.  Anything else will cause a navigation.

A: I am not sure about that, but how is it with this?:
document.url + myVar + 'myString';

Though Javascript is not my language :P


text:
Q: Using two sets of conditions in where clause I'm trying to get the count of items in my table where it should satisfy these conditions
status = active
type = Pre-order
date = $date_input

OR

status = active
type = Both
date = $date_input

I'm trying to use this statement but I'm pretty sure it's messed up.
SELECT COUNT(id) as count_date from date_restriction
where (date='$date_input' AND status='active' AND type='Pre-order')
OR (date='$date_input' AND status='active' AND type='Both')

I also tried this to no avail
SELECT COUNT(id) as count_date from date_restriction
where date='$date_input' AND status='active' AND type='Pre-order' OR type='Both'

A: Whe  you have mixed AND and OR condition you need () for the or clause
SELECT COUNT(id) as count_date
from date_restriction
where date='$date_input'
AND status='active'
AND ( type='Pre-order' OR type='Both')

or instear of several or condition you could use a IN clause
 AND  type IN ('Pre-order', 'Both')

anyway you should avoid the use of php var in SQL you are at risk for sqlinjection .. for avoid this you should take a look  at prepared  statement and binding param for your db driver

A: Your code should work.  I would write this as:
select count(*) as count_date
from date_restriction
where date = ? AND status = 'active' AND
      type in ('Pre-order', 'Both');

Note:  The ? is for a parameter so you are not munging the query string with input values.
If I had to guess why this isn't working, I would speculate that one or both of the dates have a time component.  You might try:
where date(date) = date(?) . . .

to be sure you are matching on the date, regardless of time.

A: SELECT count(id) as count_date
FROM date_restriction
WHERE date='$date_input' AND status='active' AND (type='Pre-order' OR type='Both');
Here, date and status both fields are common in your case; hence, don't wrap it in parenthesis whereas, add OR condition for type field only and con-cat it with AND in WHERE clause.


text:
Q: Moving MongoDB shards from one server to another I have a new server on which i have to copy the old version of the MongoDB already configured. On the old server(3.0.4), there are two shards: one shard has 350GB, and the other has 300GB of data.
I followed the following steps:

*

*Installed MongoDB 3.0.15 on new server

*Copied the data from two shards to the new server

*then ran the following commands
mongod    --configsvr --dbpath C:\mongoConfigData/configdb1 --port 27019
mongod    --configsvr --dbpath C:\mongoConfigData/configdb2 --port 27020
mongod    --configsvr --dbpath C:\mongoConfigData/configdb3 --port 27021

mongos    --configdb 127.0.0.1:27019,127.0.0.1:27020,127.0.0.1:27021 --port 27017

mongod    --dbpath F:\data --storageEngine wiredTiger --wiredTigerJournalCompressor zlib --wiredTigerCollectionBlockCompressor zlib --port 27010

mongod    --dbpath D:\data --storageEngine wiredTiger --wiredTigerJournalCompressor zlib --wiredTigerCollectionBlockCompressor zlib --port 27011

*Added the shard and the shard collection details
sh.addShard("localhost:27010")
sh.addShard("localhost:27011")
sh.shardCollection("log", {"id" : 1, "eventId": 1})

Shard distribution shows both the shards but the total docs and the collection size does not match the one in the initial server.
Further the content in the mongodb is not the complete data
Why is it so? What am i doing wrong?

A: You are not copying the contents of the config servers and effectively creating a new sharded deployment rather than restoring a backup of an existing one. Config servers include essential information about where data lives in a sharded deployment, so you must backup & restore the config server data along with the shards.
Note: there have been changes to sharded cluster configuration in successive releases, so make sure you are using documentation for the correct MongoDB release series. The links below are specific to MongoDB 3.0.
For supported backup approaches see the MongoDB 3.0 Backup & Restore a Sharded Cluster tutorials.

sh.addShard("localhost:27010")
sh.addShard("localhost:27011")

If you've restored a sharded cluster from a backup, the shards will already be configured. If host names have changed from the original deployment, you will need to update the config.shards information  via a mongos rather than adding new shards (and then restart the mongod instances in your sharded cluster to ensure the new names are used). See the MongoDB 3.0 Restore a Sharded Cluster tutorial for more specific details.

sh.shardCollection("log", {"id" : 1, "eventId": 1})

If a sharded cluster is already configured,  sharding an existing sharded collection will return an error. Since you ran this command starting from fresh config server data, the sh.shardCollection() command will be unaware of how existing data is distributed on the shards and assume that the primary shard for a database with an unsharded collection has the full range of data.


text:
Q: Property 'jumpservice' does not exist on type 'PaperDocuments'
*

*I am new to angular 2 and typescript.

*I am facing the below erros in my code.

*I googled for the error and they asked to include the import statements.

*but still the error is not going.

*can you guys tell me how to fix it.

*providing code and error below.

*am I missing something

*i tried all the possible solutions

///<reference path="../../../assets/js/jquery/jquery.d.ts" />
import {NgModule, CUSTOM_ELEMENTS_SCHEMA,Component, ElementRef, Inject, OnInit, ViewChild} from '@angular/core';
import {Http,HttpModule, Response,Headers, RequestOptions } from '@angular/http';
import {KendoGridComponent} from '../grid/grid.component';
//import { TranslateService } from '../../translate/translate.service';
import { SPORTSService } from '../../services/sports.service';
import {jumpService} from '../jump/jumpService';

import { FormsModule }   from '@angular/forms';
import {Observable} from 'rxjs/Rx';
declare let $:any;

@Component({
    selector: 'PaperDocuments',
    template: `<div id="windowcontainer"></div>`
})

export class PaperDocuments {

    @ViewChild(KendoGridComponent) private gridmobile: KendoGridComponent;
    private dataSourceVal;
    private MainGrid;
    private grid;
    private isVisible = false;
    public toggleCollapse : string;
    private kPopUpWindowViewHistory;
    private fileName;
    private scrollClicked;
    private dynamicnetwks;

        /*Localization*/
    public show: string;
    public all: string;
    public entries: string;
    public cancelBtn: string;
    public okBtn: string;
    public attachBtn:string;
    public elfBtn: string;
    public browseBtn:string;
    public dragDrop: string;
    public clearBtn:string;
    public attachmentType:string;
    public fileSelect:string;

    private Type = ["PRM", "STR","FRT", "Urban Legends"];
    private isDone: boolean = true
    private filesToUpload: Array<File>;
    private files = [];
    private url = "http://localhost:3002/upload";
    private dialogCommand;
    public encodeBase64:any;
    public isContractLocked=false;
    private loggedUserName;
    private documentType='';
    public elfDocIDTemp;
    public openFlag = false;
    private selectedoptions;
    //private fileSelected = false;

    private mobilecommand = {
        edit: {
          createAt: "bottom"
        },
        group: true,
        reorder: true,
        resize: true,
        sort: true,
        autoBind: false,
        filter: {
          mode: "menu"
        },
        pager: {
          messages: {
            display: "Showing {0} to {1} of {2} entries"
          }
        },
        model: {},
        columns: [],
        pagesize: 50,
        getComponentUrl: "jumps/v1/jumps/35355?includes=payments",
        postComponentUrl: "jumps/v1/jumps/35355?includes=payments",
        excelfileUidName: "ViewPaymentExport",
        isLevels: false,
        excelFileName: {
          fileName: "ViewPaymentExport",
          allPages: true
        },
        contextMenuId: "context-menuAllocation",
        navigate: false,
        data: "",
        mandatoryFields: [],
        disableFreeze: true,
        searchFields: [],
        defaultSort: []
     };

    constructor(public sportsService : SPORTSService ){

    }

    ngOnInit() {

        this.documentType='Contract';
        this.privilegeSettings();

        let that=this;

        this.jumpservice.reloadDocumentEventReceived.subscribe(documents=>{
                that.documentType="Contract";
                $('.addELFDocumentForm').hide();
                that.isDone = true;
                that.dragDrop= that.clearBtn;
                $("#attachDocumentBrowseBtn").val('');
                if(documents.isReLoad){
                    this.mobilecommand.getComponentUrl='jumps/v1/jumps/'+documents.data+'?includes=documents';//
                    that.gridmobile.getServiceCall(documents.data);

                }else{
                that.rowDotMenuClick({"selectedMenuItem":"setData","type":"normalService","data":documents.data});
                }
        });

        this.mobilecommand.model={
                id: "documentId",
                fields: {
                    contextRow:{editable:false,filterable:true},
                    docId:{editable:true,filterable:false,sortable:false},
                    documentName: { editable: false, nullable: true },
                    //elfDocID: { editable: false, nullable: true },
                    elfDocID: {
                    validation: {
                        required: true,
                        digits:true
                    }
                },
                    url: { editable: false, nullable: true },
                    documentType: { editable: false, nullable: true },
                    date: { editable: false, nullable: true }
                }
        };

        this.mobilecommand.columns=[
                                {
                                    field: "contextRow", width: 25, title:" ",
                                    template:""/*''*//*""*/
                                },
                                {
                                    field: "docId", width: 25, title:" ",sortable:false,
                                    /*template:""/*,*/

                                    template: function name(model) {
                                        return that.ImageType(model);
                                    },
                                    editor:function (container,model){
                                        that.docTemplateEditor(container,model,that);
                                    }
                                }
                            ];

    }

    privilegeSettings():void{
        let userPrivilege = this.sportsservice.getUserPrivilege({"parent":"Contract Management","child":"Documents"})
        if(userPrivilege == "Full"){
            this.isContractLocked = false;
        }else{
            this.isContractLocked = true;
        }
    }

    running(values):void{
        let that = this;
        $("#windowcontainer").append(`

Documents

                        <button class="clearBtn triggerKPopUpClickViewHistory" type="button" id="closePopup">CLOSE</button>

                BROWSE{{browseBtn}}

`);

        let viewHistoryPopUpGrid =[];

        that.dataSourceVal = new mobile.data.DataSource( {
            transport: {
                read: function(e) {
                    e.success(viewHistoryPopUpGrid);
                }
            },
            sort: true,
            group: [{field: values.group}]
            //ignoreCase: false //<--ignore the casing will stop applying .toLowerCase()
        //  filter: "gte" //<-- filter operator compliant with `number` type
        });

        that.MainGrid = {
            dataSource: that.dataSourceVal,
            reorderable:true,
            sortable: true,
            filterable: {mode:"row, menu"},
            dataBound:function(e){
               let   gridDataSource = e.sender.dataSource;
               console.log('history',e)
                    if (gridDataSource.group().length > 0) {
                        $("#collapseBtn123").removeClass('actionDisabled')
                    }else{
                        that.toggleCollapse="COLLAPSE ALL";
                        $('#collapseBtn123').text(that.toggleCollapse);
                        $("#collapseBtn123").addClass('actionDisabled')
                    }
              },
            groupable:true,
            editable: false,
            columns: values.columns,
            pageable:{messages: {display: "Showing {0} to {1} of {2} entries"}},
            pageSize:50,
        };

        that.kPopUpWindowViewHistory = $("#viewHistoryPopUpWindow");

        // $("#closePopup").click(function(){
        //  that.closePopup();
        //  console.log("click");
        // });

        // $("#collapseBtn123").click(function(){
        //    that.collapseBtn();
        // });

        that.kPopUpWindowViewHistory.mobileWindow({
                        width: "80%",
                        title: false,
                        visible: true,
                        resizable: false,
                        actions: false,
                        draggable: false,
                        modal: true,
                        ignoreCase: false, //<--ignore the casing will stop applying .toLowerCase()
                        filter: "gte", //<-- filter operator compliant with `number` type
                        open:function(e) {
                            let windowHeight = $(window).outerHeight();
                            //let popupHeight = $('.k-widget.k-window').outerHeight();
                            let popupHeight = 500;
                            console.log(windowHeight, popupHeight);
                            if(popupHeight < windowHeight) {
                                $("html, body").css("overflow", "hidden");
                            } else {

                            }
                        },

                        close: function(e) {
                            $("html, body").css("overflow", ""); that.isVisible=false;
                        },

                        deactivate: function() {
                            this.destroy();
                            console.log("deactivate Call");
                        }

                        // closePopup: function() {
                     //     this.kPopUpWindowViewHistory.data("mobileWindow").close();
                        // }

        });

        that.kPopUpWindowViewHistory.data("mobileWindow").center();
        that.kPopUpWindowViewHistory.data("mobileWindow").open();

        $(".k-window").css("top", "15%");

        // closePopup(): void {
        //      //this.isVisible = false;
        //      this.kPopUpWindowViewHistory.data("mobileWindow").close();
        //  }

    }

}

-MacBook-Pro:webapp Raj$ npm start

> SPORTS@1.0.0 start /Users/Raj/Desktop/nbc/webcomponent/src/main/webapp
> tsc && concurrently "npm run tsc:w" "npm run lite"

app/components/skys/sky-documents.ts(129,8): error TS2339: Property 'jumpservice' does not exist on type 'PaperDocuments'.
app/components/skys/sky-documents.ts(140,10): error TS2339: Property 'rowDotMenuClick' does not exist on type 'PaperDocuments'.
app/components/skys/sky-documents.ts(200,23): error TS2339: Property 'ImageType' does not exist on type 'PaperDocuments'.
app/components/skys/sky-documents.ts(203,16): error TS2339: Property 'docTemplateEditor' does not exist on type 'PaperDocuments'.
app/components/skys/sky-documents.ts(211,28): error TS2339: Property 'sportsservice' does not exist on type 'PaperDocuments'.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! SPORTS@1.0.0 start: `tsc && concurrently "npm run tsc:w" "npm run lite" `
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the SPORTS@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/Raj/.npm/_logs/2017-07-26T03_44_36_683Z-debug.log

A: You need to inject the  jumpservice to your constructor
constructor(public sportsService : SPORTSService, private _jumpService : jumpService ){
}

and use it as,
this._jumpService