text:
Q: How insert Event in calnder without using intent in Android? Here is code:
   i am trying to add event to calender without using intent..here i put code.but getting some error.help me out.and got null pointer exception as given below.what to do now?
 btn_create_without_intent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Construct event details
            long startMillis = 0;
            long endMillis = 0;
            Calendar beginTime = Calendar.getInstance();
            beginTime.set(2015, 9, 21, 7, 30);
            startMillis = beginTime.getTimeInMillis();
            Calendar endTime = Calendar.getInstance();
            endTime.set(2015, 9, 21, 8, 45);
            endMillis = endTime.getTimeInMillis();

            // Insert Event
            ContentResolver cr = getContentResolver();
            ContentValues values = new ContentValues();
            TimeZone timeZone = TimeZone.getDefault();
            values.put(CalendarContract.Events.DTSTART, startMillis);
            values.put(CalendarContract.Events.DTEND, endMillis);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
            values.put(CalendarContract.Events.TITLE, "Android Example");
            values.put(CalendarContract.Events.DESCRIPTION, "Android Example");
            values.put(CalendarContract.Events.CALENDAR_ID, 3);
            Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);

            // Retrieve ID for new event
            String eventID = uri.getLastPathSegment();
        }
    });

And getting this error:
E/DatabaseUtils﹕ Writing exception to parcel
java.lang.NullPointerException
        at com.android.providers.calendar.CalendarProvider2.insertInTransaction(CalendarProvider2.java:2523)
        at com.android.providers.calendar.SQLiteContentProvider.insert(SQLiteContentProvider.java:96)
        at android.content.ContentProvider$Transport.insert(ContentProvider.java:192)
        at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:152)
        at android.os.Binder.execTransact(Binder.java:338)
        at dalvik.system.NativeStart.run(Native Method)
java.lang.NullPointerException
        at android.os.Parcel.readException(Parcel.java:1333)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:182)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:136)
        at android.content.ContentProviderProxy.insert(ContentProviderNative.java:415)
        at android.content.ContentResolver.insert(ContentResolver.java:730)
        at mockapp.techforce.com.calendereventexample.MainActivity$1.onClick(MainActivity.java:52)
        at android.view.View.performClick(View.java:3571)
        at android.view.View$PerformClick.run(View.java:14247)
        at android.os.Handler.handleCallback(Handler.java:605)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4517)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
        at dalvik.system.NativeStart.main(Native Method)


text:
Q: Short question regarding flow on the general linear group Say that we have a vector field on $GL(n,R)$, given by $A \rightarrow (A,A^2)$ (I mean the matrix power here). If we try to find the flow of this vector field, I get that it should be:
$X(A,t) = e^{tA^2}A$, where $e^{tA^2}$ is the matrix exponential here. However, since I feel somewhat unsure about the material, I am not sure that my approach is correct. Could someone either give some confirmation as to that this method is correct, and if so, does it follow that our vector field will be a complete one? I strongly suspect that such is the case.
If I'm wrong I'd love some hint that might put me in the right direction.

A: I have tried a bit of googling to find a sense of "the flow of a vector field" where $X(A,t)=e^{tA^2}A$ would be a correct solution, but in vain. You require $\frac{d}{dt}X(A,t) = X(A,t)^2$ and $X(A,0)=A$, right?
In that case, for $GL(1,\mathbb R)$ it reduces to an ordinary differential equation $\frac{dy}{dt}=y^2$ which is easily solved to find $y=\frac{1}{y_0^{-1}-t}$ which is significantly different from $y=e^{ty_0^2}y_0$
On the other hand, intuitively and by analogy to the real case, $X(A,t) = (A^{-1}-tI)^{-1}$ ought to work. If $A$ has a positive real eigenvalue this makes sense only for $t<1/\lambda$ where $\lambda$ is the largest such eigenvalue, but that parallels the vertical blowup of the real solution and so is to be expected. (And, applying Cramer's rule we see that the inverse really does escape to infinity before it stops making sense).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i defer the last line of code which follows after AJAX request? I've got the following code which gets the list of addresses from php script, then makes an ajax request to google maps, then creates markers and changes the zoom to fit the markers.

var bounds = new google.maps.LatLngBounds();
$.getJSON('/dmvfinder/dmvsearch.php', {zipcode: zipcode, state: state, city: city}, function (addresses) {
 addresses.forEach(function(address){
  $.getJSON('http://maps.googleapis.com/maps/api/geocode/json', {address: address}, function(data){
    var p = data.results[0].geometry.location;
    var latlng = new google.maps.LatLng(p.lat, p.lng);
    var marker = new google.maps.Marker({
     position: latlng,
     map: map
    });
    bounds.extend(latlng);
  });
 });
});
map.fitBounds(bounds);

As far as i understand the problem with the code is that the fitBounds method fires before ajax finishes and the 'bounds' gets filled. How could i possibly defer the last line of code here?
Thank you in advance!

A: You need to change 2 things

*

*Accumulate all the promises from the address.forEach - change it to a map and make sure to return $.getJSON(..). This will give you an array of deferreds.

*Wait for them all to complete using $.when - as this takes arguments, not an array, you can use $.when.apply(..) on your array from 1)

Like this:
var bounds = new google.maps.LatLngBounds();
$.getJSON('/dmvfinder/dmvsearch.php', {zipcode: zipcode, state: state, city: city}, function (addresses) {
    // 1. Accumulate all the promises into an array
    var allPromises = addresses.map(function(address){
        return $.getJSON('http://maps.googleapis.com/maps/api/geocode/json', {address: address}, function(data){
            var p = data.results[0].geometry.location;
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            var marker = new google.maps.Marker({
                position: latlng,
                map: map
            });
            bounds.extend(latlng);
        });
    });
    // 2. wait for them all to complete
    $.when.apply($,allPromises).then(function(){
      map.fitBounds(bounds);
    })
});


text:
Q: Android: ListView Custom Adapter. Resource not found Error Error Log:
android.content.res.Resources$NotFoundException: String resource ID #0x0
                                                                                at android.content.res.Resources.getText(Resources.java:299)
                                                                                at android.widget.TextView.setText(TextView.java:4138)
                                                                                at me.axiom.aapp.ironbannercompanion.ListViewAdapter.getView(ListViewAdapter.java:43)
                                                                                at android.widget.AbsListView.obtainView(AbsListView.java:2347)
                                                                                at android.widget.ListView.measureHeightOfChildren(ListView.java:1270)
                                                                                at android.widget.ListView.onMeasure(ListView.java:1182)
                                                                                at android.view.View.measure(View.java:17565)
                                                                                at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:727)
                                                                                at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463)
                                                                                at android.view.View.measure(View.java:17565)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5537)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                                at android.view.View.measure(View.java:17565)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5537)
                                                                                at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
                                                                                at android.view.View.measure(View.java:17565)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5537)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                at android.view.View.measure(View.java:17565)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5537)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                                                at android.view.View.measure(View.java:17565)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5537)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
                                                                                at android.view.View.measure(View.java:17565)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2045)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1196)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1409)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1084)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5990)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:550)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

ListViewAdapter Class:
String url="http://bungie.net";

private Context context;
private GuardianInfo[] guardianList;
private LayoutInflater inflater;

public ListViewAdapter(Context context, int resource, GuardianInfo[] object) {
    super(context, resource, object);
    this.context = context;
    this.guardianList = object;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (convertView == null)
        convertView = inflater.inflate(R.layout.listview_characters_content, parent, false);

    GuardianInfo guardian = guardianList[position];

    TextView textView_Class = (TextView) convertView.findViewById(R.id.listView_CLASS);
    textView_Class.setText(guardian.getCharacterBase().getClassType());

    ImageView imageView_IMG = (ImageView) convertView.findViewById(R.id.listView_IMG);
    ImageView imageView_BG = (ImageView) convertView.findViewById(R.id.listView_BG);

    Picasso.with(context).load(url + guardian.getEmblemPath()).into(imageView_IMG);
    Picasso.with(context).load(url + guardian.getBackgroundPath()).into(imageView_BG);

    return convertView;

}

Now the error seems to occur when I attempt to change the text of the textView_Class. It says the resource could not be found.
Also I am setting the ListAdapter via
GuardianInfo[] guardians = response.body().getResponse().getData().getCharacters();

ListViewAdapter adapter = new ListViewAdapter(getBaseContext(), R.layout.listview_characters_content, guardians);

ListView listView_Characters = (ListView) findViewById(R.id.listView_Characters);
listView_Characters.setAdapter(adapter);

A: From the Exception, it looks you are setting some int value to your TextView. When you are setting an int value to your TextView, it thinks that you are trying to set the text with a String resource with ID equal to your int value which in your case may be this guardian.getCharacterBase().getClassType(). Try replacing your this line
textView_Class.setText(guardian.getCharacterBase().getClassType());

with this
textView_Class.setText(String.valueOf(guardian.getCharacterBase().getClassType()));

A: Show your List item layout... R.layout.listview_characters_content


text:
Q: cannot invoke properties of control I'm trying to programmatically create a axWindowsMediaPlayer and show it:
private void button1_Click(object sender, EventArgs e)
    {
        AxWMPLib.AxWindowsMediaPlayer wmplayer = new AxWMPLib.AxWindowsMediaPlayer();
        wmplayer.Size = new Size(200, 200);
        wmplayer.enableContextMenu = false; //here it throws an exception
        this.Controls.Add(wmplayer);
    }

but it says {Property set of 'enableContextMenu' cannot be invoked at this time.}
why is that? why can I set Size but not enableContextMenu?

A: I found the solution:
It is important that you do changes and/or function calls after you added wmplayer to this.Controls.
I don't know why wmplayer.Size worked, but it is definitively the exception..
private void button1_Click(object sender, EventArgs e)
{
    AxWMPLib.AxWindowsMediaPlayer wmplayer = new AxWMPLib.AxWindowsMediaPlayer();
    this.Controls.Add(wmplayer);
    wmplayer.Size = new Size(200, 200);
    wmplayer.enableContextMenu = false; //here it throws an exception
}

works perfectly fine..


text:
Q: How frequently can I safely cache the baseUrl? Before each request to the DocuSign REST API, I make a call to https://demo.docusign.net/restapi/v2/login_information. But the only information I need from that response is the first baseUrl attribute, which never seems to change. If it truly never changes, I should just store the value as a constant, cutting my number of requests in half.
How often (or under what circumstances) does the baseUrl change, assuming my integration key is constant? More importantly, how infrequently can I safely cache the baseUrl?

A: Since it is a third-party API outside your control, I would recommend that you follow the requirements of the documentation, and make the call each time.  There's no telling when they might change the internals of the API.

A: Short answer: cache with caution. It will most likely never change, but if it does, just grab it again. I would make the call at the beginning of a set of requests, and then forget about it.
The baseUrl parameter would look like:
"https://demo.docusign.net/restapi/v2/accounts/123456"
To break it down:

*

*demo.docusign.net -> Our uri, demo environment is as you expect, the
demo site.

*restapi/v2/ -> Using version 2 of the api

*accounts/123456
-> Your account id particular to the demo site. (This will be a different id for the production site)

You would need to know this url for every api call. I wouldn't store it 'forever' just to be safe, but you could cache it for a short time to reduce the number of API calls. Your accountId should never change on the environment, but we do provide new environments occasionally, and every different account will have a different baseUrl.
For reference, see here: https://docs.docusign.com/esign/guide/usage/quickstart.html
If you really want to store it for a long time, I would set a 30 day time-out or something along those lines.


text:
Q: Efficient Aeson parsing for sum type toEncoding I'm parsing a third party JSON structure into my own set of types. I'd like to parse in the most efficient way possible (I'm parsing data sent over a unix socket with Network.Socket)
Aeson's documentation claims that parsing with toEncoding yields up to a 3x speedup over toJSON, however I don't understand how to write a valid instance using toEncoding for my simple sum type.
for example:
data NodeLayout =
    SplitHorizontalLayout
    | SplitVerticalLayout
    | StackedLayout
    | TabbedLayout
    | DockAreaLayout
    | OutputLayout
    deriving (Eq, Generic)

instance ToJSON NodeLayout where
    toJSON = \case
        SplitHorizontalLayout -> "splith"
        SplitVerticalLayout   -> "splitv"
        StackedLayout         -> "stacked"
        TabbedLayout          -> "tabbed"
        DockAreaLayout        -> "dockarea"
        OutputLayout          -> "output"

instance FromJSON NodeLayout where
    parseJSON (String s) = pure $ case s of
        "splith"   -> SplitHorizontalLayout
        "splitv"   -> SplitVerticalLayout
        "stacked"  -> StackedLayout
        "tabbed"   -> TabbedLayout
        "dockarea" -> DockAreaLayout
        "output"   -> OutputLayout
        _          -> error "Received unrecognized NodeLayout"
    parseJSON _ = error "Error parsing NodeLayout"

I have other data types that will receive Vectors of this, but sometimes I receive a single value that needs to be parsed individually. How does one efficiently parse strings into sum types using toEncoding?

A: As far as I know, Aeson does not provide an alternative to fromJSON for parsing / decoding.  The docs explain that toEncoding allows more efficient encoding / serialization - going from the Haskell in-memory representation to the wire format.  It's not clear from your question which direction you require to be fast.
You can provide an explicit toEncoding following the pattern of your toJSON.  Data.Aeson.Encoding provides a bunch of helper functions for writing these:
    toEncoding = \case
        SplitHorizontalLayout -> text "splith"
        SplitVerticalLayout   -> text "splitv"
        StackedLayout         -> text "stacked"
        TabbedLayout          -> text "tabbed"
        DockAreaLayout        -> text "dockarea"
        OutputLayout          -> text "output"


text:
Q: Merge multiple arrays using zip This may be a silly one. But I am not able to figure it out.
names = ['Fred', 'John', 'Mark']

age = [27, 40, 25]

location = ['Sweden', 'Denmark', 'Poland']

names.zip(age)

#Outputs => [["Fred", 27], ["John", 40], ["Mark", 25]]

But I need to output it with the 3rd array (location) with it.
#Expected Output => [["Fred", 27,"Sweden"], ["John", 40,"Denmark"], ["Mark", 25,"Poland"]]

The most important condition here is that, there may be any number of arrays but the output should form from the first element of each array and encapsulate inside another array.
Thanks for any help.

A: Try passing multiple arguments to zip:
names.zip(age, location)
# => [["Fred", 27, "Sweden"], ["John", 40, "Denmark"], ["Mark", 25, "Poland"]]


text:
Q: `hardhat` support for `pnpm` Trying to use hardhat via pnpm.
With command:

pnpm add -D @nomicfoundation/hardhat-toolbox

Get following error:
devDependencies:
+ @nomicfoundation/hardhat-toolbox 1.0.2

 WARN  Issues with peer dependencies found
.
├─┬ @nomicfoundation/hardhat-toolbox 1.0.2
│ ├── ✕ missing peer @ethersproject/abi@^5.4.7
│ ├── ✕ missing peer @ethersproject/providers@^5.4.7
│ ├── ✕ missing peer @nomicfoundation/hardhat-network-helpers@^1.0.0
│ ├── ✕ missing peer @nomicfoundation/hardhat-chai-matchers@^1.0.0
│ ├── ✕ missing peer @nomiclabs/hardhat-ethers@^2.0.0
│ ├── ✕ missing peer @nomiclabs/hardhat-etherscan@^3.0.0
│ ├── ✕ missing peer @types/chai@^4.2.0
│ ├── ✕ missing peer @types/mocha@^9.1.0
│ ├── ✕ missing peer @types/node@>=12.0.0
│ ├── ✕ missing peer @typechain/ethers-v5@^10.1.0
│ ├── ✕ missing peer @typechain/hardhat@^6.1.2
│ ├── ✕ missing peer chai@^4.2.0
│ ├── ✕ missing peer ethers@^5.4.7
│ ├── ✕ missing peer hardhat-gas-reporter@^1.0.8
│ ├── ✕ missing peer solidity-coverage@^0.7.21
│ ├── ✕ missing peer ts-node@>=8.0.0
│ ├── ✕ missing peer typechain@^8.1.0
│ └── ✕ missing peer typescript@>=4.5.0
└─┬ hardhat 2.11.1
  ├── ✕ missing peer ts-node@"*"
  └── ✕ missing peer typescript@"*"
Peer dependencies that should be installed:
  @ethersproject/abi@^5.4.7                        @types/mocha@^9.1.0
  @ethersproject/providers@^5.4.7                  @types/node@>=12.0.0
  @nomicfoundation/hardhat-chai-matchers@^1.0.0    chai@^4.2.0
  @nomicfoundation/hardhat-network-helpers@^1.0.0  ethers@^5.4.7
  @nomiclabs/hardhat-ethers@^2.0.0                 hardhat-gas-reporter@^1.0.8
  @nomiclabs/hardhat-etherscan@^3.0.0              solidity-coverage@^0.7.21
  @typechain/ethers-v5@^10.1.0                     ts-node@>=8.0.0
  @typechain/hardhat@^6.1.2                        typechain@^8.1.0
  @types/chai@^4.2.0                               typescript@>=4.5.0

Progress: resolved 294, reused 284, downloaded 0, added 1, done

I've seen several other packages that doesn't work with pnpm too before.
So, what's the reason cause such issue, is it pnpm or specific packages (e.g hardhat) responsible for such issue?
I really prefer to use pnpm, because it's much quicker than npm.

A: Try the command:
pnpm config set auto-install-peers true

After that, just repeat your command and it will automatically install all the dependencies.


text:
Q: virtual machine loses internet connection if anything happens to host internet connection I am using Virtual Box and if i lose internet connection or anything happens with my network adapter on host machine i will lose the internet connection on my Virtual Machine.
Even if i connect again, the host is fine but my Virtual Machine can't connect, i need to restart it in order to get internet.
Is there a way to restart networking on the Virtual Machine somehow without rebooting the whole Virtual Machine?
update:
i have tried this command:
sudo /etc/init.d/networking restart

but it just hangs and nothing happens.

A: This problem is very familiar as it seems and I have experimented a little and it turns out that you can change the network adapter while the VM is running here:

and then change only the Attached to: option to NAT or Bridged Adapter (mine was on Bridged adapter so i changed it to NAT).

and click OK. And then change it again to which it was before and again click on OK to accept it.
Now go back to your VM terminal and run this command
sudo /etc/init.d/networking restart

Update:
for Ubuntu 18|20 run
sudo apply netplan

to restart Networking
And the internet connection will work without reseting the VM.

A: Something that works for me is to turn off the network adapter and then turn it back on (go to the drop down box next to the battery icon in the far top right corner of the VM display and then do "Wired Connected" | "Turn Off" and then Turn On). That seems to jolt it out of its slumber. It is nevertheless very annoying as it seems like its up for about 10 or 15 minutes before it goes down again


text:
Q: 'dllimport' attribute only applies to variables, functions and classes warning even though applied to class function I'm in the middle of a port to the newest c++ Builder 11 (Clang) compiler and I ran into a warning that I don't understand
The warning:
'dllimport' attribute only applies to variables, functions and classes

The simplified code:
class Test
{
   public:

   Test() ;

   int __declspec(dllimport) (*DllFunction)  (int a, int b) ;

} ;

And during construction (for instance) I load the dll and find a pointer for DllFunction
This is a function, so .. why the warning ?
What am I not getting ?

A: As the error message says, dllimport cannot be used to import individual class methods. Only standalone variables and functions, and whole classes. However, dllimport is meant for static linking only, but you are using dynamic loading instead, so there is no need to use dllimport in this code at all.

A: You can't dllimport a member function without dllimport-ing the whole class - this is where your dllimport should be.


text:
Q: Codeigniter form submit on same page ends in empty result I have a controller which fetches data from a database and assigns that data to the view. This controller is Searchcontroller.
If I sumbit the form on the Indexpage view to the Searchcontroller everything works fine, the data gets fetched and displayed correctly.
The issue is when I try to submit the same form in the Searchview that is displayed by Searchcontroller. Then I get empty results.
Searchcontroller
public function index() {
  $this->load->model('Dbmodel');

  $data = array(
    'result' => $result = $this->Dbmodel->getSearch($this->input->post('okresselect'), null),
    'okresy' => $result = $this->Dbmodel->getOkresy()
  );

  $this->load->view('searchpage', $data);
}

Indexpage view
<form method="post" action="search">

  .. some code here

</form>

Searchpage view

<form method="post" action="<?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>">

  .. some code here

</form>

Thanks

A: the action in the form should look like  with the last trailing slash. now everything works correctly.
Thanks anyway guys!


text:
Q: Angular JS : Service : Flip the page on adding more divs/sections? I have 6 widgets in one page1.I want to flip the page1 to Page2 when the 7th widget is added to it. For adding the widget i am using the Angular JS.
The solution for the same problem you may also suggest in javascript or jQuery.
My recordsService.js is as following :
app.service('recordsService', function () {
this.getRecords = function () {
    return records;
};

this.insertRecord = function (newWidgets) {
    records.push(neWWidgets);
};

this.getRecord = function (id) {
    for (var i = 0; i < records.length; i++) {
        if (records[i].id === id) {
            return records[i];
        }
    }
    return null;
};

& recordcontrollers.js is as follwing:
 app.controller('RecordsController', function ($scope, recordsService) {

init();
function init() {
    $scope.records = recordsService.getRecords();
}
$scope.insertRecord = function (type) {

    if(type=="tag")
        {

    var newWidgets =
    {
        "id": 7,
        "age" : "7"
     };
        recordsService.insertRecord(newWidgets);
  }
        };

  });

Here is the picture that what i really want to need. here 5 divs are visible when someone click on link1 6th will be added to the next page so only next page will be visible with the new 6th div only.
Looking for help.Thanks.


text:
Q: Stata drop observations command I have panel data for two years for individuals (id). A dummy variable (empl) takes on three values (1,2,3). I'd like to keep only those ids which take on a value of 1. What Stata command should I use?

A: The code cited in the comments
by empl, sort: keep if empl == 1

is equivalent to
keep if empl == 1

and pays no attention to the panel structure.
What is wanted is to keep panels for which empl is always 1: if that is so, the minimum and maximum are always 1, so a criterion is
by id (empl), sort: keep if empl[1] == empl[_N] & empl[1] == 1

or
by id (empl), sort: keep if empl[1] == 1 & empl[_N] == 1


text:
Q: W3 Total Cache, CDN and theme files I updated the style.css file of my WordPress installation recently. The change were effective: when logged in as an administrator (my blog is set so that the administrator is never served a cached version of the site, but a "live" one), I can see them.
But my blog is being served through a CDN (using W3 Total Cache). Through the CDN, the changes are not effective: the CDN does not serve the modified files from my theme. Even though I've uploaded them after modification (Dashboard>Performance>CDN>Upload theme files.
My CDN runs on AmazonCloud Front. And Minify is disabled on W3 Total Cache.
The theme file being served through my CDN is a compressed version: style.css.gzip
Should I "purge" objects from my CDN or wait a little more (it's been more than a week). And yes, I empty the cache of the browser I'm using to see in the changes are taking effect. Or is there something else I'm missing?
Thanks,
P.

A: There's a pretty simply "trick" to prevent caching, when file contents changed: Add a version number, that is set to the latest date/time you changed your file.
add_action( 'wp_enqueue_scripts', 'wpse61738_non_cached_stylesheet' );
function wpse61738_non_cached_stylesheet()
{
    wp_enqueue_style(
        'style-main',
        get_stylesheet_directory_uri().'/style.css',
        array(),
        filemtime( get_stylesheet_directory().'/style.css' )
    );
}

This will append ?ver=0123456789 to your style.css reference link in your header. The version number will only change, when the files contents get modified. So you have a solution that works perfect with a) server side cache b) browser cache and refreshes automatically.

A: You need to either

*

*Version your files (by calling it  style.css?ver=xxx.xxx) and making sure your CloudFront distribution has "Forward Query strings" turned on. This is the better option, as it means that all you need to do is increment the number in the query string and CloudFront will fetch this file automatically.

*Manually invalidate your files via the AWS Console (there is an invalidation tab when you edit your distribution)
To turn on 'Forward Query Strings' do the following:

*

*Edit your Cloudfront distro by ticking the checkbox on the left of the 'i' and then click on the "distribution settings" button in the toolbar

*Go to the Behaviors tab

*Select the line, and click on 'Edit'

*Change "forward query strings" to Yes

*Click on "Yes, Edit"

A: a short answer ...

*

*Delete all your theme files and re-upload them.  some times the delete action clears the CDN

*Yes, you could try Purge -- but Delete and re-upload is usually quicker.

*Also check out the settings in W3TC and in Amazon. The default Cache for in W3TC is usually 365 days. which is 31536000 seconds :)
In Amazon .. there will be a setting for endpoints to re-query the CDN. i know in Rackspace the default is 24 hours.


text:
Q: Why is assert not working in abstract class? I need you assistance to understand why assert is not working in my code (I am using this code to learn about abstract classes, getters and setters), I am a newbie at abstract classes.
If I put a negative number at power attribute, the code should be stop with a warning, but assert ignores if power is negative, zero or non-negative number.
Another test code without concrete methods at base class, but the same concrete methods at subclasses the code stop and give me a warning.
Here is my complete code to tests.
from abc import ABC, abstractmethod

class Load(ABC):
    #That's a class to create load to circuits.
    @abstractmethod
    def __init__(self, power=0, power_factor=1):
        self.__power = power
        self.__power_factor = power_factor

    # the attributte name and the method name must be  same
    # which is used to set the value for the attributte
    @property
    def power(self):
        return self.__power

    @power.setter
    def power(self, power):
        # AT TEST SHOULD STOP HERE ANY CONDITION - ONLY TEST PURPOSEs
        # BUT HERE ASSERT IS IGNORED
        assert (power < 0), "power must be non-negative"
        assert (power >= 0), "***power must be negative - ONLY TEST"
        self.__power = power

    @property
    def power_factor(self):
        return self.__power_factor

    @power_factor.setter
    def power_factor(self, power_factor):
        assert 0 < power_factor <= 1, "power factor must be greater 0 until 1"
        self.__power_factor = power_factor

class Specific(Load):
    def __init__(self, power, power_factor):
        super().__init__(power, power_factor)
    # the attributte name and the method name must be  same
    # which is used to set the value for the attributte

### ONLY TESTs PURPOSE

a = Specific(-11,1) # TO FORCE THE ERROR
print(a.power, a.power_factor)
a.power_factor = .4
print(a.power, a.power_factor)

What am I doing wrong?

A: You are not using your setter - you directly assign to your backing fields.
Use
class Load(ABC):
    #That's a class to create load to circuits.
    @abstractmethod
    def __init__(self, power=0, power_factor=1):
        self.power = power                          # acutally use the setter, do not
        self.power_factor = power_factor            # set the backing field directly...

so your setters check the values.


text:
Q: Casting floats and UILabel HI -
I have a value in a UILabel and I want to pass the number to a value that is of float type.
rate = float
hourlyRate = label

Below is my code and im getting errors.  I know its bad form to go from object to primitive values but there has to be a way.
Any help would be appreciated!
rate = NSNumber numberWithFloat:[hourlyRate.text rate];

A: NSString has a convenient floatValue method:
rate = [hourlyRate.text floatValue];

A: rate = NSNumber numberWithFloat:[hourlyRate.text rate];

That's invalid because if you're trying to send the message numberWithFloat: to NSNumber it has to be enclosed in brackets, like so:
rate = [NSNumber numberWithFloat:[hourlyRate.text rate]];

And what's more hourlyRate.text returns an NSString. You can't send an NSString the method rate unless you subclassed it and added that method.
This is the right way to get the float value of UILabel, try this:
rate = [hourlyRate.text floatValue];

And do you mean:
float rate;


text:
Q: How to distribute a windows phone 7 application from within an intranet I have a windows phone 7 application which I need to distribute to elements of my company. How can I achieve this? I do not want the application to be on the marketplace because it is a corporate application which should only be visible and used by elements of the organization.
Is this possible?
Best regards,
Bruno

A: There are 2 options currently open to you:

*

*You could use Beta distribution as Tom says, but that's limited to 90 days and no updates.

*You could also publish the application on Marketplace, but make it hidden so that other users cannot search for it. You would need to send your users a link so that they could install the app. See MSDN documentation.

However for the 2nd option you should beware that anyone would be able to install the application if they know the link for it. So if you need it to be secure you need to provide some other mechanism to lock it down.

A: There has been news about a private distribution model for corporate applications, but this is not available yet. For now you can use the private beta distribution for this purpose, all you need is a list of the Live IDs used by the people within your company.
I wrote a blog explaining private beta functionality, you can find it here


text:
Q: Why there is no varchar datatype in DynamicReports I am using DynamicReports to generate a report in PDF,XLS,DOC. But my database columns are in "varchar" datatype. So when I am using those fields in generating DynamicReports there is every other datatype other than varchar. I need varchar datatype because my column consists of commas, fullstops, numbers like these. So is there any option to convert or to get the datatype as varchar.
Here is my code:
public class DynamicReport {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/marketing_database","root","root");
        } catch (SQLException e) {
            e.printStackTrace();
            return;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }

        JasperReportBuilder report = DynamicReports.report();//a new report
        StyleBuilder plainStyle = stl.style().setFontName("FreeUniversal");

        StyleBuilder boldStyle = stl.style(plainStyle).bold().setBorder(stl.pen1Point());

        report
          .columns(
              Columns.column("Contact Person", "Contact_Person", DataTypes.stringType()))
          .title(//title of the report
                  Templates.createTitleComponent("Fonts"),
              Components.text("FreeUniversal").setStyle(boldStyle)
              .setHorizontalAlignment(HorizontalAlignment.CENTER))
              .pageFooter(Components.pageXofY())//show page number on the page footer
              .setDataSource("SELECT Contact_Person FROM marketing_database.lead",
                                      connection);

        try {
            report.show();
            report.toPdf(new FileOutputStream("c:/report.pdf"));
        } catch (DRException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
      }
}

Any help in this will be appreciated

A: Since Dynamic Reports is based on Java, you can use the String data type for VARCHAR db types, as @AlexK and @KarthikeyanVaithilingam suggested.

CHAR, VARCHAR, and LONGVARCHAR could have been mapped to either String or char[], but String is more appropriate for normal use. Also, the String class makes conversions between String and char[] easy: There is a method for converting a String object to a char[] and also a constructor for turning a char[] into a String object.

Source


text:
Q: If e is a pointer then why . operator is being used instead of ->? Code works fine.
Output received from some input
In several places after the term e[something] '.' operator is used. Since e is a pointer that holds address to an element, Why isn't '->' operator is used. Is it so because e[something] will hold an entire structure as value to that index=something instead of an address to the element?
#include <stdio.h>
#include <stdlib.h>

struct element{
  int i;
  int j;
  int x;  //x represents value of A[i][j]
};

struct sparse{
  int m;
  int n;
  int num;  // num represents no. of non-zero elements
  struct element *e;
};

void create(struct sparse *);
void display(struct sparse);

void create(struct sparse *s){
  printf("Enter Dimensions :\n");
  scanf("%d%d", &s->m, &s->n);
  printf("Enter number of non-zero elements :");
  scanf("%d", &s->num);

  s->e = (struct element *) malloc(s->num * sizeof(struct element));

  printf("Enter i, j, x :\n");
  for(int k = 0; k < s->num; k++){
    scanf("%d%d%d", &s->e[k].i, &s->e[k].j, &s->e[k].x); // why not s->e[k]->i
  }
}

void display(struct sparse s){
  int p, q, k = 0;
  for(p = 0; p < s.m; p++){
    for(q = 0; q < s.n; q++){
      if(p == s.e[k].i && q == s.e[k].j){
        printf("%d ", s.e[k].x);
        k++;
      }
      else{
        printf("0 ");
      }
    }
    printf("\n");
  }
}

int main(){
  struct sparse s;

  create(&s);
  display(s);
  return 0;
}

A: back to basics of arrays :
arr[i] is equivalent to *(arr + i) and arr itself is the base address of the array
so e[k] is equivalent to *(e + k) and e value itself is just address.
so when you say *(e + k) this means that you have the actual instance not a pointer that points to its place. as you dereference e using [] operator.
the only case that you can write  e[k]->i; is when e[k] itself is a pointer but in your case e[k] isn't a pointer , as said above , it's equivalent to *(e + k) so it's dereferenced and *(address) will give you the actual instance in the memory that e + k points to.

A: s->e = (struct element *) malloc(s->num * sizeof(struct element));

e points to an array of structs.
doing something like s->e[i].member is completely legal. We can use . because e[i] isn't pointer.
So if it isn't a pointer what is it?
e[i] is some value/data at an address.  Specifically e[i] is some value/data at the address of the ith struct in e. Using e[i] will allow us to reference the ith struct.
When we do e[i] it's the same as *(e+i). Notice how a * (dereference operator) is used. This will get us the value/data that we need from the address that e+i points to, which in turn will enable us to access its members.


text:
Q: Partial specialization of function templates Does anyone know whether, in C++11, function templates can be partially specialized?

A: No, they can't. The draft C++0x standard has a section (14.5.5) on class template partial specialisations, but no mention of function template partial specialisations.

A: No; they were proposed as core language issue #229 (from n1295) but ultimately rejected (and quite rightly so, since overloading does the job).


text:
Q: Error Missing Type specifer - int assumed . Note C++ does not support default init In order to make two objects, User1 and User2, of a class User sending and receiving messages,
#include <iostream>

using namespace std;

class reply
{
public:
    User* sender;
 };

class User
{
    BlockingQueue<Message > queue;

public:

    void sendMessage()
    {
    };

    void run()
    { //......
    }

};

In the Player class, I get an error indicating that Player* sender is not a member of the Message class!
And in the Message class, i get this error:
Severity    Code    Description Project File    Line    Suppression State

    Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int

Can you please help me with this?

A: You have to add a forward declaration of player before Message
class Player; <<<<=====
class Message
{
public:

    Player* sender ;
    std::string text;
};

see here for explanation What are forward declarations in C++?
and yes - it should be std::string


text:
Q: Using Google Contacts API v3, how to get contacts for a specific group? I am able to get contacts and groups.  What I am unable to do is query contacts for a specific group.  I've read the Docs, and specifying group Atom Id doesn't make sense because there is a type collision.
const string name = "MyGroup";
var uri = ContactsQuery.CreateGroupsUri("default");
var gQuery = new GroupsQuery(uri);
var group = cr.Get<Group>(gQuery).Entries.AsQueryable()
    .SingleOrDefault(e => e.GroupEntry.Title.Text.Contains(name));

uri = ContactsQuery.CreateContactsUri("default");
var cQuery = new ContactsQuery(uri);
if (group != null)
{
   cQuery.Group = (string)group.AtomEntry.Id;   //  WHAT TO PUT HERE ?
}
Feed<Contact> feed = cr.Get<Contact>(cQuery);

Unable to assign type AtomId...
group.AtomEntry.Id // type = AtomId

... to string type for ...
cQuery.group // type = string

Thanks!

A: Change...
cQuery.Group = (string)group.AtomEntry.Id;

to...
cQuery.Group = (string)group.Id;

The hint came from this post.  Where I realized that the URI being constructed is quite long and includes [the contacts URI] + ?group= [the group base/id URI].  Example:  https://www.google.com/m8/feeds/contacts/default/full?group=http://www.google.com/m8/feeds/groups/user.email%40domain.com/base/some_alphanumeric_id


text:
Q: VB.net using google translator i tried to translate the word "test",

my code:
Imports Google.API.Translate

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = "test"
        Dim gtras As New TranslateClient("MY API KEY")
        Label1.Text = gtras.Translate(TextBox1.Text, Language.English, Language.Hebrew, TranslateFormat.Text)

    End Sub
End Class

the exception is:
Attempt by method 'Google_Translator.Form1.Button1_Click(System.Object, System.EventArgs)' to access method 'Google.API.Enumeration.op_Implicit(Google.API.Enumeration)' failed.

A: This issue has been fixed in a later version of the API (0.3.1 seems to work):
http://code.google.com/p/google-api-for-dotnet/issues/detail?id=43

A: This code works very well:
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System
Imports System.Net
Imports System.Text
Imports System.Web
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    MsgBox(gtranslate(TextBox1.Text, "it", "en"))'From italian to english, of course you can change it
End Sub

Public Shared Function gtranslate(ByVal inputtext As String, ByVal fromlangid As String, ByVal tolangid As String) As String
    inputtext = HttpUtility.HtmlAttributeEncode(inputtext)
    Dim step1 As New WebClient
    Dim step2 As String = step1.DownloadString("https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=" & tolangid & "&hl=" & fromlangid & "&dt=t&dt=bd&dj=1&source=icon&q=" & inputtext)
    Dim step3 As Newtonsoft.Json.Linq.JObject = JObject.Parse(step2)
    Dim step4 As String = step3.SelectToken("sentences[0]").SelectToken("trans").ToString()
    Return step4
End Function
End Class

The dll library "Newtonsoft.JSON" is available from their website and, if you get some errors with "HttpUtility", add the reference "System.Web" in the add reference window -> .net tab

A: Fix Encoding And update code
Public Shared Function gtranslate(ByVal inputtext As String, ByVal fromlangid As String, ByVal tolangid As String) As String
    inputtext = HttpUtility.HtmlAttributeEncode(inputtext)
    Dim step1 As New WebClient
    step1.Encoding = Encoding.UTF8
    Dim step2 As String = step1.DownloadString("https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=" & tolangid & "&hl=" & fromlangid & "&dt=t&dt=bd&dj=1&source=icon&q=" & inputtext)
    Dim step3 As Newtonsoft.Json.Linq.JObject = JObject.Parse(step2)
    Dim step4 As String = step3.SelectToken("sentences[0]").SelectToken("trans").ToString()

    Return step4

End Function

Add : step1.Encoding = Encoding.UTF8


text:
Q: How to extract href link title with selenium? I am having issues figuring out how to extract all 100 of the link titles on the page with selenium. I have the code to extract only the links but how would I go about doing the same but for the link titles? Any help would be appreciated, thanks!
What I have:
from selenium import webdriver
driver = webdriver.Chrome('/Users/wwds/Downloads/chromedriver')
driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')

elems = driver.find_elements_by_css_selector(".ndm-result-title [href]")
links = [elem.get_attribute('href') for elem in elems]

A: To get the title from all 100 links on a page.You need to induce WebDriverWait() and wait for visibility_of_all_elements_located() and the following css selector.
driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "#all a[target='_self']")))
linkTitles = [title.text for title in elements]
print(len(linkTitles))
print(linkTitles)

You need to import following libraries.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Output Console:
100
['Capital markets activities, gross new issues, retirements and net new issues, par value, Bank of Canada', 'Funds advanced, outstanding balances, and interest rates for new and existing lending, Bank of Canada', 'Funds advanced, outstanding balances, and interest rates for new and existing lending, dollars, Bank of Canada', 'Net new issues of bonds and equities by corporations and federal government enterprises: Industrial classification, Bank of Canada', 'Bank of Canada, assets and liabilities, average of Wednesdays', 'Chartered banks, assets and liabilities, monthly average, Bank of Canada', 'Currency outside banks and chartered bank deposits, monthly average, Bank of Canada', 'Selected credit measures, monthly average or average of month-ends, unadjusted unless otherwise noted, Bank of Canada', 'Chartered bank assets and liabilities and monetary aggregates, monthly average, seasonally adjusted, Bank of Canada', 'Consumer credit, outstanding balances of selected holders, Bank of Canada', 'Credit measures, Bank of Canada', 'Corporate short-term paper outstanding, Bank of Canada, monthly', 'Toronto Stock Exchange statistics', 'Residential mortgage credit, outstanding balances of major private institutional lenders, Bank of Canada', 'Bonds outstanding, shown at par value, by currency of payments and issuers, Bank of Canada', 'Bank of Canada, assets and liabilities, Wednesdays', 'Bank of Canada, money market and other interest rates', 'Positions of members of the Canadian Payments Association and Bank of Canada operations, Bank of Canada, weekly', 'Chartered banks, classification of non-mortgage loans, at end of period, Bank of Canada', 'Tobacco, sales and inventories, monthly production', 'Historical (real-time) releases of Consumer Price Index (CPI) statistics, measures of core inflation - Bank of Canada definitions', 'Historical (real-time) releases of wholesale sales, price and volume, seasonally adjusted', 'Historical (real-time) releases of wholesale trade, sales', 'Historical (real-time) releases of wholesale trade, inventories', 'Historical (real-time) releases of retail trade, sales', 'Historical (real-time) releases of retail sales, price, and volume', 'Capital expenditures, oil and gas extraction industries, Canada', 'Daily average foreign exchange rates in Canadian dollars, Bank of Canada', 'Investment in Building Construction', 'Gross domestic product (GDP) at basic prices, by industry, provinces and territories, percentage share', 'Gross domestic product (GDP) at basic prices, by industry, provinces and territories', 'Gross domestic product (GDP) at basic prices, by industry, provinces and territories, growth rates', 'Canadian Economic Dashboard and COVID-19', 'Statistics Canada - Data Visualization Products', 'Financial market statistics, last Wednesday unless otherwise stated, Bank of Canada', 'Selected United States dollar interest rates, Wednesdays, Bank of Canada', 'Fisher commodity price index, United States dollar terms, Bank of Canada, Fisher commodity price index, United States dollar terms, Bank of Canada, weekly', 'Financial market statistics, as at Wednesday, Bank of Canada', 'Exports and imports of goods and services, quarterly, Canada, (NAPCS 2017)', 'Contributions to annual percent change in real exports and imports of goods and services, Canada, annual, (NAPCS 2017)', 'Industrial product price index, by major product group, monthly', 'Industrial product price index, by major product group, percentage change, monthly', 'Industrial product price index, by product, monthly', 'Industrial product price index, by product, percentage change, monthly', 'Industrial product price index, for selected products, by region, monthly', 'Industrial product price index, for selected products, by region, percentage change, monthly', 'Industrial product price index, by industry, monthly', 'Industrial product price index, by industry, percentage change, monthly', 'Raw materials price index, monthly', 'Raw materials price index, percentage change, monthly', 'Commercial software price index, monthly', 'Commercial software price index, percentage change, monthly', 'Couriers and messengers services price index, monthly', 'Couriers and messengers services price index, percentage change, monthly', 'Computer price index, by type of purchaser, monthly', 'Computer price index, by type of purchaser, percentage change, monthly', 'Computer peripheral price index, monthly', 'Computer peripheral price index, percentage change, monthly', 'Smart phone price index, monthly', 'Smart phone price index, percentage change, monthly', 'Civil aviation operating statistics, by type of service, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation operating statistics, by sector, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation financial statistics, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation financial performance indicators, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation productivity measures, Canadian air carriers, Levels I and II, quarterly', 'Weekly rail terminal performance indicator, Transport Canada', 'Weekly performance indicators of grain transportation by rail, Transport Canada', 'Weekly rail system performance indicators, by commodities, Transport Canada', 'Weekly rail system performance indicator, by type of rail car, Transport Canada', 'Flows and stocks of fixed non-residential and residential capital, by sector and asset, provincial and territorial', 'Gross domestic product, income-based, quarterly', 'Gross domestic product, expenditure-based, Canada, quarterly', 'Gross national income and gross domestic income, indexes and related statistics, quarterly', 'Gross domestic product price indexes, quarterly', 'Household final consumption expenditure, quarterly, Canada', 'Gross fixed capital formation, quarterly, Canada', 'Investment in inventories, quarterly, Canada', 'Current and capital accounts - National, Canada, quarterly', 'Current and capital accounts - Households, Canada, quarterly', 'Compensation of employees, Canada, quarterly', 'Current and capital accounts - Non-profit institutions serving households, Canada, quarterly', 'Current and capital accounts - Corporations, Canada, quarterly', 'Undistributed corporation profits', 'Current and capital accounts - General governments, Canada, quarterly', 'Current and capital accounts - Non-residents, Canada, quarterly', 'Gross domestic income, gross national income and net national income, Canada, quarterly', 'Gross domestic product, expenditure-based, at 2012 constant prices, quarterly', 'Detailed household final consumption expenditure, Canada, quarterly', 'Corporation profits before taxes, on an original-cost-basis, excluding government business enterprises, Canada, quarterly', 'Property income of households, Canada', 'General governments final consumption expenditure, Canada, quarterly', 'Contributions to annual percent change in real expenditure-based gross domestic product, Canada, annual', 'Gross national income and gross domestic income, indexes and related statistics, annual', 'Gross domestic product price indexes, annual (2012=100)', 'Contributions to annual percent change in real household final consumption expenditure, Canada, annual', 'Contributions to annual percent change in real gross fixed capital formation, Canada, annual', 'Contributions to annual percent change in real general governments final consumption expenditure, Canada, annual', "Wages, salaries and employers' social contributions", 'Gross domestic product, expenditure-based, at 2012 constant prices, annual', 'Gross domestic product (GDP) at basic prices, by industry, monthly']

A: Try find the element with xpath, and get the title by .text like below:
driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')
elems = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//details[@id='all']//a[@target]")))
links = [elem.text for elem in elems]

Following import:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Is it possible to get data from the server without passing a tableName parameter? Retrofit @FormUrlEncoded
@POST("Places.php")
Call<List<CountryModel>> getCountries(@Field("tableName") String tableName);

@FormUrlEncoded
@POST("Places.php")
Call<List<CityModel>> getCities(@Field("tableName") String tableName);

@FormUrlEncoded
@POST("Places.php")
Call<List<NeighborhoodModel>> getNeighborhoods(@Field("tableName") String tableName);

I have a PHP file named Places.php and this file provides me the data as a JSON array according to the tableName parameter.
Everything is working well but I want to ask is it possible to get the data from the server according to the method name, Not tableName.
For example, If I called the getCountries method then that means I want to get countries, Is it possible to do that without inserting the table name parameter?

A: Create Restful API in PHP and just call the method. use this exaqmple
Update:
 <? PHP
   require_once ( "SiteRestHandler.php");
   $ view = "";
   if (isset ($ _GET & # 91; "view" & # 93;))
   $ view = $ _GET & # 91 ; "view" & # 93 ;;
   / *
     * RESTful service controller
     * URL mapping
     * /
   switch ($ view) {

   case "all":
   // Handle REST Url / site / list /
   $ siteRestHandler = new SiteRestHandler ();
   $ siteRestHandler -> getAllSites ();
   break;

  case "single":
  // Handle REST Url / site / show / < id> /
  $ siteRestHandler = new SiteRestHandler ();
  $ siteRestHandler -> getSite ($ _GET [ "id"]);
  break;

  case "":
  // 404 - not found;
  break;
  }
?>

learn more

A: Sure, but this part is to be done from PHP code side first then on Android.
The PHP code would look something like this
<?php

$api_url = 'http://dummy.restapiexample.com/api/v1/employees';

// Read JSON file
$json_data = file_get_contents($api_url);

// Decode JSON data into PHP array
$response_data = json_decode($json_data);

// All user data exists in 'data' object
$user_data = $response_data->data;

// Cut long data into small & select only first 10 records
$user_data = array_slice($user_data, 0, 9);

// Print data if need to debug
//print_r($user_data);

// Traverse array and display user data
foreach ($user_data as $user) {
    echo "name: ".$user->employee_name;
    echo "
";
    echo "name: ".$user->employee_age;
    echo "

";
}

?>


text:
Q: Compilation of F#/WPF code I find some good post on F#/WPF programming, but it doesn't seem to teach a way to compile/build the code to make binary out of F#/WPF.
What command/tool do I use to build/compile this code into execution binary? Just running fsc or fsi doesn't seem to work.
#light
#I @"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0"
#r @"WindowsBase.dll"
#r @"PresentationCore.dll"
#r @"PresentationFramework.dll"

open System
open System.Windows

(* From Chap 1 - SayHello.cs *)

let win = new Window()
win.Title <- "Say Hello"
win.Show()

#if COMPILED
[<STAThread()>]
do
     let app =  new Application() in
     app.Run() |> ignore
#endif

A: If you want to compile the code using fsc then you'll need to remove the #I and #r commands and use a compiler command line arguments instead. The #light command is not required anymore, so you can just delete first 5 lines. In addition to the #r references, I also had to add System.Xaml.dll (which is probably new in .NET 4)
Then you can compile it using something like:
fsc.exe -r:WindowsBase.dll -r:PresentationCore.dll -r:System.Xaml.dll
        -r:PresentationFramework.dll --target:winexe Main.fs

Running the code in fsi.exe should work just fine (after adding #r "System.Xaml.dll"). Just copy the code and paste it to the F# Interactive (running either in console or in Visual Studio IDE).

A: Running fsc should work. You'll want to pass the --target:winexe command line argument to the fsc.exe.
See F# Compiler Options for more info.


text:
Q: Visual studio and MS build have different build results Lately we (the team I work with and myself) have been seeing something strange between the build results of MS-build and Visual Studio (2015).
The situation
The team I work with has been tasked with refactoring an older and rather large c# project that contains many (150+) projects all bundled into a single sln file. As to be expected merge conflicts occur in the sln file during our work and one of the team members resolved this conflict incorrectly. Leaving the sln file with a missing project reference.
From here on out the behavior of the project is different on 3 location. They are described below

Visual studio of the developer that origionally made the mistake
(note that I assume that this developer has not cleaned his solution)
This programmer has already build and run the project (using visual studio 2015 professional). So all compiled dll files are in the prorammers output folder. This means that Visual studio does not notice that a reference is missing. The programmer can build, run and test the application without any problems.

The build server
The build server (Jenkins) does not run Visual studio, but it uses MS-build 14 to compile the source code. The Jenkins server is configured to run with pipelines, described in groovy. We call ms build by invoking a bat script that runs MS-build over the command line. An example:
"C:\Program Files (x86)\MSBuild\14.0\Bin\amd64\msbuild.exe" "TheSolutionFile.sln" /property:Configuration="Debug" /property:Platform="Any CPU"

Somehow the build will succeed even with the incorrect sln file. I suspect that ms build resolves its own dependencies as the workspace on the buildserver is clean (completely empty) so no leftover dll's can fool the system. (am I correct in assuming this?)

The other team members
The other team members will eventually pull the changes of the broken sln file and they will be in for some 'fun'. When you do not have the dll files in your output folder Visual studio will attempt to rebuild the missing dependencies. But since the references cannot be resolved it will fail and start stacking errors about missing meta data. In the team we all use Visual studio 2015. But we also tried it with 2017 and ran into the same result. The person who originally made the mistake can also end up in this group of he cleans the solution.
The Question
Obviously we are not happy with the fact that the build server accepts the build with a broken sln file (a developer pulling the latest version cannot compile or run the program). Is there a way to get the last two situations in sync (so ms build not accepting a 'broken' sln file to compile)

A:
Is there a way to get the last two situations in sync (so ms build not accepting a 'broken' sln file to compile

That is because MSBuild.exe from command line does not have the same build environment as Visual Studio. You can call MSBuild.exe from VS command promt which has the same biuld environment as Visual Studio.
If you want call ms build by invoking a bat script that runs MS-build over the command line, you can use devenv.exe to build the solution/project from command line:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE>devenv "D:\TestSample\TestProject\TestProject\TestProject.sln" /build Debug /project "TestProject\TestProject.csproj" /projectconfig Debug

For the detail information about devenv.exe you can refer to Devenv Command Line.
Hope this can help you.

A: My advice:
The .sln file is just a collection of project files.  Create a brand new one, and add in your proj files one by one.  Forget the code-merge-conflict-resolution drama.
The voodoo in the .sln file is too much voodoo.  Let VS do it for you...as you add each project in, one by one.

File / New / Project ::: Installed / Templates / Other Project Types / Visual Studio Solution ::: Blank
  Solution.

One other hint.  If you still have issues, then open up each proj, and any "by project" references, delete them and re-add them.  Sometimes the GUID's get mixed up, especially over a long code-merge history.


text:
Q: PF / IceFloor - Redirecting a service / port to a specific IP What I'm trying to do is redirect all requests to a certain service or port to a specific IP address with IceFloor as the frontend for PF.
In the example I'm posting en1 is my only enabled network adapter, 192.168.0.1 is the server I'm trying to redirect to and port 53 is the port I want to redirect all traffic for to that IP.
Icefloor has been letting me enter (but not completely add to the ruleset) these two lines through the custom rules page.
I don't get a bad syntax warning as though I've put in a bad rule, but the rules aren't appearing in either the icefloor custom rules GUI list or the icefloor.custom_rules file.
rdr on en1 inet proto tcp from any to any port 53 -> 192.168.0.1 port 53
rdr on en1 inet proto udp from any to any port 53 -> 192.168.0.1 port 53

Any ideas what I'm doing wrong, or if this is even possible?
Additional info:

*

*OS X 10.11.1

*I'm not running a DNS server on EN1

*I am running a DNS server on 192.168.0.1

*EN1 and 192.168.0.1 are on the same host, 192.168.0.1 is on a virtual adapter belonging to an OpenVPN TUN.

*The purpose is to redirect DNS requests to any IP address to the DNS server I'm running.

*EN1 is on 192.168.16.0/24

*EN0 is a disabled adapter configured to use DHCP when active


text:
Q: Set the property 'text-overflow: ellipsis' and then its sibling element's text can't align to it

  p{
    width: 300px;
    margin: 0 auto;
  }
  span{
    display: inline-block;
  }
  .left{
    width: 40%;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }

    TestTestTestTest
    Test

And then it  will display like
this,
I think the reason why display like this maybe the property 'overflow: hidden' created a  bfc, so  I set the property 'overflow: hidden' or 'float: right' for '.right', and then '.right' align to '.left'.
but I've seen description of BFC from MDN, it says that display:inline-block will creating a BFC,  So the BFC of each span tags should already be created because of  the css rule span {display: inline-block}, but why they are not align before I set the properties for '.right' ?
finally,please don't focus on my poor English, I just wanna find the answer for the question I've met, and I think I will get it by this way . Thank you!
O(∩_∩)O~

A: Just give  vertical-align: top; to span. Because inline-block default vertical-align is baseline.

p{
    width: 300px;
    margin: 0 auto;
  }
  span{
    display: inline-block;
    vertical-align: top;
  }
  .left{
    width: 40%;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }

    TestTestTestTest
    Test


text:
Q: how to convert and download data from webpage into PDF i am developing a web application using PHP Codeigniter, i want a code to display and download a data from web page into a PDF format.

A: Download mPDF and Extract it to application/third_party/ Folder
Create a new file in application/libraries/ name it M_pdf.php
In M_pdf.php file
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

include_once APPPATH.'/third_party/mpdf/mpdf.php';

class M_pdf {

    public $param;
    public $pdf;

    public function __construct($param = '"en-GB-x","A4","","",10,10,10,10,6,3')
    {
        $this->param =$param;
        $this->pdf = new mPDF($this->param);
    }
}

Then successfully integrated mPDF in CodeIgniter.
How to Used,
Load the mPDF library in Controller as the controller below,
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cont_letter_pdf extends CI_Controller {

    public function __construct() {
        parent::__construct();

        $this->load->library('m_pdf'); //load mPDF library
    }

    public function pdf_download()
    {
        $data = [];
        //load the view and saved it into $html variable
        $html=$this->load->view('welcome_message', $data, true);

        //this the the PDF filename that user will get to download
        $pdfFilePath = "output_pdf_name.pdf";

        //load mPDF library
        $this->load->library('m_pdf');

       //generate the PDF from the given html
        $this->m_pdf->pdf->WriteHTML($html);

        //download it.
        $this->m_pdf->pdf->Output($pdfFilePath, "D");

    }

I learn this from the following url. You can also view the Tutorial from here as well.
https://arjunphp.com/generating-a-pdf-in-codeigniter-using-mpdf/


text:
Q: JQuery scrolltop is scrolling up rather than down For some reason all of my Scrolltop jquery functions are working great on this page: http://www.nvrentals.net/ -except for the scroll function that's applied to each "Client icon".
Here's my goal: in the mobile phone width (the site is responsive) - when a user clicks on the "Concert Halls" icon, they should scroll down to the open panel below....
Problem: right now, when it's clicked, the user scrolls up to a random spot on the page.
I can't figure out what's going on - the stuff works fine in JSfiddle: http://jsfiddle.net/gGuDF/
Here's my JS:
 $('.scrollerr').click(function(e){

    $("html, body").animate({scrollTop:$('.scrollee').position().top}, 600);

    e.preventDefault();

});

A: Have you tried,
$('.scrollee').offset().top

I havent tested it, or maybe try this,
 var $scrollee = $(this).find('.scrollee');

 var newScroll = parseInt( $scrollee.position().top )
    + parseInt( $scrollee.parent().scrollTop() );

  $("html, body").animate({scrollTop:newScroll}, 600);

OR
 $('.scrollerr .scrollee').click(function(e){

$("html, body").animate({scrollTop:$(this).position().top}, 600);

e.preventDefault();

});


text:
Q: Find the image of an element without clear function rule. How can I find $f(4)$ from the following equation:
$$f(x) + f(2x+1) = 6x+10$$

A: Let $g(x)=f(x)-2x-4$ to get
$$g(x)+g(2x+1)=0$$
Substitute $x\mapsto2^x-1$ and let $h(x)=g(2^x-1)$ to get
$$h(x)+h(x+1)=0$$
We can produce infinitely many solutions for $h$. An obvious form can be given by trigonometric functions, and more generally Fourier series. As a simple example:
$$h(x)=A\sin(\pi x)$$
$$g(x)=A\sin(\pi\log_2(x+1))$$
$$f(x)=2x+4+A\sin(\pi\log_2(x+1))$$
$$f(4)=12+A\sin(\pi\log_2(5))$$
which depends on the arbitrary value $A$. Thus there is no unique solution, given the conditions.

A: $f(x)=2x+4$ satisfies the equation so $f(4)=12$


text:
Q: Graph scrolling using pyqt5 and malplotlib previous question (link)
Here i want that when i move the scroll bar using  mouse it will not scroll the graph but when i leave the mouse then the graph will be updated. Here every time axis limit are updating but i want it will update the axis limit when i leave the mouse moving the scroll bar at a certain position. Note : Here y -axis trick label position will be fixed and it would be visible but value will update when i scroll the graph.and i also want that scroll bar will start from right position.
Here my program :
import sys
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from PyQt5.QtWidgets import QMainWindow,QVBoxLayout
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtCore, QtGui, QtWidgets
import datetime
from matplotlib.dates import num2date, date2num
from mpl_finance import candlestick_ochl as candlestick
import numpy as np
import matplotlib.ticker as ticker
import matplotlib.dates as mdates
import pylab as pl
class MainWindow_code_serarch(object):

    def setup_code_serarch(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1070, 680)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget1 = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget1.setGeometry(QtCore.QRect(17, 30, 741, 13))
        self.verticalLayoutWidget1.setObjectName("verticalLayoutWidget")
        self.verticalLayout1 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget1)
        self.verticalLayout1.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout1.setObjectName("verticalLayout1")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(17, 10, 1040, 603))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.figure = Figure(figsize=(100,7.2), dpi=80, facecolor='k')
        self.canvas = FigureCanvas(self.figure)
        self.canvas.draw()
        # self.widget = QtWidgets.QWidget()
        # self.scroll_area = QtWidgets.QScrollArea(self.widget)
        # self.scroll_area.setWidget(self.canvas)
        # self.verticalLayout.addWidget(self.scroll_area)
        self.scroll = QtWidgets.QScrollBar(QtCore.Qt.Horizontal)
        self.axes, self.axes2 = self.figure.subplots(nrows=2, sharex=True)

        self.verticalLayout.addWidget(self.canvas)
        self.verticalLayout.addWidget(self.scroll)

        data = {
            'date': ['2018/10/29','2018/10/30', '2018/11/03', '2018/11/04', '2018/11/05', '2018/11/07', '2018/11/10', '2018/11/11','2018/11/12','2018/11/13'],
            'open': [8824,8824, 8726.31, 8642.14, 8531.51, 8630.25, 8602.50, 8640.22,8202.50, 8610.22],
            'high': [8858,8858, 8748.60, 8551.36, 8653.16, 8476.69, 8630, 8570.56 ,8602.50, 8640.22],
            'low': [8688,8688, 8743.67, 8550.76, 8449.50, 8631.83, 8602.18, 8743.22 ,8502.50, 8540.22],
            'close': [8820,8820, 8747.17, 8550.52, 8553., 8517.10, 8628.78, 8588.52 ,8602.50, 8640.22],
            'volume': [17759.56,17759.56, 120000.17, 18739.52, 38599.50, 16517.10, 17723.78, 15588.52 ,28602.50, 28640.22]
        }
        x = date2num([datetime.datetime.strptime(d, '%Y/%m/%d').date() for d in data['date']])
        t= np.arange(len(data['date']))
        candle_trace = zip(t, data['open'], data['high'], data['low'], data['close'], data['volume'])
        candlestick(self.axes, candle_trace, width=.75, colorup='g', colordown='r')
        self.axes2.plot(t, [1, 2, 3, 4, 7, 8, 9,6,6,9])
        self.axes.set_position([0.02, 0.37, 0.88, 0.6])
        self.axes2.set_position([0.02, 0.15, 0.88, 0.22])
        self.axes.tick_params(axis='both', color='#ffffff', labelcolor='#ffffff')
        self.axes.yaxis.tick_right()
        self.axes2.tick_params(axis='both', color='#ffffff', labelcolor='#ffffff')
        self.axes2.grid(color='lightgray', linewidth=.5, linestyle=':')
        self.axes.grid(color='lightgray', linewidth=.5, linestyle=':')
        self.axes2.yaxis.tick_right()
        self.axes.autoscale_view()
        self.axes2.autoscale_view()
        self.axes.set_facecolor('#041105')
        self.axes2.set_facecolor('#041105')
        # N = len(dates)
        self.axes.set_xticks(range(0, len((x)), 1))
        self.axes.set_xticklabels([mdates.num2date(d).strftime('%b-%d') for d in x])
        self.axes.set_xticklabels([mdates.num2date(d).strftime('%Y-%m-%d') for d in x])
        self.axes2.set_xticklabels([mdates.num2date(d).strftime('%Y-%m-%d') for d in x])
        self.canvas.draw()
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 246, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        # self.pushButton.clicked.connect(self.graphShowCode)
        self.step = .1
        self.setupSlider()

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        # self.pushButton.setText(_translate("MainWindow", "OK"))

    def setupSlider(self):
        self.lims = np.array(self.axes2.get_xlim())
        print("limit"+str(self.lims))
        self.scroll.setPageStep(self.step * 100)
        self.scroll.actionTriggered.connect(self.update)
        self.update()

    def update(self, evt=None):
        r = self.scroll.value() / ((1 + self.step) * 100)
        l1 = self.lims[0] + r * np.diff(self.lims)
        l2 = l1 + np.diff(self.lims) * self.step
        self.axes2.set_xlim(l1, l2)
        self.axes.set_xlim(l1, l2)
        print(self.scroll.value(), l1, l2)
        self.figure.canvas.draw_idle()
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = MainWindow_code_serarch()
    ui.setup_code_serarch(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

A: QScrollBar inherits a comprehensive set of signals from QAbstractSlider.
I have used sliderReleased(). because it is emit when the user releases the slider.To start scroll bar from right position. I initiate scroll bar value (99) Because here i find scroll bar minimal value is (0) and maximum value is (99).
my program :
import sys
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from PyQt5.QtWidgets import QMainWindow,QVBoxLayout
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtCore, QtGui, QtWidgets
import datetime
from matplotlib.dates import num2date, date2num
from mpl_finance import candlestick_ochl as candlestick
import numpy as np
import matplotlib.ticker as ticker
import matplotlib.dates as mdates
import pylab as pl
class MainWindow_code_serarch(object):

    def setup_code_serarch(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1070, 680)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget1 = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget1.setGeometry(QtCore.QRect(17, 30, 741, 13))
        self.verticalLayoutWidget1.setObjectName("verticalLayoutWidget")
        self.verticalLayout1 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget1)
        self.verticalLayout1.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout1.setObjectName("verticalLayout1")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(17, 10, 1040, 603))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.figure = Figure(figsize=(100,7.2), dpi=80, facecolor='k')
        self.canvas = FigureCanvas(self.figure)
        self.canvas.draw()
        # self.widget = QtWidgets.QWidget()
        # self.scroll_area = QtWidgets.QScrollArea(self.widget)
        # self.scroll_area.setWidget(self.canvas)
        # self.verticalLayout.addWidget(self.scroll_area)
        self.scroll = QtWidgets.QScrollBar(QtCore.Qt.Horizontal)
        self.axes, self.axes2 = self.figure.subplots(nrows=2, sharex=True)

        self.verticalLayout.addWidget(self.canvas)
        self.verticalLayout.addWidget(self.scroll)
        self.scroll.setValue(99)

        data = {
            'date': ['2018/10/29','2018/10/30', '2018/11/03', '2018/11/04', '2018/11/05', '2018/11/07', '2018/11/10', '2018/11/11','2018/11/12','2018/11/13'],
            'open': [8824,8824, 8726.31, 8642.14, 8531.51, 8630.25, 8602.50, 8640.22,8202.50, 8610.22],
            'high': [8858,8858, 8748.60, 8551.36, 8653.16, 8476.69, 8630, 8570.56 ,8602.50, 8640.22],
            'low': [8688,8688, 8743.67, 8550.76, 8449.50, 8631.83, 8602.18, 8743.22 ,8502.50, 8540.22],
            'close': [8820,8820, 8747.17, 8550.52, 8553., 8517.10, 8628.78, 8588.52 ,8602.50, 8640.22],
            'volume': [17759.56,17759.56, 120000.17, 18739.52, 38599.50, 16517.10, 17723.78, 15588.52 ,28602.50, 28640.22]
        }
        x = date2num([datetime.datetime.strptime(d, '%Y/%m/%d').date() for d in data['date']])
        t= np.arange(len(data['date']))
        candle_trace = zip(t, data['open'], data['high'], data['low'], data['close'], data['volume'])
        candlestick(self.axes, candle_trace, width=.75, colorup='g', colordown='r')
        self.axes2.plot(t, [1, 2, 3, 4, 7, 8, 9,6,6,9])
        self.axes.set_position([0.02, 0.37, 0.88, 0.6])
        self.axes2.set_position([0.02, 0.15, 0.88, 0.22])
        self.axes.tick_params(axis='both', color='#ffffff', labelcolor='#ffffff')
        self.axes.yaxis.tick_right()
        self.axes2.tick_params(axis='both', color='#ffffff', labelcolor='#ffffff')
        self.axes2.grid(color='lightgray', linewidth=.5, linestyle=':')
        self.axes.grid(color='lightgray', linewidth=.5, linestyle=':')
        self.axes2.yaxis.tick_right()
        self.axes.autoscale_view()
        self.axes2.autoscale_view()
        self.axes.set_facecolor('#041105')
        self.axes2.set_facecolor('#041105')
        # N = len(dates)
        self.axes.set_xticks(range(0, len((x)), 1))
        self.axes.set_xticklabels([mdates.num2date(d).strftime('%b-%d') for d in x])
        self.axes.set_xticklabels([mdates.num2date(d).strftime('%Y-%m-%d') for d in x])
        self.axes2.set_xticklabels([mdates.num2date(d).strftime('%Y-%m-%d') for d in x])
        self.canvas.draw()
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 246, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        # self.pushButton.clicked.connect(self.graphShowCode)
        self.step = .1
        self.setupSlider()

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        # self.pushButton.setText(_translate("MainWindow", "OK"))

    def setupSlider(self):
        self.lims = np.array(self.axes2.get_xlim())
        print("limit"+str(self.lims))
        self.scroll.setPageStep(self.step * 100)
        # self.scroll.actionTriggered.connect(self.update)
        self.scroll.sliderReleased.connect(self.update)

        self.update()

    def update(self, evt=None):
        r = self.scroll.value() / ((1 + self.step) * 100)
        l1 = self.lims[0] + r * np.diff(self.lims)
        l2 = l1 + np.diff(self.lims) * self.step
        self.axes2.set_xlim(l1, l2)
        self.axes.set_xlim(l1, l2)
        print(self.scroll.value(), l1, l2)
        self.figure.canvas.draw_idle()
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = MainWindow_code_serarch()
    ui.setup_code_serarch(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


text:
Q: Query website(that requires login information) with input parameters and retrieve results I'm a noob at this so can anyone tell me how to login to a website and fill forms and retrieve results that can be parsed into say .csv. For instance, a website where you enter certain parameters and the server returns products that best match your input parameters. I need to retrieve the list of products with their specifications and parse them into .csv. Doing that requires me to select certain buttons on the webpage which seem to be javascript objects. I tried mechanize but it doesn't seem to work for javascript objects. I would prefer to post my queries in python. Thanks!

A: You have two options I can think of:
1) Figure out what the fields generated by the javascript are named, or their naming scheme, and submit the values directly to the form handler -- eliminating the need to even deal with the input page.
2) Use a framework that emulates a "real" browser and is capable of processing javascript.  This question has some suggestions for frameworks, but having never used one, I can't suggest any myself.


text:
Q: jQuery replace html in span Is there an issue with replacing the contents of a <span in jQuery.
I have this;

  some html

and
$('.DimensionList').html("This is the new html");

What I'm finding is that in FF the contents of the span are being added to.  So the new HTML sits above the old.
In IE6, yes I have to cater for it, it's doing much the same.
EDIT
I have edited the question to show that there is html in the replacement html

A: if you needed to use .html() you could empty it first:
$('.DimensionList').html("").html("This is the new html");

A: Since there's no markup in your replacement text, use text() instead of html():
$('.DimensionList').text("This is the new html");

A: You've capitalized DimensionList in your javascript and it is lowercase in your HTML source. They need to be identical. In other words, it is case sensitive.

A: Have you tried .text() ? It is similar to .html()
From jQuery's Documentation:

Unlike the .html() method, .text() can
  be used in both XML and HTML
  documents
We need to be aware that this method
  escapes the string provided as
  necessary so that it will render
  correctly in HTML. To do so, it calls
  the DOM method .createTextNode(),
  which replaces special characters with
  their HTML entity equivalents (such as
  < for <).

http://api.jquery.com/text/


text:
Q: MySQL Multitable Query Problem I have a problem querying multiple tables in MySQL and am currently at my wits end.
I have unique IDs in each table, and am using an INNER JOIN to combine them; I am quite new to SQL and this may be the wrong method, hence me posting here:
Query:
SELECT res.UserID, res.QuizID, res.QuizResult, u.UserID, u.UserLogin, q.QuizID, q.QuizName, q.QuizFile
FROM results res
INNER JOIN users u ON (res.UserID = u.UserID)
INNER JOIN quiz q ON (res.QuizID = q.QuizID)

Table users contains
UserID
UserLogin
UserPass

Table quiz contains
QuizID
QuizName
QuizFile

Table results contains
UserID
QuizID
QuizResults

Can anybody please tell me why I am getting a cartesian product, and how I should go about fixing it?

A: Try this:

SELECT res.UserID, res.QuizID, res.QuizResult, u.UserID, u.UserLogin, q.QuizID, q.QuizName, q.QuizFile FROM results as res INNER JOIN users as u ON res.UserID = u.UserID INNER JOIN quiz as q ON res.QuizID = q.QuizID

A different way to realize something like an INNER JOIN is this:+

SELECT res.UserID, res.QuizID, res.QuizResult, u.UserID, u.UserLogin, q.QuizID, q.QuizName, q.QuizFile
FROM results as res,users as u ,quiz as q
WHERE res.UserID = u.UserID
AND res.QuizID = q.QuizID


text:
Q: Why does light keep it's direction when passing through glass? It is assumed that light does not propagate through a different medium as such but by interacting with electrons of atoms it reaches. So photons crash into electrons of the medium's atoms, elevate their energy level and when falling back to their original energy level, they themselves create photons of the wavelength h/E. The question is: what about direction? Let's say the point source is a laser whose photons pass through a glass, why does it not scatter everywhere as the electrons falling back emit photons in 360° x 180° direction?

A: Glass typically has a very high bandgap due to its low refractive index so photons of visual wavelengths typically don't have enough energy to cause the excitation of electrons in glass since the photons would require an energy $\geq E_g$. Thus, the photons are simply transmitted through the glass since they don't have enough energy to interact with the electrons, and the direction and angle can be described with the refractive index.
Beside this, one can also discuss the topic of scattering, which can be quite complex if one wants it to be. Shortly put, the roughness of a surface quantifies the angle at which we'll observe scattered photons. Worst case would be Lambertian scattering, where it is scattered in all directions in a half-sphere and best case would be no scattering but only transmission.


text:
Q: What if anything, is Symfony 3 I keep hearing about Symfony 3, in particular the new directory structure, but I can find nothing about a release date. Are there plans to release a new major iteration of symfony?

A: Yes there are plans but nothing definite yet.
The community section of the Symfony 2 site has plenty of information on these sorts of things.
From: http://symfony.com/doc/current/contributing/community/releases.html
The work on a new major version of Symfony starts whenever enough
major features breaking backward compatibility are waiting on the todo-list.

The next major version will be 3.0.
The next major long term release will be S2.7 schedule for May of 2015.  I would not be surprised if serious work on S3.0 starts after that release but that is just a guess.  Check the development mailing list and chat rooms for more information.


text:
Q: rails named_scope issue with eager loading Two models (Rails 2.3.8):
User; username & disabled properties; User has_one :profile
Profile; full_name & hidden properties
I am trying to create a named_scope that eliminate the disabled=1 and hidden=1 User-Profiles.  Moreover, while the User model is usually used in conjunction with the Profile model, I would like the flexibility to be able specify this using the :include => :profile syntax.
I have the following User named_scope:
  named_scope :visible, {
    :joins => "INNER JOIN profiles ON users.id=profiles.user_id",
    :conditions => ["users.disabled = ? AND profiles.hidden = ?", false, false]
  }

This works as expected when just reference the User model:
>> User.visible.map(&:username).flatten
=> ["user a", "user b", "user c", "user d"]

However, when I attempt to include the Profile model:
User.visible(:include=> :profiles).profile.map(&:full_name).flatten

I get an error that reads:
NoMethodError: undefined method `profile' for #<User:0x1030bc828>

Am I able to cross model-collection boundaries in this manner?

A: To access a user's profile, you have to use something like
@user = User.visible(:include => :profiles)
@user.first.profile

Or, if what you want is all full_names, I believe you should do something like
# untested
User.visible(:include=> :profiles).map(&:profile).collect{ |p| p.full_name }

But probably there's a better way... It doesn't look pretty =P


text:
Q: ComboBox Selected Value to be Blank Uses: VS 2012;
I've a combobox attached to a datasource in my form. And things work fine. When I run the form, again everything works fine; I can select an item in the dropdown list and it updates to the datasource as well. My problem comes when I need to deselect/revert what I have selected after I saved or Remove what I have select (basically should go as null for that field value).
Our legacy system was built in Delphi 3 & 5, and users got a feature of right-clicking on the dropdown list and get a small popup like button named

Blank

which blanks what have been selected. I could not find anything that will do the same what ever user have selected in .NET's combo box.

A: You can add a new item in dropdown named -Select-( or something similar name) by using following code:

drp.DataSource = dataSet;
drp.DataBind();
// do it after binding
    drp.Items.Insert(0, new ListItem("-Select-", "NA"));

If you are binding in xaml then on page_load event you can write only this line
 drp.Items.Insert(0, new ListItem("-Select-", "NA"));

Now if user want to deselect choice, he/she will simply select -Select- item.

A: Whilst thanking all of your Answers and suggestions, I used @V4Vendetta's idea and composed my solution.
Similarly to deleting a record in a datagridview where you click Delete key, I took the same concept and associated my solution with Delete Key.
What I did was created a handler for ComboBox's Keypress Event like:
private void comboBox_KeyPress(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
            (sender as ComboBox).SelectedIndex = -1;
    }
}

And linked to every ComboBox's available
ComboBox1.KeyDown += new KeyEventHandler(comboBox_KeyPress);
ComboBox2.KeyDown += new KeyEventHandler(comboBox_KeyPress);

Now when user clicks Delete key while the ComboBox selected/active, it gets blank.


text:
Q: Meteor: How to create a user account on the server without sending plain text password over the wire? I am creating an admin interface and the admin needs the ability to create user accounts, pick and change the password.
If I try to call Account.createUser on the Client, it automatically logs the user in as the new user, which is what I do not want.
An approach that will work but I am afraid might be insecure is:

*

*Call a server side Meteor method with the username and password for the new account that the admin has picked.

*On the server I can use Accounts.createUser to create the new user with password and it will return the new UserId.
But with this approach I am sending the password in plain text over the wire. We could use https and ssl and I think we will be safe, but is there a more secure way to do this?

A: A much better practice which avoids any user knowing any other user's password is to create the account on the server (as you suggested) but don't specify a password, instead let the user pick it later. From the docs

Call createUser with the email option and then call
  Accounts.sendEnrollmentEmail. This will send the user an email with
  a link to set their initial password.