text:
Q: 'data-rel' lightbox not working with ajax content I have this piece of code which is a partial for a one page website and i call it with ajax to fill the 'portfolio content' of the website.

{{ $data['generals']->portfolio_title }}

{{ $data['generals']->portfolio_secondary_title }}

        @foreach($data['portfolio'] as $port)

                background_image}}" alt="">

{{$port->title}}

{{$port->body}}

                    background_image}}" data-rel="lightbox" class="expand">

        @endforeach

When i call it with ajax the data-rel="lightbox" is not working. If i don't call it and i just include the code in the project it is working just fine. Why AJAX won't let it work?
I call it like this:
function appendData(div, url){
    $.ajax({
        url: url,
        success: function (data) {
            $(div).append(data);
        }
    });
}
appendData('#portfolio');

I am using this plugin
And I call it like this :
  $(function(){
    $('[data-rel="lightbox"]').lightbox();
  });

Thanks!

A: You've to initialize the plugin after adding the new DOM to the document :
function appendData(div, url){
    $.ajax({
        url: url,
        success: function (data) {
             $(div).append(data);

             $('[data-rel="lightbox"]').lightBox(); //init plugin for new elements
        }
    });
}

NOTE : You should initialize your plugin inside success callback where the new elements are already appended to the DOM, it will not work if you call it after appendData since $.ajax request is asynchronous.
Hope this helps.


text:
Q: Plaid link not opening w/ rails ENV After following the Plaid integration tutorial on the Stripe website, I am unable to get the plaid link to work.
I have tried to replace the "env" and "key" variables with environment keys as follows:
<button id='linkButton'>Open Plaid Link</button>
<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js">
</script>
<script>
var linkHandler = Plaid.create({
  env: ENV['PLAID_ENV'],
  clientName: 'Divco',
  key: ENV['PLAID_PUBLIC_KEY'],
  product: ['auth'],
  selectAccount: true,
  onSuccess: function(public_token, metadata) {
    // Send the public_token and account ID to your app server.
    console.log('public_token: ' + public_token);
    console.log('account ID: ' + metadata.account_id);
  },
  onExit: function(err, metadata) {
    // The user exited the Link flow.
    if (err != null) {
      // The user encountered a Plaid API error prior to exiting.
    }
  },
});

// Trigger the Link UI
document.getElementById('linkButton').onclick = function() {
  linkHandler.open();
};

When I step back away from having "fancy" environment variables, inserting my keys directly, I don't have an issue. I feel like I have mistyped something... but for my life, I can't find it.

A: In fact, ENV is a Ruby call. You need to use <%= ENV[*] %> in your javascript and add the .erb extension to your javascript file.
You can use gem like Figaro to easily deal with ENV variables.

redpajama_set_name: RedPajamaStackExchange


text:
Q: plotly python plot method launch browser my problem is that the plotly python plot method
plot_url = py.plot(fig, filename='box-plot')

automatically launch the web browser, is it possible to prevent this behaviour ?
Thanks for your answers!

A: Plotly for Python can be configured to render locally inside Jupyter (IPython) notebooks, locally inside your web browser, or remotely in your online Plotly account.
Offline mode will save an HTML file locally and open it inside your web browser.
plot() takes options:

auto_open (default=True) -- Toggle browser options
   * True: open this plot in a new browser tab
   * False: do not open plot in the browser, but do return the unique

plot_url = py.plot(fig, filename='box-plot', auto_open=False)

A: Another way is to use py.iplot
plot_url = py.iplot(fig, filename='box-plot')

I had it this way and wanted it to actually show me the graph. So then I took away the 'i' to match your example and it worked :P

A: Just to add on this. import plotly.plotly as py will not work anymore.
plotly.plotly is deprecated.
Need to install chart_studio
python2 -m pip install chart-studio

This will change into
import chart_studio.plotly as py


text:
Q: Improve SQLAlchemy update efficiency I have two tables, users (~200.000) and tweet (~2.000.000)
I need to update all users, with the number of tweets, favourites(of their tweets), replies, retweets.
This is inside a script:
@classmethod
def get_user_tweet_counts(cls, user_id):
    return (db_session
        .query(
            func.sum(Tweet.favorite_count).label('favorite_count'),
            func.sum(Tweet.retweet_count).label('retweet_count'),
            func.sum(Tweet.reply_count).label('reply_count'),
            func.count(Tweet.id).label('tweet_count'))
        .filter(Tweet.user_id == user_id)
        .group_by(Tweet.user_id).first())  # This will always be one result, should I query differently?

db_session:
engine = create_engine('postgresql://tweetsql:tweetsql@127.0.0.1/tweetsql')
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=True,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

The 10 minute loop:
for user in all_users:
    update_count += 1
    aggregation_result = Tweet.get_user_tweet_counts(user.id)
    user.total_tweet_favourites = aggregation_result[0] or 0
    user.total_tweet_retweets = aggregation_result[1] or 0
    user.total_tweet_replies = aggregation_result[2] or 0
    user.tweet_count = aggregation_result[3] or 0
User.save()  # this just calls db_session.commit()
# We only commit the session once to speed things up

User and Tweet are declared like:
User(Base), Tweet(Base) (from the db_session snippet).
While this is running, python hits 80% cpu, and ~600mb memory. How can I make this better? Tweet has index on user_id and its own id.

A: Here is a great answer by the author of SQLAlchemy. Basically, you'll want to bypass the ORM if you need to scale to large number of rows.
In your particular situation, you can write a single query to achieve the same result using SQL aggregation:
UPDATE users SET
  total_tweet_favourites = aggregated.total_tweet_favourites,
  total_tweet_retweets = aggregated.total_tweet_retweets,
  total_tweet_replies = aggregated.total_tweet_replies,
  tweet_count = aggregated.tweet_count
FROM (
  SELECT
    users.id AS id,
    SUM(tweets.favorite_count) AS total_tweet_favourites,
    SUM(tweets.retweet_count) AS total_tweet_retweets,
    SUM(tweets.reply_count) AS total_tweet_replies,
    COUNT(tweets.id) AS tweet_count
  FROM users JOIN tweets ON tweets.user_id = users.id
  GROUP BY users.id
) aggregated
WHERE users.id = aggregated.id;

To translate this to SQLAlchemy:
aggregated = session \
    .query(
        User.id.label("id"),
        func.sum(Tweet.favorite_count).label("total_tweet_favourites"),
        func.sum(Tweet.retweet_count).label("total_tweet_retweets"),
        func.sum(Tweet.reply_count).label("total_tweet_replies"),
        func.count(Tweet.id).label("tweet_count")) \
    .select_from(User) \
    .join(Tweet) \
    .group_by(User.id) \
    .subquery() \
    .alias("aggregated")
query = User.__table__ \
    .update() \
    .values(
        total_tweet_favourites=aggregated.c.total_tweet_favourites,
        total_tweet_retweets=aggregated.c.total_tweet_retweets,
        total_tweet_replies=aggregated.c.total_tweet_replies,
        tweet_count=aggregated.c.tweet_count) \
    .where(User.__table__.c.id == aggregated.c.id)
session.execute(query)


text:
Q: changing the href or removing the onclick for a button Next

I want to change the href of this button and also removing on click. Could anybody tells me how to do it in jquery?

A: You can try something like this:
var el = $("#element");
if (el){
    el.unbind("click");
    el.attr("href", "newpage.htm");
}

A: Here is a demo attached: http://jsfiddle.net/xavi3r/DQ4Sn/
$('#btnContinuePhone').click(function(){
   return false;
});
$('#btnContinuePhone').attr('href','http://newurl.com');

A: This is my solution :
$('#btnContinuePhone').attr('href', 'what ever you like');
$('#btnContinuePhone').click(function(){ return false;});

Or you can do that alternativly:
$('#btnContinuePhone').attr('href', 'what ever you like');
$('#btnContinuePhone').click(function(e){ e.preventDefault(); });


text:
Q: Avoid selection in a form when double-click In excel-2007 I have a macro that when double clicking a cell, a form will open.
When the relevant cell is located within the range in which the form will appear, an undesired selection is carried out in the form.
How can I avoid this selection?

From a suggested edit by hammejdp on barrowc's answer:
I use this (i.e. BeforeDoubleClick event) already but not fix the problem
Private Sub Workbook_SheetBeforeDoubleClick(ByVal sh As Object, ByVal target As Range, cancel As Boolean)

Call s_Click_DoubleClick(sh, target, cancel)

End Sub

Private Sub Workbook_SheetBeforeRightClick(ByVal sh As Object, ByVal target As Range, cancel As Boolean)

Call s_Click_DoubleClick(sh, target, cancel)

End Sub

Private Sub s_Click_DoubleClick(sh, target, cancel)

Application.ScreenUpdating = False

If sh.Name <> "Legende" Then
    cancel = True
    ' Maak gebruik van een range
    vRowCount = target.Rows.Count
    vColumnCount = target.Columns.Count
    f_Input.TextBox1.Value = vColumnCount

A: If you are using the BeforeDoubleClick event, try setting Cancel to True within the event handler

A: Setting Cancel = True does not resolve the issue.  To replicate the error, create a User Form with a List Box and set the List Box Row Source to a range of cells.  In a worksheet's BeforeDoubleClick event, insert code to launch the form (e.g. frmMyform.Show).  Now double-click somewhere in the center of the worksheet, in the area on the screen where the form will appear.  What will happen is the second click of your double-click will be interpretted as trying to make a selection on the form.
Here is another way to replicate the problem.  Do the same as above, but during your double click HOLD DOWN the second click.  As you will see, your user form appears before you even release the second click of the double-click.  While holding down the mouse, you can drag the mouse around and see that when you let go of the second click, the mouse actually selects the item in the list box where the mouse pointer is located.
To summarize, the intention of the poster is that double-clicking in a cell will launch a form.  The effect is that it does indeed launch the form, BUT ALSO interprets the second click in the double-click as also a click on that form.  Setting Cancel = True does not resolve the issue.

A: Setting Cancel = True will not work.  Here is some code that will resolve the issue.  It's not pretty, but it works.  First, disable the ListBox when the user form initializes:
Private Sub UserForm_Initialize()
    Me.listMyList.Enabled = False
End Sub

This will prevent the second click from the BeforeDoubleClick event from being interpreted as a selection in the List box on the user form (or rather, it will block the ability for the second click to be interpreted as such because the control is not Enabled).  Next, enable the ListBox on the user form's MouseDown event:
Private Sub UserForm_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    Me.listMyList.Enabled = True
End Sub

It's not pretty, but it works.

A: The original question asked is from 2012 but I have faced the same issue today with Microsoft 365 (Win 10 Home 64bit, 64-bit Office). Tried all of the suggestions here but none worked reliably. (After many doubleclicks) This seems to be working for me with a modal userform. I used Sleep() since 1 second seemed a bit long.
On the sheet with BeforeDoubleClick event:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    Application.OnTime (Now + TimeValue("00:00:00")), "mdlInventory.Load_UserForm"
    Call mdlInventory.Inventory_DblClick ' Some extra code unrelated to the userform.
    Cancel = True

End Sub

On mdlInventory (standard module):
Sleep declaration (I am not very versed with these declarations, might be missing something)
#If VBA7 Then ' Excel 2010 or later
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr)
#Else ' Excel 2007 or earlier
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)
#End If

and the sub that loads the userform:
Private Sub Load_UserForm()

    Sleep (50)
    DoEvents
    Load frm_Inventory
    frm_Inventory.Show

End Sub

50 ms sleep seems to be doing the job (actual sleep maybe a little more due to timer resolution). I didn't bother testing for less. Don't think Cancel=True is required, but it helps with cursor getting stuck inside the double clicked cell after userform is dismissed.

A: The best solution I found so far is putting a small delay in the initialize routine of the form's code as such:
Private Sub UserForm_Initialize()
Application.Wait (Now + #12:00:01 AM#)
End Sub
The minimum increment of time seems to be 1 second. If anyone has a cleaner solution or is able to reduce the delay to less than 1 second, kindly share. Note that the "Sleep" function does not work here in preventing the form click (Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)).


text:
Q: Is there a way to check for unused indexes in google datastore? I would like to know if there is a way to get the list of unused index in datastore? If not, is there an easy work around way to delete the ones that are not in use?

A:
is there an easy work around way to delete the ones that are not in use?

gcloud datastore indexes cleanup index.yaml will delete all indexes that are no longer present in your index.yaml file

A: There are two types of indexes in Cloud Datastore: built-in and composed.
If you're using composed indexes, you can get the count of indexes per kind with the following command:
gcloud --project=PROJECT_ID beta datastore indexes list | grep 'kind: ' | sort | uniq -c

However, this command doesn't work with the built-in indexes but there is a feature request for that, which you can find here.
Other than that, you would need to implement some logging on your end in order to track the usage of indexes.


text:
Q: Как исправить ошибку при загрузки приложения в TestFlight На почту пришла следующая ошибка сборки
ITMS-90428: Invalid Swift Support - The files libswift_Concurrency.dylib don't match /Payload/6 Sense.app/Frameworks/libswift_Concurrency.dylib. Make sure the files are correct, rebuild your app, and resubmit it. Don't apply post-processing to /Payload/6 Sense.app/Frameworks/libswift_Concurrency.dylib.


text:
Q: Completing an entry from a drop down list in one column, based on the choice from another column I want to add text to cells in Column C based on what is entered in Column B.  Column B AND Column C are both drop down lists.  So, if in Column B I have chosen Coach Substitution from the drop down list, I need the word 'SUBSTITUTION' to appear in Column C (it is in the drop down list for Column C), if any other choice is made in Column B from that drop down list, Column C remains blank and ready to accept a choice from THAT drop down list.  I keep getting error messages about "You may not use reference operators (such as unions, intersections, and ranges) or array constants for Conditional Formatting criteria.", OR it won't alter anything at all.  YIKES! Help!!??

A: The below requires the C cell or cells to be populated (won't switch from a validation entry of blank to SUBSTITUTION).
Perhaps what you want is to select the relevant ColumnC cells (say C1 or starting at C1) and Format - Conditional formatting..., Custom formula is and:
=B1="Coach Substitution"

with formatting of Custom:
"SUBSTITUTION"

Done.


text:
Q: A good title for a paper Is this a correct title for an article, etc:

Airplane and the system of its emergency airplane-door locks

?
It seems its cannot be used in this phrase.
Which is correct/prefered for a title:

*

*Airplanes and the system of their emergency airplane-locks

*Airplanes and the systems of their emergency airplane-locks

*On Airplanes and the system of their emergency airplane-locks

*On an Airplane and the system of its emergency airplane-locks

*The system of emergency airplane-locks of an airplane

A: Without twisting up the structure too much, I would say (if its airplane):

The airplane and its system of emergency airplane-door locks.

And if its airplanes:

Airplanes and their system of emergency airplane-door locks.

I am assuming the "airplane-locks* are in the airplane.
And possibly the hyphen is not necessary, unless its a proper noun.

A: At a slight tangent, I'd suggest "Emergency Lock Systems" rather than "Systems of Emergency Locks". "System of emergency locks" suggests that you are defining a new system which people haven't heard of and don't normally treat as a system. "Emergency Lock System" implies that people know which system you're talking about, and you're going to provide a review of that system instead of defining it from scratch. It is like "Emergency Lock" is an adjective describing which "System" you mean.
I agree that "Its" is unhelpful. You could say "Airplanes and Airplane Emergency Lock Systems" - a library catalogue program wouldn't know what "its" was referring to. However, I still prefer a variant of your suggestion 5 - "Airplane Emergency Lock Systems". You want as short and precise a title as possible.
Lastly, do you mean "Emergency Lock Systems", as in the set of physical locks, or "Emergency Locking Systems", as in the physical locks plus the process of locking a plane?


text:
Q: Why does selecting/updating on inner-join take so much longer on higher IDs and is threr a way around it? I have two tables, one with ~250k records one with ~1.5M records.
I am doing a Select and/or Update using Inner Join.
It hung so I decided to to in batches e.g.
Where ID<100000

then
Where ID>=100000 and ID<200000

with each successive batch it takes longer and longer.  Adding to the issue of course is there might be records that would have joined w/o being separated by batches.
I'm curious why that is (why do the first 100k IDs join fast and the last 100k take so much longer) and if there is a way to do as a single query w/o the IDs becoming a/the issue (if they in fact are).


text:
Q: How to bounds in Leaflet? So ive got a 2000x2000 image as a CRS map where i need to fit -600000 +600000 coordinates, but the image becomes so zoomed that im obviously not doing it right, i guess the program does not know how to combine and calculate that by itself to fit the units into pixels, or does it have a setting for that?
I guess it still makes each pixel of the image approx 600units big but i guess thats accurate enough for what im trying to do.
Coordinates themselves seem to be working as the center of the image is exactly spot on.
    var mapOptions = {
            center: [11999, 9199],
            minZoom: 0,
            maxZoom: 0
         }

         // Creating a map object
        var map = L.map('bigmapleaf', {
            crs: L.CRS.Simple
        }, mapOptions);
        var bounds = [[600000,-600000], [-600000,600000]];
        var image = L.imageOverlay('../pictures/map.png', bounds).addTo(map);
         // Adding layer to the map
        map.fitBounds(bounds);
map.setView( center, 1);

Edit:
Now i have managed to find the math that makes the map the right size without any zooming with good precision, but i need to make the map to respond to those kind of large units which i believe requires another conversion back to the original units which does not feel right. I wish i could work with the large units and let leaflet do all the map view conversions. Maybe i try to make a script that discusses both ways with their own units.
Still waiting if someone knows easy answer for my troubles.
In addition to being easier working with them large units, i could also make the map with absolute accuracy.


text:
Q: How to extract from multiple tables with different structure to one flat file? I have following three tables, which can be joined using the common column, key and they have different number of columns.
table1 (key, colnA-1, colnA-2, …, colnA-n)
table2 (key, colnB-1, colnB-2, …, colnB-m)
table3 (key, colnC-1, colnC-2, …, colnC-i)

I need to combine the three tables and export to a flat file like following
colnA-1, colnA-2, A, colnA-3, …, colnA-n
colnA-1, colnA-2, B, colnB-1, colnB-2, …, colnB-m
colnA-1, colnA-2, B, colnB-1, colnB-2, …, colnB-m
colnA-1, colnA-2, B, colnB-1, colnB-2, …, colnB-m
…
colnA-1, colnA-2, C, colnC-1, colnC-2, …, colnC-i
colnA-1, colnA-2, C, colnC-1, colnC-2, …, colnC-i
colnA-1, colnA-2, C, colnC-1, colnC-2, …, colnC-i
…

A means the data in rest of the line are from table1, B means the data in the rest of the line are from table2, etc.

My first question is that is it possible to write a query to join the three tables to generate a final table with the structure like above, then I could use SSIS to export the data to a flat file from the final table? My own answer to this is maybe not, since the record from table A has different structure from the record from table B.
Another question is, since I am fairly new to create a SSIS package, my only experience using SSIS is to do import/export in SSMS, can anybody share some idea how to create an SSIS package to achieve my goal?

A: I don't really understand how you're joining the three tables.  I'd need specifics to be more precise.
The basic idea is to go
SELECT colnA-1, colnA-2, 'A', …, colnA-n
FROM table1
UNION ALL
SELECT colnB-1, colnB-2, 'B', …, colnB-n
FROM table2
UNION ALL
SELECT colnC-1, colnC-2, 'C', …, colnC-n
FROM table3

If your datatypes are incompatible, you'll need to use CAST() statements to make them compatible.
When you're building the package and selecting a data source, choose an OLE DB Source.  In the configuration window, instead of picking a table, choose an SQL command.  Then paste your working query into SSIS.


text:
Q: How I can check an XmlReader can read content before calling Read()? I read xml-string using XmlReader with code:
  XmlReader reader = XmlReader.Create(new StringReader(xmlString));
  while (reader.Read())
  {
    // some code
  }

But if xmlString equal "" then I have XmlException on reader.Read(): root element not found. How I can check can XmlReader read content or not before reader.Read()?

A:
But if xmlString equal ""

Well, that's invalid XML, so it is an exceptional situation where it would be better to throw an exception rather than continuing to read something that is not what it pretends to be (XML). So you could simply catch this exception and inform the user that an error occurred. If he is responsible of the input string tell him that he entered invalid XML that cannot be processed. And if it is you, apologize by saying that something very bad went wrong.
This is to say that the XmlReader class expects a valid XML as input.


text:
Q: Make HTTP GET request with cURL from Wowza Rest API I have never used cURL before and I think I have hit a roadblock in my learning. I am trying to make a HTTP GET request to my Wowza server which uses the Rest API to return JSON results. The URL actually returns it in XML but Wowza support says it I can get the response in JSON by adding the content type as I have done.
$url = 'http://DOMAINNAME:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/instances/_definst_/incomingstreams/ncopeland';

 $cURL = curl_init();

 curl_setopt($cURL, CURLOPT_URL, $url);
 curl_setopt($cURL, CURLOPT_HTTPGET, true);

curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
     'Content-Type: application/json;charset=utf-8',
     'Accept: application/json'
 ));

 $result = curl_exec($cURL);
 $result = json_decode($result,true);

curl_close($cURL);

The response should be this.
{
  "serverName": "_defaultServer_",
  "sourceIp": "ncopeland",
  "isPTZEnabled": false,
  "applicationInstance": "_definst_",
  "name": "ncopeland",
  "isRecordingSet": false,
  "isStreamManagerStream": true,
  "isPublishedToVOD": false,
  "isConnected": true,
  "ptzPollingInterval": 2000
}

But, instead the response is being returned and formatted like this.
{"serverName":"_defaultServer_","sourceIp":"ncopeland","isPTZEnabled":false,"applicationInstance":"_definst_","name":"ncopeland","isRecordingSet":false,"isStreamManagerStream":true,"isPublishedToVOD":false,"isConnected":false,"ptzPollingInterval":2000}

How can I format this so I can get these into usable variables. Really all I am needing from the response is "name" and "isConnected" so I can updated fields in a DB. Really all I am needing from the response is "name" and "isConnected" so I can updated fields in a DB like this.
Array (
[serverName] => _defaultServer_
[sourceIp] => ncopeland
[isPTZEnabled] => false
[applicationInstance] => _definst_
[name] => ncopeland
[isRecordingSet] => false
[isStreamManagerStream] => true
[isPublishedToVOD] => false
[isConnected] => false
[ptzPollingInterval] => false

)

So I can work with $obj variable as an array like so.
echo $obj['name'];
echo $obj['isConnected'];

A: I'm not sure what are you missing, everything should be working as intended from your code. The fact, that json returns data without newline, doesn't change how data will be used later.
$jsondata = '{"serverName":"_defaultServer_","sourceIp":"ncopeland","isPTZEnabled":false,"applicationInstance":"_definst_","name":"ncopeland","isRecordingSet":false,"isStreamManagerStream":true,"isPublishedToVOD":false,"isConnected":false,"ptzPollingInterval":2000}';

$result = json_decode($jsondata,true); //is array
var_dump ($result['serverName']);
var_dump ($result['isConnected']);

Besides that, keep in mind, that you cannot echo boolean values.
BTW, using objects is even simpler than arrays in my opinion.
$jsondata = '{"serverName":"_defaultServer_","sourceIp":"ncopeland","isPTZEnabled":false,"applicationInstance":"_definst_","name":"ncopeland","isRecordingSet":false,"isStreamManagerStream":true,"isPublishedToVOD":false,"isConnected":false,"ptzPollingInterval":2000}';
$result = json_decode($jsondata);

var_dump ($result->serverName);
var_dump ($result->isConnected);

A: There was nothing wrong with my code after all. Come to find out on my hosted server solution the package I was using from Bluehost blocked the ports I was needing to make the http request via cURL. I was able to upgrade to a dedicated IP to get the ports I was needing open so it would work and has been working great since.


text:
Q: Most efficient way to send large payload to a web front-end I have a grid that loads about 100k rows of data, which comes out to about 20MB. To get that data, we are currently doing something like this:
cursor.execute(sql)
data = cursor.fetchall()
return HttpResponse(data.json())

And then we will use JSON.parse in the javascript to then load that data into the grid. From end-to-end, what would be the fastest way to get that data from our database into our grid (with the one caveat that we do not allow the sql request in the front-end javascript code)?
Possible solutions I've thought of are:

*

*send things as-is, with no compression

*gzip the json data (almost zero work required)

*compress to lz4 then decompress in javascript (would require compiling cpp to javascript)

*use another format, such as protobuf or message pack

I'm not concerned about the size of the message, I'm only concerned about the end-to-end timing of displaying that data to the front-end. Basically, how long it takes the end-user to get a response.
(Note that I'm not concerned about breaking the data up into chunks, this is a very specific use case where a user has asked for all data to be loaded into an html table)


text:
Q: Translate Date Time CEST CET (OSM timestamp) in to CET YYYY-MM-dd (QGIS) I need the date in YYYY-MM-DD (CET) from an OSM timestamp with mixed (CEST/CET) dates. The time is not necessary. Finally, I just want to show all records that are 7 days old (as expression to filter or style).
Here my date-times:

A: Your field already is in datetime format. You can see this because its alligned right. If it was a string, it would be alligned left. To filter for records of the last 7 days you can use:
osm_timestamp >= (now() - to_interval('7 day'))

If you want to create a datefield without the time you can use:
to_date("osm_timestamp")

To change the format the Datetime is displayed in, go to layer properties -> attributes form, choose the field and change the field format or widget display:

This should work since 3.16 as stated in an QGIS issue.


text:
Q: SQL begin end print I have following tsql code in sql server 2008:
    declare @ID INT
    SET @ID = 0
    IF (@ID IS NOT NULL OR @ID <> 0)
    begin
      print 'ID is not 0 or null'
    end

Since @ID is 0, why does it even get into the begin end ... It should not.

A: You have better luck using and instead
declare @ID INT
    SET @ID = 0
    IF (@ID IS NOT NULL AND @ID <> 0)
    begin
      print 'ID is not 0 or null'
    end

A: Most probably a case of meaning AND and not OR. Then it should have the result you expect.

A: The @ID is not Null so it meets the requirement for half of your OR statement.  If you want it to not hit the print, then you should use AND.

A: Your first condition @ID iS NOT NULL is true so it's going inside and printing the statement.

A: IF (@ID IS NOT NULL OR @ID <> 0)

Since @ID is not null, it enters the begin-end block.


text:
Q: How Do I Backup the Windows Master Boot Record with C#? Using C#, how do I backup the Windows Master Boot Record of the system booted hard drive? It's for an Antivirus engine.

A: using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace BackupMBR
{
    class Program
    {

        [DllImport("kernel32")]
        private static extern IntPtr CreateFile(
           string lpFileName,
           uint dwDesiredAccess,
           uint dwShareMode,
           IntPtr lpSecurityAttributes,
           uint dwCreationDisposition,
           uint dwFlagsAndAttributes,
           IntPtr hTemplateFile);

        static void Main(string[] args)
        {
            IntPtr handle = CreateFile(
                @"\\.\PHYSICALDRIVE0",
                0x80000000,
                1,
                IntPtr.Zero,
                3,
                0,
                IntPtr.Zero
           );
            using (FileStream disk = new FileStream(handle, FileAccess.Read))
            {
                byte[] mbrData = new byte[512];
                Console.WriteLine("Starting MBR Backup...");
                try
                {
                    disk.Read(mbrData, 0, mbrData.Length);
                    FileStream mbrSave = new FileStream("mbr.img", FileMode.Create);
                    mbrSave.Write(mbrData, 0, mbrData.Length);
                    Console.WriteLine("MBR Backuped to mymbr.img success!");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            Console.ReadKey();

        }
    }
}


text:
Q: Laravel Collective SSH results I am performing SSH in Laravel whereby I connect to another server and download a file.  I am using Laravel Collective https://laravelcollective.com/docs/5.4/ssh
So, the suggested way to do this is something like this
$result = \SSH::into('scripts')->get('/srv/somelocation/'.$fileName, $path);

if($result) {
   return $path;
} else {
    return 401;
}

Now that successfully downloads the file and moves it to my local server.  However, I am always returned 401 because $result seems to be Null.
I cant find much or getting the result back from the SSH.  I have also tried
$result = \SSH::into('scripts')->get('/srv/somelocation/'.$fileName, $path, function($line){
    dd( $line.PHP_EOL);
});

But that never gets into the inner function.
Is there any way I can get the result back from the SSH?  I just want to handle it properly if there is an error.
Thanks

A: Rather than rely on $result to give you true / false / error, you can check if the file was downloaded successfully in another way:
// download the file
$result = \SSH::into('scripts')->get('/srv/somelocation/'.$fileName, $path);

// see if downloaded file exists
if ( file_exists($path) ) {
  return $path;
} else {
  return 401;
}

A: u need to pass file name also like this in get and put method:
$fileName = "example.txt";

$get = \SSH::into('scripts')->get('/remote/somelocation/'.$fileName, base_path($fileName));

in set method
$set = \SSH::into('scripts')->set(base_path($fileName),'/remote/location/'.$fileName);

in list
$command = SSH::into('scripts')->run(['ls -lsa'],function($output) {
    dd($output);
});


text:
Q: SugarCRM Rest API: Required fields for a Meeting entry? I'm trying to create a Meeting entry via the API, but I can't seem to find it in my calendar even though it saved successfully (I got the ID back) and I can see it in the Meetings list.
What fields do I need to populate for it to show in my Sugar calendar? Here are the fields I'm populating:
{
 'assigned_user_id': '1', # My user's ID
 'date_end': '2013-04-16 01:30:00',
 'date_start': '2013-04-16 01:23:45',
 'description': 'hello world',
 'location': 'JCenter',
 'name': 'Test',
 'team_id': '1',
 'type': 'Sugar' # This doesn't seem to be required
}

A: Try to set "user_id" and take a look into mettings_users table where you will find it.


text:
Q: I am Facing issue in magento timezone when someone place order. Timezone Issue is inside the order email.
I put My code which returns date like :
Code :
$created =  Mage::helper('core')->formatDate($this->getCreatedAt(), 'long', true);
O/P :
March 31, 2016 9:10:33 AM EDT
But I want to Need Date Like Based on EST Timezone :
EST - Timezone with proper
So please any one can help me how can i achieve this and also first priority to magento code and second one PHP.
Thank You.

A: Login as admin and navigate to System -> Configuration -> General -> Locale Options -> Timezone and change timezone from there


text:
Q: resolving laravel 5.3 route name conflict I have this app in laravel 5.3 on my local machine that uses two controllers

AdminUsersController and AgentUsersController

Now I set their routes in the following ways:
Route::group(['middleware' => 'admin'], function(){

  Route::get('/admin', function(){
    return view('admin.index');
  });

  Route::resource('admin/users', 'AdminUsersController');

  Route::resource('admin/posts', 'AdminPostsController');
});

Route::group(['middleware' => 'agent'], function(){

  Route::get('/agent', function(){
    return view('agent.index');
  });

  Route::resource('agent/posts', 'AgentPostsController');

});

When I list the routes in this with php artisan route:list I get the following out come:
+--------+-----------+-------------------------+---------------+------------------------------------------------------------------------+--------------+
| Domain | Method    | URI                     | Name          | Action                                                                 | Middleware   |
+--------+-----------+-------------------------+---------------+------------------------------------------------------------------------+--------------+
|        | GET|HEAD  | /                       |               | Closure                                                                | web          |
|        | GET|HEAD  | admin                   |               | Closure                                                                | web,admin    |
|        | GET|HEAD  | admin/posts             | posts.index   | App\Http\Controllers\AdminPostsController@index                        | web,admin    |
|
|        | GET|HEAD  | agent/posts             | posts.index   | App\Http\Controllers\AgentPostsController@index                        | web,agent    |
|        | POST      | agent/posts             | posts.store   | App\Http\Controllers\AgentPostsController@store                        | web,agent    |

Notice that the URI agent/posts has the name posts.index and that the URI admin/posts has the name posts.index.
Now in my blade template when I added the route for an admin user like so {{route('posts.index')}}. I get the URI mydomain/agent/posts instead of mydomain/admin/posts. How do I let route in blade know which of the URIs to pick.
I know I can also do URL('/admin/posts') to pick the right one, but I am wondering if using route method is possible.

A: Yes, you can override the names of one of your Resource controllers! Just pass another argument to the resource method, providing an array with the 'names' keyword as the index and another array as the value:
Route::resource('agent/posts', 'AgentPostsController', ['names' => [
    'index' => 'agent.posts.index'
]]);


text:
Q: PHP dynamic name for object property Instead of using
$object->my_property

I want to do something like this
$object->"my_".$variable

A: How about this:
$object->{"my_$variable"};

I suppose this section of PHP documentation might be helpful. In short, one can write any arbitrary expression within curly braces; its result (a string) become a name of property to be addressed. For example:
$x = new StdClass();
$x->s1 = 'def';

echo $x->{'s' . print("abc\n")};
// prints
// abc
// def

... yet usually is far more readable to store the result of this expression into a temporary variable (which, btw, can be given a meaningful name). Like this:
$x = new StdClass();
$x->s1 = 'def';

$someWeirdPropertyName = 's' . print("abc\n"); // becomes 's1'.
echo $x->$someWeirdPropertyName;

As you see, this approach makes curly braces not necessary AND gives a reader at least some description of what composes the property name. )
P.S. print is used just to illustrate the potential complexity of variable name expression; while this kind of code is commonly used in certification tests, it's a big 'no-no' to use such things in production. )

A: Use curly brackets like so:
$object->{'my_' . $variable}


text:
Q: whenever/capistrano `method_missing_with_variables': undefined method `role_names_for_host' I'm using whenever/capistrano to update my cron_tab when deploying with capistrano, it was working great until recently my deploys started to fail when updating the cron_tab.
.rvm/gems/ruby-1.9.3-p362-turbo@psg-web/gems/capistrano-2.8.0/lib/capistrano/configuration/variables.rb:122:in `method_missing_with_variables': undefined method `role_names_for_host' for #<Capistrano::Configuration:0x000000018e6a10> (NoMethodError)

I am setting the *role_names_for_host*
set_default(:whenever_roles, [:workers])

and my tasks look like this
namespace :whenever do
  desc "Stop whenever"
  task :stop , roles: [:workers] do
    clear_crontab
  end

  desc "Start whenever"
  task :start , roles: [:workers] do
    update_crontab
  end

  desc "Restart whenever"
  task :restart , roles: [:workers] do
    update_crontab
  end

  after 'deploy:symlink', 'whenever:update_crontab'
  %w[start stop restart].each do |command|
    after "deploy:#{command}", "whenever:#{command}"
  end
end

Any Ideas on what I could be doing wrong?
Gem versions

*

*capistrano (2.8.0)

*whenever (0.8.2)

A: The method missing is introduced in capistrano after 2.9.0.
Patch: You can add this at the top of your Capfile or deploy.rb file:
require 'capistrano/server_definition'
require 'capistrano/role'
class Capistrano::Configuration
  def role_names_for_host(host)
    roles.map {|role_name, role| role_name if role.include?(host) }.compact || []
  end
end

I would recommend whenever updating it's gem dependencies :)
( source: https://github.com/javan/whenever/issues/302#issuecomment-14962350 )


text:
Q: Are there any established standard practices for video on the web while supporting mobile? Seeing as how Flash Video isn't well supported in the mobile world, are there any best practices for embedding video on a website ensuring that it can accessed by as many devices as possible?
(short of creating a native app like the ted / you tube apps)

A: Well, there are no standarts, but there are formats specifically made for mobile. Youtube has 3GP video on ALL videos, so it's a good bet. (Yes, all videos on Youtube have a 3GP version).
It's not sure that a certain mobile would play 3GP, but look at your possibilities:
1) It supports 3GP: You're done.
2) It supports another format:
  a) Do many users access from that mobile? no > don't care about it
  b) Yes? then try supporting it too.
3) It actually supports flash, or even AVC: support it if it's worth the hassle, since they must also support 3GP
4) They don't support video: Just tell that to the user!
:)


text:
Q: How is android.database different from android.database.sqlite? I am trying to develop this android application whose database is not stored in the device but on a server. To use sqlite database I need to use android.database.sqlite; and I haven't made much use of android.database package. I went through the documentation site but it did not state clearly if it's possible can store my sqlite database file on server and invoke methods to access it from there. What should I do?

A: SQLite is not an ideal database to use on a server.  The andriod.database.sqlite package is going to have resources for dealing with sqlite specifically, where the android.database package is going to have generic database resources, not specific to sqlite.
For using sqlite on a server, first bear in mind that concurrent connections are a big no-no... sqlite is not designed to handle them.
If I still felt I had to do this, I'd probably look at creating an adapter on the server which would accept requests from the application, then use the android.database.sqlite package on the server, as it's local per the scope there (as sqlite is designed for).
https://www.sqlite.org/serverless.html


text:
Q: Exchange 2010 purging client subscriptions using EWS Scenario
I have a console service responsible for maintaining a streaming subscription to our Exchange 2010 SP1 server. I've properly hooked up my events (notification, error, disconnect) using the Exchange Web Services SDK 1.1.
Problem
When I try and re-establish my subscription I will sometimes (no pattern as far as I can see) I will receive an exception saying that I do not have an active subscription. Sometimes I can go through 10 reconnect cycles no problem and other times it tries to reconnect once and my subscription magically disappears.
I've tested against our QA server and I am able to successfully reinitialize my subscription once I get disconnected (due to the timeout). However, our production server appears to be having a real hard time keeping a subscription.
Question
Does Exchange 2010 SP1 have some sort of odd mechanism where it will simply remove subscriptions once the client is disconnected? Since I'm pretty sure this is the case how do you disable such thing?
This question is related to something I asked earlier today on SO. After some more thinking and playing around with our QA and production environment I believe it might be a settings issue with Exchange.
Edit: This is issue is still not fully resolved. I managed to manually resubscribe however I'm still intrigued in finding out exactly why my subscriptions are vanishing.
Edit 2: Another related issue is that new mail notification events are not being sent out. Are there any resources I can read regarding client subscriptions with Exchange 2010 SP1?
Edit 3: If it helps we're currently in an upgrade phase where we have an Exchange 2003 and Exchange 2010 server running at the same time. So I'm wondering if it's possible that that's causing the issue as as our QA environment isn't running the identical architecture.

A: a) You can take a look at this cmdlet - Get-ThrottlingPolicy. It has MaxTimeinAD and other keys which can be modified. More details here.
http://blogs.msdn.com/b/exchangedev/archive/2011/06/23/exchange-online-throttling-and-limits-faq.aspx
b) How can you control EWS Access.

*

*Per Mailbox> Run this from Exchange shell get-casmailbox -identity:"username" | fl "*EWS*
You can disable those keys using a set-mailbox -identity:"username" -EWSEnabled: $False

*The whole organization: `Get-OrganizationConfig | fl EWS

*You can play around with this, with a list of mailboxes to modify in CSV, and then importing the CSV > and piping out all mailboxes one by one to set-casmailbox.

c) New Mail Notification is a client side feature, so you need to check outlook / phone settings.
b) During Exchange 2003-2010 co-existence, are all mails routed through 2010 or 2003. Also did you setup the CAS role and tested OWA access ?


text:
Q: jquery function (.on) not working Ive got some problem with my jquery function. First of all, this is my HTML head
<link href="css/bootstrap.css" media="screen" rel="stylesheet">
    <link href="css/datepicker.css" media="screen" rel="stylesheet">
    <link rel="stylesheet" type="text/css" media="screen" href="css/bootstrap-datepicker.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="css/bootstrap.min.css">

and here is the code from my button.js file
$(window).load(
    function(){
        ...
        $(document).on('click', '.popover a', function(){
            alert("asd");
        });

        $('#button_nowtime').popover({
            trigger: 'click',
            html: 'true',
            title:  "Čas",
            content:
            function() {
                var returnstring="",button;
                    for(var i=0; i<files.length; i++){
                        button = document.createElement("a");
                        button.innerText = "someText"
                        button.href="#";
                        returnstring+=button.outerHTML;
                    }
                return returnstring;
            }
        });
   }
);

html
N/A

the problem is, the alert("asd") wont pop up when I click on any button in the tooltip

A: You should use $.ready instead of window.load, probabily your code doesn't work because window.load occurs before your objects exist. http://www.dotnetbull.com/2013/08/document-ready-vs-window-onload.html
This sample works http://jsfiddle.net/nWKqt/
[ignore this - just including a code block so stackoverflow will let me post the above JSFiddle link. Yeah, seriously.]
Also, you wrote a code that depends on a class that is defined not by you but from a jquery plugin, which you fire after you declared the events.
Try to put the click event after you declared the popover plugin, but better would be to define your cssClass and depend on it.

A: Why dont use this:
 $(".popover a").click( function(){
            alert("asd");
        });

the old method works fine ..


text:
Q: Hadoop & Hive as warehouse: daily data deliveries I am evaluating the combination of hadoop & hive (& impala) as a repolacement for a large data warehouse. I already set up a version and performance is great in read access.
Can somebody give me any hint what concept should be used for daily data deliveries to a table?
I have a table in hive based on a file I put into hdfs. But now I have on a daily basis new transactional data coming in.
How do I add them ti the table in hive.
Inserts are not possible. HDFS cannot append. So whats the gernal concept I need to follow.
Any advice or direction to documentation is appreciated.
Best regards!

A: Hive allows for data to be appended to a table - the underlying implementation of how this happens in HDFS doesn't matter. There are a number of things you can do append data:

*

*INSERT - You can just append rows to an existing table.

*INSERT OVERWRITE - If you have to process data, you can perform an INSERT OVERWRITE to re-write a table or partition.

*LOAD DATA - You can use this to bulk insert data into a table and, optionally, use the OVERWRITE keyword to wipe out any existing data.

*Partition your data.

*Load data into a new table and swap the partition in

Partitioning is great if you know you're going to be performing date based searches and gives you the ability to use options 1, 2, & 3 at either the table or partition level.

A:  Inserts are not possible

Inserts are possible ,like you can create a new table and insert the data from new table to old table.
But simple solution is You can load data of the file into Hive table with the below command.
load data inpath '/filepath' [overwrite] into table tablename;

If you use overwrite then only existing data replced with new data otherwise It is appending only.
You can even schedule the script by creating a shell script.


text:
Q: present continuous for a short action is it possible in this case After waking up today I received a phone call of a friend I had not seen or spoken for years .
Can I say: "my day is starting very well" or "my day has started well" or "my day starts well"
I think the first solution is the best because it is not a habit (no present) and this is what is happening now so present continuous seems to be the best . But can we consider a start as something in progress?
What about present perfect and present  in this case.


text:
Q: How to make celery retry using the same worker? I'm just starting out with celery in a Django project, and am kinda stuck at this particular problem: Basically, I need to distribute a long-running task to different workers. The task is actually broken into several steps, each of which takes considerable time to complete. Therefore, if some step fails, I'd like celery to retry this task using the same worker to reuse the results from the completed steps. I understand that celery uses routing to distribute tasks to certain server, but I can't find anything about this particular problem. I use RabbitMQ as my broker.

A: You could have every celeryd instance consume from a queue named after the hostname of the worker:
celeryd -l info -n worker1.example.com  -Q celery,worker1.example.com

sets the hostname to worker1.example.com and will consume from a queue named the same, as well as the default queue (named celery).
Then to direct a task to a specific worker you can use:
task.apply_async(args, kwargs, queue="worker1.example.com")

similary to direct a retry:
task.retry(queue="worker1.example.com")

or to direct the retry to the same worker:
task.retry(queue=task.request.hostname)


text:
Q: What about negative (absolute) pressure in Bernoulli Equation I'm studying Aerodynamics and I'm thinking about the Bernoulli Equation Statement.
Ignoring gravity contributes, it states that, in a potential fluid, the sum of static pressure and kinetic energy (per unit of mass) is a constant:
$$P+0.5ρv^2=const$$
Typically, to solve the pressure distribution around an aerofoil (in order to calculate lift) in the context of a potential fluid, we can solve the Divergence problem about the velocity field:
$$\nabla \cdot V =0$$
Once the velocity field has been determined, we can use the Bernoulli equation to find the static pressure value in every point of the fluid field.
So my question is:
If the velocity would be too large in some points of the field, may we find there a negative static pressure? Algebraically speaking the answer is yes, because the Bernoulli Equation may "mathematically" lead to this result. But negative (absolute) pressure has no physical meaning, so how can we know if the Bernoulli Equation application will lead to robust results? A negative pressure would represent an "exhaustion" of static pressure to convert in kinetic energy, so in these conditions the velocity field cannot be realized and the Bernoulli equation would be violated. As I know, if we are dealing with liquid, the occurrence of a negative pressure would lead to cavitation and boiling, but in aerodynamics we deal with air (a  gas).
So, How can we deal with an aerodynamic problem in which such a circumstance occurs, and what are the conditions to garantee negative pressure not to happen?

A: The Bernoulli equation is derived assuming the fluid is incompressible, which is an idealization even for liquids, and even more for gases.
This idealization is valid provided density $\rho$ in the fastest parts of the flow does not change much from its value where $v$ is minimal.
For liquids, this is usually the case. For gases, it depends on the flow speeds. Density of air at points where the flow has high velocity can drop substantially, and so can pressure $p$.
So in places where density of air gets too low, the original Bernoulli equation (with pressure term instead of enthalpy term) stops being accurate. In any case, air as well as other gases cannot have negative pressure, so $p<0$ won't happen.


text:
Q: topology puzzle - without cut the rope, separate two rings hello I wonder whether this puzzle is possible to solve.
if possible, what kind of thing should I learn to solve this?
the problem is make left one to right one without cut the rope
only stretch and bending are allowed
I found out this puzzle here->(www.ocf.berkeley.edu/~wwu/riddles/hard.shtml/)

I wish this problem lead me to learn math intuitively.

A: Here's one way to think of it.
Call the loops $L_1$ and $L_2$, joined by the stem which attaches to $L_1$ at $S_1$ and $L_2$ at $S_2$.  You will notice there is a point $A$ where $L_1$ crosses and is above $L_2$ and another point $B$ where $L_1$ crosses and is below $L_2$.
Now contract the stem until it vanishes so that $S_1$ and $S_2$ become a single point $S$ and you will see that one of the points $A$ or $B$ will also move to $S$ under this deformation.
If you try to draw the two rings now joined at the single point $S$ you will see they are no longer linked - there is only one crossing point now so you simply have two rings sitting on top of one another joined at a point.
All you need to do now is stretch out the stem again and the rings will look like the second picture.

A: This is a classical topological problem and magic trick.
The concept is fairly simple and the diagram is misleading. If you manufacture latex or plastic loops as per the diagram, it is an impossible task.
However, if you take a string then to create the loops, you need to tie 2 knots. That's the key. The idea is basically to pass one loop through the other's knot.


text:
Q: How to read until end of file (EOF) using BufferedReader in Java? I have problem with reading the input until EOF in Java. In here, there are single input and the output consider the input each line.
Example:
input:
1
2
3
4
5

output:
0
1
0
1
0

But, I have coded using Java, the single output will printed when I was entering two numbers. I want single input and print single output each line (terminate EOF) using BufferedReader in Java.
This is my code:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
StringBuffer pr = new StringBuffer("");

String str = "";
while((str=input.readLine())!=null && str.length()!=0) {
    BigInteger n = new BigInteger(input.readLine());
}

A: With text files, maybe the EOF is -1 when using BufferReader.read(), char by char.
I made a test with BufferReader.readLine()!=null and it worked properly.

A: You are consuming a line at, which is discarded
while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at
BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as
BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to
while((str=input.readLine())!=null)

see related post string to bigint
readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

see javadocs


text:
Q: Arch linux graphics problems I've been trying to install various versions of arch (Manjaro, architect...). All goes well except for a graphics problem. I've tried updating drivers, changing window managers...to no avail. Actually the only linux distro to work right is ubuntu, even fedora didn't work right.
Here is what I'm seeing:
text on windows is all screwed up, but text on websites for example looks fine.
Any ideas?

A: Turns out deleting the video-intel driver with "sudo mhwd -r video-intel" solved the problem. My system still shows that it is running the video-intel driver, but I'm not too worried as long as it's working :)

A: For Arch, it may be the default acceleration method used by your intel driver (should be something like /etc/X11/xorg.conf.d/20-intel.conf).
The default is "sna". You might want to try changing it to "uxa" by adding the following line to the above configuration file:
Option      "AccelMethod"  "uxa"
Source (a very useful page generally):
https://wiki.archlinux.org/index.php/intel_graphics#SNA_issues


text:
Q: how to write json data to a file in android Can someone explain what is going wrong here I am using following function
public void WriteSettings(Context context, String data){
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;

    try{
     fOut = context.openFileOutput("schemas.json",Context.MODE_APPEND);
     osw = new OutputStreamWriter(fOut);
     osw.write(data);
     osw.flush();
     Toast.makeText(context, data+"Data",Toast.LENGTH_SHORT).show();
     Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
     }
     catch (Exception e) {
     e.printStackTrace();
     Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
     }
     finally {
        try {
               osw.close();
               fOut.close();
               } catch (IOException e) {
               e.printStackTrace();
               }
     }
}

And calling with once my http request is completed
JSONObject json_res = currentDFD.getJSONObject("result");
WriteSettings(getBaseContext(),json_res.toString());
The result is alerted in toast however not written to the file
the file is located in assets folder
thanks in advance

A: AFAIK You can't. The assets folder is read-only at runtime.
Pick a different location to save your data, see Data Storage in Android for more information.
The assets folder is like folders res, src, gen, etc. These are all useful to provide different files as input to build system to generate APK file for your app.
All these are read-only while your app is running. At run-time you can only write to SD card.


text:
Q: height of iframe doesn't resize based on outer div height using CSS I have a general question about resizing iframe contents.
I have observed that if I change the width of the outer div that contains the iframe, then the iframe contents adjust according to the outer div width specifications. The same doesn't hold true for the height attribute. Can someone explain me or guide more on this to me?
By changing the height and width attribute values, I meant specifying height and width in percentages and not in pixel values.
Example:

A: if you want your iframe to respond to width changes and maintain the proportions, you have to play with the aspect ratio of the wrapper div with the padding like this:
HTML

CSS
.wrapper {
  position: relative;
  padding-bottom: 56.25%;
}
.wrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

So to specify the width and height of your iframe, you just need to play around with the padding-bottom of the wrapper div.
Check this jsfiddle.
Original source.


text:
Q: Interpretation of a statement that I think I can prove by mathematical induction I want to prove by mathematical induction the following statement: for any sequence (a_k) of non negative real numbers holds that:
$$(1+a1)(1+a2)...(1+a_n) >= 1 + a_1 + a_2 + ... a_n$$
I think this statement verbally translates as: the products of the sum of any positive real number with 1 is greater than or equal to the sum between 1 and the positive real numbers chosen.
Indeed, I have a doubt now. Do the indices of the letters $a$ tell me that inside any parenthesis can be or should be chosen a different real number?.
If yes, I would be a bit in trouble in writing the base case - or might I skip it, in some circumstances? - otherwise, since that we now deal with positive real numbers - a superset with respect to the natural numbers - I think that I could choose zero for the base case - perhaps, I should choose zero - as it is the first non negative real number! Obviously, you can disprove my statement.
However, zero holds for the base case, because we would end up with 1 = 1 - but I am not considering the different indices of the letters $a$, which is my first doubt.

A: Consider a sequence $a_n \geq 0$. Clearly $$a_1+1 \geq a_1+1.$$
Assume that for $k$ we have $$(1+a_1)(1+a_2) \cdots (1+a_k) \geq 1+a_1+a_2 + \cdots +a_k.$$
Now $$(1+a_1)(1+a_2) \cdots (1+a_k)(1+a_{k+1}) \geq \left( 1+a_1+a_2 + \cdots +a_k \right)(1+a_{k+1}) \\ \geq 1+a_1+a_2 + \cdots +a_k +a_{k+1}, $$
because the last expression is obtained by dropping some non-negative terms.

A: The base case is $n=1$ because your first available subscript is $1$. There is no $a_0$. So base case, $n=1$ you must show that $(1+a_1) \geq 1 + a_1$, which is trivial. Then prove induction statement for $n+1$, which states
\begin{equation}
\prod_{i=1}^{n+1} (1+a_i) \geq 1 + \sum_{i=1}^{n+1} a_i
\end{equation}
But
\begin{equation}
\prod_{i=1}^{n+1} (1+a_i) = \prod_{i=1}^{n} (1+a_i) \cdot (1+a_{n+1})
\end{equation}
And
\begin{equation}
1 + \sum_{i=1}^{n+1} a_i = 1 + \sum_{i=1}^{n} a_i + a_{n+1}
\end{equation}
Consider $\prod_{i=1}^{n} (1+a_i) \cdot (1+a_{n+1})$. Rewrite using distributive law such that
\begin{equation}
\prod_{i=1}^{n} (1+a_i) \cdot (1+a_{n+1})=\prod_{i=1}^{n} (1+a_i) + a_{n+1} \cdot \prod_{i=1}^{n} (1+a_i)
\end{equation}
Since you are using mathematical induction, you are assuming that your induction statement
\begin{equation}
P(n):\prod_{i=1}^{n} (1+a_i) \geq 1 + \sum_{i=1}^{n} a_i
\end{equation}
is true. Now add $a_{n+1} \cdot \prod_{i=1}^{n} (1+a_i)$ to both sides of the inequality such that
\begin{equation}
\prod_{i=1}^{n} (1+a_i) +a_{n+1} \cdot \prod_{i=1}^{n} (1+a_i) \geq 1 + \sum_{i=1}^{n} a_i + a_{n+1} \cdot \prod_{i=1}^{n} (1+a_i)
\end{equation}
The left-hand side of this inequality is just
\begin{equation}
\prod_{i=1}^{n+1} (1+a_i)
\end{equation}
as was shown near the start. Upon substitution into the inequality,
\begin{equation}
\prod_{i=1}^{n+1} (1+a_i) \geq 1 + \sum_{i=1}^{n} a_i + a_{n+1} \cdot \prod_{i=1}^{n} (1+a_i)
\end{equation}
Now, since every $a_i$ is a nonnegative integer, $1+a_i\geq 1$. More specifically,
\begin{equation}
\prod_{i=1}^{n} (1+a_i) \geq 1 \implies a_{n+1} \cdot \prod_{i=1}^{n} (1+a_i) \geq a_{n+1}
\end{equation}
Thus,
\begin{equation}
\prod_{i=1}^{n+1} (1+a_i) \geq 1 + \sum_{i=1}^{n} a_i + a_{n+1} \cdot \prod_{i=1}^{n} (1+a_i) \geq 1 + \sum_{i=1}^{n} a_i + a_{n+1} \\
\prod_{i=1}^{n+1} (1+a_i) \geq 1 + \sum_{i=1}^{n} a_i + a_{n+1} =1 + \sum_{i=1}^{n+1} a_i \\
\prod_{i=1}^{n+1} (1+a_i) \geq 1 + \sum_{i=1}^{n+1} a_i
\end{equation}
Done


text:
Q: update remaining balance to 0 if payment is greater than remaining balance using this query i can easily deduct the payment to the remaining balance
let say that my rem_balance is 3000  and my payment is 5000 so basically the change would be 2000.
UPDATE tbl_users SET rem_balance = (rem_balance - '5000') WHERE user_id = '2017001002'

but since i use this query what happen is the rem_balance updates to -2000 what i wanted to achieve is that if payment is > rem_balance, rem_balance becomes 0 and it will separate the change.

A: Something like this should work
UPDATE tbl_users
SET rem_balance = (CASE WHEN rem_balance < 5000 THEN 0 ELSE rem_balance - 5000 END)
WHERE user_id = '2017001002'

Please be aware of the fact that you use implicit conversion in your SQL ('5000' instead of 5000). It is a bad habit and it can harm performance of your queries in certain cases. For example, if tbl_users.user_id is integer as well then the update will be unable to use indexes to search the row with the specific user_id and it will do a sequential scan which is very slow.


text:
Q: Show that $f^{[n]}(0)=0$ for all $n=0,1,2...$ Let $$f(x)=\left\{ {\matrix{
   {{e^{ - {1 \over {{x^2}}}}},x \ne 0}  \cr
   {0,x = 0}  \cr
 } } \right.$$

Show that $f^{[n]}(0)=0$ for all $n=0,1,2,\cdots$

The proof:
First note that for $x\ne 0$: $f'(x)=\frac{2}{x^3} e^{-\frac{1}{x^2}}$
Consider the polynomial function $P_1(x) = 2x^3$, then we have:
$$f'(x) = P_1\left(\frac{1}{x}\right)e^{-\frac{1}{x^2}}$$
Since,
$$\lim\limits_{x\to 0} \frac{1}{x^n} e^{-\frac{1}{x^2}} = 0 $$
for any integer $n\ge 0$:
$$\lim\limits_{x\to 0} P\left(\frac{1}{x}\right) e^{-\frac{1}{x^2}} = 0 $$
for any polynomial $P(x)$.
Then, by induction we prove there exists $P_n(x)$ such that: $f^{(n)}(x) = P_n\left(\frac{1}{x}\right)e^{-\frac{1}{x^2}}$
My Question:
I don't understand the base case: Why are the two limits approaches $0$?
(And where the $\frac{1}{x^n}$ came from?). It looks like black-magic :)
Thanks in advance.

A: To make sure consider $u=\frac{1}{x}$. Then 1st limit
$$\lim\limits_{u\to \infty} \frac{e^{-u^2}}{u^{n}} \quad \forall n \in \mathbb{N}$$
Using many well-known methods ($\varepsilon-\delta$, for example) you can prove that it is $0$. For better understanding it means that exponential decays faster than any power function. The second is a corollary from the 1st: it's no difference between polynomial or its greater power summand in denominator


text:
Q: Regular Expression to just complete word C# I would like to know how to extract complete words using a Regex in C#
For example, my String input:

This$#23 is-kt     jkdls

I want to get Regex Match as

*

*This$#23

*is-kt

*jkdls
I need to extract non space words [which can have numbers or special characters]
by specifying Regex Match pattern
Regex myrex = new Regex("pattern")

A: MatchCollection matches = Regex.Matches("This$#23 is-kt     jkdls", @"\S+");
    foreach(Match match in matches)
        Console.WriteLine(match.Value);

Use \S+ to match words.

A: var words = string.Split(' ');


text:
Q: Converting for loop in R to Rcpp I've been playing around with using more efficient data structures and parallel processing and a few other things. I've made good progress getting a script from running in ~60 seconds down to running in about ~9 seconds.
The one thing I can't for the life of me get my head around though is writing a loop in Rcpp. Specifically, a loop that calculates line-by-line depending on previous-line results and updates the data as it goes.
Wondering if someone could convert my code into Rcpp that way I can back-engineer and figure out, with an example that I'm very familiar with, how its done.
It's a loop that calculates the result of 3 variables at each line. Line 1 has to be calculated separately, and then line 2 onwards calculates based on values from the current and previous lines.
This example code is just 6 lines long but my original code is many thousands:
temp <- matrix(c(0, 0, 0, 2.211, 2.345, 0, 0.8978, 1.0452, 1.1524, 0.4154,
                 0.7102, 0.8576, 0, 0, 0, 1.7956, 1.6348, 0,
                 rep(NA, 18)), ncol=6, nrow=6)
const1 <- 0.938

for (p in 1:nrow(temp)) {
  if (p==1) {
    temp[p, 4] <- max(min(temp[p, 2],
                          temp[p, 1]),
                      0)
    temp[p, 5] <- max(temp[p, 3] + (0 - const1),
                      0)
    temp[p, 6] <- temp[p, 1] - temp[p, 4] - temp[p, 5]
  }
  if (p>1) {
    temp[p, 4] <- max(min(temp[p, 2],
                          temp[p, 1] + temp[p-1, 6]),
                      0)
    temp[p, 5] <- max(temp[p, 3] + (temp[p-1, 6] - const1),
                      0)
    temp[p, 6] <- temp[p-1, 6] + temp[p, 1] - temp[p, 4] - temp[p, 5]
  }
}

Thanks in advance, hopefully this takes someone with Rcpp skills just a minute or two!

A: Here is an the sample Rcpp equivalent code:
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix getResult(NumericMatrix x, double const1){
  for (int p = 0; p < x.nrow(); p++){
    if (p == 0){
      x(p, 3) = std::max(std::min(x(p, 1), x(p, 0)), 0.0);
      x(p, 4) = std::max(x(p, 2) + (0.0 - const1), 0.0);
      x(p, 5) = x(p, 0) - x(p, 3) - x(p, 4);
    }
    if (p > 0){
      x(p, 3) = std::max(std::min(x(p, 1), x(p, 0) + x(p - 1, 5)), 0.0);
      x(p, 4) = std::max(x(p, 2) + (x(p - 1, 5) - const1), 0.0);
      x(p, 5) = x(p - 1, 5) + x(p, 0) - x(p, 3) - x(p, 4);
    }
  }
  return x;
}

A few notes:

*

*Save this in a file and do Rcpp::sourceCpp("myCode.cpp") in your session to compile it and make it available within the session.

*We use NumericMatrix here to represent the matrix.

*You'll see that we call std::max and std::min respectively. These functions require two common data types, i.e. if we do max(x, y), both x and y must be of the same type. Numeric matrix entries are double (I believe), so you need to provide a double; hence, the change from 0 (an int in C++) to 0.0 (a double)

*In C++, indexing starts from 0 instead of 1. As such, you convert R code like temp[1, 4] to temp(0, 3)

*Have a look at http://adv-r.had.co.nz/Rcpp.html for more information to support your development

Update: If x was a list of vectors, here's an approach:
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List getResult(List x, double const1){
  // Create a new list from x called `res`
  Rcpp::List res(x);

  for (int p = 0; p < x.size(); p++){
    // Initiate a NumericVector `curr` with the contents of `res[p]`
    Rcpp::NumericVector curr(res[p]);
    if (p == 0){
      curr(3) = std::max(std::min(curr(1), curr(0)), 0.0);
      curr(4) = std::max(curr(2) + (0.0 - const1), 0.0);
      curr(5) = curr(0) - curr(3) - curr(4);
    }
    if (p > 0){
      // Initiate a NumericVector `prev` with the contents of `res[p-1]`
      Rcpp::NumericVector prev(res[p-1]);
      curr(3) = std::max(std::min(curr(1), curr(0) + prev(5)), 0.0);
      curr(4) = std::max(curr(2) + (prev(5) - const1), 0.0);
      curr(5) = prev(5) + curr(0) - curr(3) - curr(4);
    }
  }
  return x;
}

A: So I tried both jav's answers, and did a little bit of reading. Looks to me like Lists are a R-kinda-thing and Rcpp seems to prefer simple vectors and matrices and whatnot.
So I decided to pass my vectors from the list directly into the Rcpp script. The whole thing works wonders. My ~70 second script which I got down to about ~5 seconds with parallel processing is now running in 0.3 seconds. So Rcpp is pretty awesome at this as I had read.
Here's the code I went with:
(temp is a list of 3 vectors that feed into the calculation of the other 3 vectors, and that const 1 is a constant defined earlier in the code)
R code that calls the script:
temp <- getResult(zero=temp[[i]][, 1],
                  one=temp[[i]][, 2],
                  two=temp[[i]][, 3],
                  const1=constant, rows=(as.double(rowslength)))

Output is a matrix with 3 columns calculated by the following Rcpp script:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix AWBMgetResult(NumericVector zero, NumericVector one,
                        NumericVector two, double const1, double rows){
  // create numericmatrix x
  Rcpp::NumericMatrix x(rows, 3);
  // compute loop
  for (int p = 0; p < rows; p++){
    if (p == 0){
      x(p, 0) = std::max(std::min(one(p), zero(p)), 0.0);
      x(p, 1) = std::max(two(p) + (0.0 - const1), 0.0);
      x(p, 2) = zero(p) - x(p, 0) - x(p, 1);
    }
    else{
      x(p, 0) = std::max(std::min(one(p), zero(p) + x(p - 1, 2)), 0.0);
      x(p, 1) = std::max(two(p) + (x(p - 1, 2) - const1), 0.0);
      x(p, 2) = x(p - 1, 2) + zero(p) - x(p, 0) - x(p, 1);
    }
  }
  return x;
}

I went with if else in the Rcpp code because I couldn't find out how to do 2 loops in a row, 1 of for (p in 1:1) and 1 of for (p in 2:rowslength). But it doesn't seem to matter from a speed point of view. I assumed an if else would still be quicker than an if = 1, if > 1 (since that is checking the value of p at every row)


text:
Q: How can I concatenate dates in python? I want to concatenate dates between a specific time period, i.e 2017.08.15 - 2018.08.15, and I want this in string formats in a list or a set:
("2017.08.15", "2017.08.16", ...)

Is there a way to concatenate dates?

A: Wasn't sure if the date formatting was important, but here is my approach to the problem. Hope this is helpful.
from datetime import date, timedelta

def get_dates(start_date, end_date):
    """
    :param start_date: date as a string ('YYYY.MM.DD')
    :param end_date: date as a string ('YYYY.MM.DD')
    :return: returns list of dates formatted as strings
    """
    # convert date as string to array of ints
    # i.e '2017.08.15 => [2017, 8, 15]
    start_date = map(int, start_date.split('.'))
    end_date = map(int, end_date.split('.'))

    # unpack array with date values into date objects
    start_date = date(*start_date)
    end_date = date(*end_date)

    # find difference between end_date and start
    delta = end_date - start_date

    # create list of dates between start_date and end_date
    dates = [start_date + timedelta(i) for i in range(delta.days + 1)]
    # format dates
    formatted_dates = [f'{date.year}.{date.month:02d}.{date.day:02d}' for date in dates]
    return formatted_dates

print(get_dates("2017.08.15", "2017.09.15"))

Output:
['2017.08.15', '2017.08.16', ... '2017.09.15']

A: I looked up the datetime module, and got this:
def get_dates():
    import datetime
    start_date = datetime.date(2015, 1, 1)
    end_date   = datetime.date(2016, 1, 1)
    date_range_list = []
    date_range = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]
    for date in date_range:
        date_range_list.append(str(date).replace("-","."))
    return(date_range_list)


text:
Q: How to pause camera preview? I am using Flutter's camera plugin to get a live camera preview. But I want to  freeze CameraPreview when the user taps the button. So that the picture will stay on the screen when the user taps on the button.
For example in Android: camera.stopPreview();
I cannot use stopImageStream() because I am not streaming the image.
Does anyone know how to do this?

A: A way this is accomplished is by establishing a counter and incrementing it, and pausing the camera controller when the pauseCamera value is odd.
var pauseCamera = 0;
CameraController? camera; //From the camera package.
...
FloatingActionButton(
          onPressed: () {
            pauseCamera++;
            pauseCamera.isOdd
                ? camera!.pausePreview()
                : camera!.resumePreview();
          },
          child: CameraView(),
        ),


text:
Q: CSS3 Transform scaling issue on IPad Safari I am dynamically scaling the iframe using CSS3 Transform: scale() property in javascript.
Scaling is working fine but the page hyperlinks are no more clickable.
A grey rectangle appears when i Long press the link, on some other place.
Note: The links are 'absolute' positioned in the page.
Please help.

A: This issue occurs in Safari on iOS6 when applying -webkit-transform to an iframe. It does not occur in iOS7 or Chrome on iOS.
It appears as though although the content is visually scaled, it thinks the anchor is in it's original position still (the grey box you are seeing is the click effect on the anchor).
Applying it to the body of the iframe's document resolves the issue while producing the same visual effect.
eg. Instead of this:
$(iframeControl).css('-webkit-transform', 'scale(0.5)');
Do this:
$(iframeControl.contentDocument.body).css('-webkit-transform', 'scale(0.5)');


text:
Q: How to use iRedMail's LDAP database for user authentication? I have a few servers set up and I'd like to centralize access for users using LDAP. I have my primary server that is hosting email using iRedMail, and there already happens to be an LDAP database that was set up with iRedMail. Now, I'd like for my user accounts to be tied to their email accounts (for example, changing their email password also changes their password on servers they have access to). I've done some searching (DuckDuckGoing?) for how to use iRedMail's LDAP database as a user authentication database for UNIX accounts, but I've yet to find anything remotely helpful. Anyone ever done this have any tips?

A: So, I figured it out. Here's a quick and dirty guide on how I got it done:

*

*First, iRedMail automatically generates an SSL certificate on install. If your hostname is not what you want the CN for the cert to be, then you're going to need to generate a new SSL cert. Actually, I'd do this regardless. Here's how to accomplish step one:
$ cd iRedMail-0.8.5/tools
$ vi generate_ssl_keys.sh

# Modify the following line
export HOSTNAME="*.yourdomain.com" # I created a wildcard cert

# Set the rest (e.g., TLS_COUNTRY) to match your information

*Now we need to generate our SSL certs:
$ sh generate_ssl_keys.sh
$ mv certs/iRedMail_CA.pem /etc/pki/tls/certs/
$ mv private/iRedMail.key /etc/pki/tls/private/

*At this piont I rebooted my system. It was easier for me than restarting a bunch of services.

*Now, before we move to our LDAP clients, we need to make some changes to our LDAP server. The first change we will make is to add unixHomeDirectory to the posixAccount objectclass. The reason: I did not want my users being stuck in the homeDirectory that iRedMail associates with their account.
$ vi /etc/openldap/schema/nis.schema

# Add the following under attributetype nisMapEntry (1.3.6.1.1.1.1.27)
attributetype ( 1.3.6.1.1.1.1.28 NAME 'unixHomeDirectory'
    DESC 'The absolute path to the users home directory'
    EQUALITY caseExactIA5Match
    SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )

# Associate unixHomeDirectory with the posixAccount objectclass
objectclass ( 1.3.6.1.1.1.2.0 NAME 'posixAccount'
    DESC 'Abstraction of an account with POSIX attributes'
    SUP top AUXILIARY
    MUST ( cn $ uid $ uidNumber $ gidNumber $ homeDirectory )
    MAY ( userPassword $ loginShell $ gecos $ unixHomeDirectory $ description ) )

*Now we are going to add an obMemberOf attribute for our users. This will be used later with sssd.
$ vi /etc/openldap/schema/iredmail.schema

# I added this under listAllowedUser attributetype (1.3.6.1.4.1.32349.1.2.3.3)
attributetype ( 1.3.6.1.4.1.32359.1.2.3.4 NAME 'obMemberOf'
    DESC 'Distinguished name of a group of which the object is a member'
    EQUALITY distinguishedNameMatch
    SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 )

# And then I associated it with the objectclass mailUser
objectclass ( 1.3.6.1.4.1.32349.1.2.4.3 NAME 'mailUser'
    DESC 'Mail User' SUP top AUXILIARY
    MUST ( mail $ uid )
    MAY ( storageBaseDirectory $ mailMessageStore $ homeDirectory $
          userPassword $ mailHost $ mailUID $ mailGID $
          mailQuota $ mailQuotaMessageLimit $
          mailForwardingAddress $ shadowAddress $ accountStatus $
          userRecipientBccAddress $ userSenderBccAddress $
          enabledService $ telephoneNumber $ backupMailAddress $
          mtaTransport $ memberOfGroup $ expiredDate $
          lastLoginDate $ lastLoginIP $ lastLoginProtocol $
          preferredLanguage $ disclaimer $ accountSetting $
          title $ userManager $
          mailWhitelistRecipient $ mailBlacklistRecipient $
          domainGlobalAdmin $ obMemberOf ))

*I made the following changes to /etc/openldap/slapd.conf
# Comment out disallow bind_anon
# Disallow bind as anonymous.
#disallow    bind_anon

# Uncommented this line
# Uncomment below line to allow binding as anonymouse.
allow bind_anon_cred

#
access to dn.regex="cn=[^,]+,dc=domain,dc=com"
      by anonymous                    auth
      by self                         write
      by users                        none

# Added these two lines
access to dn.exact=""
      by * read

# And these two
access to dn.exact="cn=Subschema"
     by * read

# And gave anonymous read access
# Set default permission.
access to *
    by anonymous                    read
    by self                         write
    by users                        read

*Now I went to https://www.mydomain.com/iredadmin and added a user. After adding the user, an ldapsearch returns the following:
# user1@mydomain.com, Users, mydomain.com, domains, mydomain.com
dn: mail=user1@mydomain.com,ou=Users,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
objectClass: inetOrgPerson
objectClass: mailUser
objectClass: shadowAccount
objectClass: amavisAccount
mail: user1@mydomain.com
userPassword:: XXX
uid: user1
storageBaseDirectory: /var/vmail
mailMessageStore: vmail1/mydomain.com/d/a/w/user1-2013.11.19.17.43.46/
homeDirectory: /var/vmail/vmail1/mydomain.com/d/a/w/user1-2013.11.19.17.43.46/
enabledService: mail
enabledService: deliver
enabledService: lda
enabledService: smtp
enabledService: smtpsecured
enabledService: pop3
enabledService: pop3secured
enabledService: imap
enabledService: imapsecured
enabledService: managesieve
enabledService: managesievesecured
enabledService: sieve
enabledService: sievesecured
enabledService: forward
enabledService: senderbcc
enabledService: recipientbcc
enabledService: internal
enabledService: lib-storage
enabledService: shadowaddress
enabledService: displayedInGlobalAddressBook
shadowLastChange: 0
amavisLocal: TRUE
mailQuota: 0
cn: Good User
givenName: user1
sn: user1
preferredLanguage: en_US
employeeNumber: Application Developer
accountStatus: active

*As we can see, everything to make this a posixAccount is missing. So, that's what we're going to do:
 $ vi /tmp/user1.modify
 # Now, I create a file called /tmp/user1.modify that looks like this
 dn: mail=user1@mydomain.com,ou=Users,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
 changetype: modify
 add: objectClass
 objectClass: posixAccount
 -
 add: loginShell
 loginShell: /bin/bash
 -
 add: uidNumber
 uidNumber: 2006
 -
 add: gidNumber
 gidNumber: 2006
 -
 add: unixHomeDirectory
 unixHomeDirectory: /home/user1

*And we run ldapmodify to add the attributes to the account
ldapmodify -x -D "cn=Manager,dc=mydomain,dc=com" -W -f /tmp/user1.modify

*Now I create an LDAP group.
vi /tmp/devgroup.ldif

# Paste the following in there
dn: cn=developers,ou=Groups,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
objectClass: posixGroup
objectClass: top
cn: developers
userPassword:: {crypt}x
gidNumber: 1500
memberUid: user1

# And add to LDAP
ldapadd -x -D "cn=Manager,dc=mydomain,dc=com" -W -f /tmp/devgroup.ldif

*Add user1 as an obMemberOf the developers group
 vi /tmp/user1.modify

 # It should now look like this
 dn: mail=user1@mydomain.com,ou=Users,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
 changetype: modify
 add: obMemberOf
 obMemberOf: cn=developers,ou=Groups,domainName=mydomain.com,o=domains,dc=mydomain,dc=com

 # Run ldapmodify
 ldapmodify -x -D "cn=Manager,dc=mydomain,dc=com" -W -f /tmp/user1.modify

*At this point we have user1, two custom attributes (obMemberOf, unixHomeDirectory), and an LDAP group for developers. It's now time to set up a few clients. The first client I set up was running Ubuntu 12.04 server. Here are the steps for that client:
  # First install all the relevant packages
  $ apt-get install ldap-utils libpam-ldap libnss-ldap nslcd

  # I need the SSL cert from my iRedMail host
  scp user@mydomain.com:/etc/pki/tls/certs/iRedMail_CA.pem /etc/ssl/certs/cacert.pem

  # Now we configure the LDAP client
  $ vi /etc/ldap.conf

  # Here's what my ldap.conf ended up looking like:
  # BEGIN /etc/ldap.conf
  host ldap.mydomain.com
  base dc=mydomain,dc=com
  ldap_version 3
  # You can user cn=Manager,dc=yourdomain,dc=com if you'd like. iRedMail sets up this vmail account as read-only, so I went with that instead.
  rootbinddn cn=vmail,dc=mydomain,dc=com
  pam_password ssha
  nss_base_passwd ou=Users,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
  nss_base_shadow ou=Users,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
  nss_base_group ou=Groups,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
  nss_map_attribute homeDirectory unixHomeDirectory
  pam_login_attribute uid
  ssl start_tls
  tls_checkpeer yes
  tls_cacertfile /etc/ssl/certs/cacert.pem
  # END /etc/ldap.conf

  # Create file /etc/ldap.secret and put the plain text password for your rootbinddnn in there, then 'chmod 600 /etc/ldap.secret (root:root ownership).

  # Next I edit /etc/nslcd.conf. Here is that file
  # BEGIN /etc/nslcd.conf
  uid nslcd
  gid nslcd
  uri ldap://ldap.mydomain.com
  base dc=mydomain,dc=com
  ldap_version 3
  ssl start_tls
  tls_reqcert demand
  tls_cacertfile /etc/ssl/certs/cacert.pem
  # END /etc/nslcd.conf

  # Now I edit /etc/ldap/ldap.conf and add the following line to the bottom
  # It is the only uncommented line in the file
  TLS_CACERT    /etc/ssl/certs/cacert.pem

  # My PAM files look as follows

  # BEGIN /etc/pam.d/common-account
  account   [success=2 new_authtok_reqd=done default=ignore]    pam_unix.so
  account   [success=1 default=ignore]  pam_ldap.so
  account   requisite           pam_deny.so
  account   required            pam_permit.so
  # END /etc/pam.d/common-account

  # BEGIN /etc/pam.d/common-auth
  auth  [success=2 default=ignore]  pam_unix.so nullok_secure
  auth  [success=1 default=ignore]  pam_ldap.so use_first_pass
  auth  requisite           pam_deny.so
  auth  required            pam_permit.so
  # END /etc/pam.d/common-auth

  # BEGIN /etc/pam.d/common-password
  password  [success=2 default=ignore]  pam_unix.so obscure sha512
  password  [success=1 user_unknown=ignore default=die] pam_ldap.so try_first_pass
  password  requisite           pam_deny.so
  password  required            pam_permit.so
  # END /etc/pam.d/common-password

  # BEGIN /etc/pam.d/common-session
  session   [default=1]         pam_permit.so
  session   requisite           pam_deny.so
  session   required            pam_permit.so
  session       optional            pam_umask.so
  session   required                    pam_unix.so
  session   optional            pam_ldap.so
  session   optional                    pam_systemd.so
  session required pam_mkhomedir.so skel=/etc/skel umask=0022
  # END /etc/pam.d/common-session

  # I then edit /etc/nsswitch.conf and added ldap at the end of the passwd, group and shadow lines
  passwd:         compat ldap
  group:          compat ldap
  shadow:         compat ldap

  # Enable the service and restart it
  $ update-rc.d nslcd enable
  $ /etc/init.d/nscd restart

  # Test things out
  $ gnutls-cli --x509cafile /etc/ssl/certs/cacert.pem ldap.mydomain.com
  $ ldapsearch -H"ldap://ldap.mydomain.com" -D "cn=vmail,dc=mydomain,dc=com" -b "dc=mydomain,dc=com" -W -d-1 -Z
  $ getent passwd
  $ id user1

  # You should now be able to su to user1 and ssh in as user1.

*The next client I set up was a CentOS 6.4 server running sssd.
  # Install the relevant packages
  $ yum install openldap-clients sssd
  $ chkconfig sssd on

  # For now I set SELinux to permissive
  $ echo 0 > /selinux/enforce

  # scp  my cert over
  $ scp user@mydomain.com:/etc/pki/tls/certs/iRedMail_CA.pem /tmp
  $ scp user@mydomain.com:/etc/pki/tls/private/iRedMail.key /tmp

  # combine the two certs
  $ awk 'FNR==1{print ""}1' /tmp/iRedMail.key /tmp/iRedMail_CA.pem > /etc/openldap/cacerts/iRedMail_CA.pem
  $ cacertdir_rehash /etc/openldap/cacerts/

  # Enable sssd.
  $ authconfig --enableldap --enableldapauth --ldapserver=ldaps://ldap.mydomain.com --ldapbasedn="dc=mydomain,dc=com" --update

  # I modified my /etc/sssd.conf file to look like this:
  [sssd]
  config_file_version = 2
  services = nss, pam
  domains = LDAP
  [nss]
  filter_users = root,named,avahi,haldaemon,dbus,radiusd,news,nscd

  [pam]

  [domain/LDAP]
  ldap_search_base = dc=mydomain,dc=com
  ldap_access_filter = obMemberOf=cn=developers,ou=Groups,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
  id_provider = ldap
  auth_provider = ldap
  chpass_provider = ldap
  access_provider = ldap
  ldap_schema = rfc2307
  ldap_uri = ldap://ldap.mydomain.com
  ldap_user_name = uid
  ldap_user_home_directory = unixHomeDirectory
  ldap_user_search_base = ou=Users,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
  ldap_group_search_base = ou=Groups,domainName=mydomain.com,o=domains,dc=mydomain,dc=com
  ldap_default_bind_dn = cn=vmail,dc=mydomain,dc=com
  ldap_default_authtok_type = password
  ldap_default_authtok = p4ssw0rd
  enumerate = true
  cache_credentials = true
  ldap_tls_reqcert = never
  ldap_tls_cacertdir = /etc/openldap/cacerts

  # Start sssd in the foreground with debugging on.
  $ /usr/sbin/sssd -i -d7

  # Open another terminal and do the following
  $ getent passwd
  $ id user1
  $ ssh user1@localhost
  $ su - user1

  # Check the other terminal for any errors and fix as necessary.
  # If no errors... break the sssd process with Ctrl+C
  $ service sssd start

Here are some of the errors I ran into during this process and what I did to fix each of them.

Warning: LDAP access rule 'filter' is set, but no ldap_access_filter configured. All domain users will be denied access.

This is why I added the LDAP group on my server and the obMemberOf attribute. I then used it on the sssd client as my ldap_access_filter (i.e., anyone who has attribute obMemberOf set to the DN for the development group has access to the system.

TLS: skipping 'iRedMail_CA.pem' - filename does not have expected format (certificate hash with numeric suffix)

Running 'cacertdir_rehash /etc/openldap/cacerts/' seemed to fix things. It created a symlink (the certificates hash with numeric suffix) that points to iRedMail_CA.pem
I ran into quite a few other errors (A plethora of "Invalid Credentials," "Access Denied," and other access related errors). I will update this later to cover them as well.

A: I wonder whether you can configure sssd to use a flexible ldap filter and lookup different (non-default) ldap attributes in this case.
If you modified iRedMail LDAP schema file, you should pay attention to sync this schema with upstream.


text:
Q: How to split a string value from angular variable and set it to two html controls In Angular, how to split a variable's two values and set it to two controls.
like var date="3,2".split(',');
The variable 'date' contains data values for a textbox and a dropdown list.
<input id="txtDateBox" type="text" ng-model="response" value="3"/>

<select name="singleSelect" ng-model="data.singleSelect">
      <option>2</option>
</select>

Thanks

A: Create a filter to split your data.
myapp.filter('CommaSplitter', function(){
    return function(value){
        return value ? value.split(',') : undefined;
    }
});

Then use it:
<select name="singleSelect" ng-model="data.singleSelect" ng-options="'Option ' + option for option in values | CommaSplitter">
</select>


text:
Q: Fillrate Issues on Android Emulator I'm getting very low framerate with OpenGL ES. If the model is far from the camera I get like 35 fps, but if it fills entire screen (say, a skybox) I'm getting 6-8 fps. It even happens when rendering a skybox alone and nothing else.
Is that actually an issue with the emulator? I'm using Windows XP SP3 on a AMD Athlon 64 Dual Core 3800 2Ghz, with 1 Gb RAM.

A: The emulator doesn't use any hardware acceleration AFAIK, so it can get quite slow at times. Especially with blending and in other fillrate taxing situations, like yours. Have you tried running your project on an actual device? I'm guessing it will perform better on a phone.
Disclaimer: My experience with the emulator so far is on a very dated Athlon XP machine, so with current PCs it probably is much faster -- on my PC it's practically unusable.


text:
Q: Change fragment's Textview from main activity I have been following tutorials on how to implement bottom nav bar with three fragments. I am now stuck when I need to update my profile fragment's textview. MainActivity code:
public class MainActivity extends AppCompatActivity {
    String activeUser = "", response="myresponse";
    ProgressDialog progDailog;

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

    activeUser = getIntent().getStringExtra("currentUser");

    setupNavigationView();

    new getProfileData().execute("myurl");

    getSupportActionBar().setTitle("Home");

}

private void setupNavigationView() {
    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
    if (bottomNavigationView != null) {

        // Select first menu item by default and show Fragment accordingly.
        Menu menu = bottomNavigationView.getMenu();
        selectFragment(menu.getItem(1));

        // Set action to perform when any menu-item is selected.
        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        selectFragment(item);
                        return false;
                    }
                });
    }
}

/**
 * Perform action when any item is selected.
 *
 * @param item Item that is selected.
 */
protected void selectFragment(MenuItem item) {

    item.setChecked(true);

    switch (item.getItemId()) {
        case R.id.menu_home:
            // Action to perform when Home Menu item is selected.
            pushFragment(new HomeFragment());

            break;
        case R.id.menu_news:
            // Action to perform when News Menu item is selected.
            pushFragment(new NewsFragment());
            break;
        case R.id.menu_profile:
            // Action to perform when Profile Menu item is selected.
            pushFragment(new ProfileFragment());
            break;
    }
}

/**
 * Method to push any fragment into given id.
 *
 * @param fragment An instance of Fragment to show into the given id.
 */
protected void pushFragment(Fragment fragment) {
    if (fragment == null)
        return;

    FragmentManager fragmentManager = getFragmentManager();
    if (fragmentManager != null) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (ft != null) {
            ft.replace(R.id.main_container, fragment);
            ft.commit();
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.three_dots_items, menu);
    return true;
}

ProfileFragment code:
public class ProfileFragment extends Fragment {

TextView profile;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.profile_fragment, container, false);
    profile = (TextView) view.findViewById(profileData);
    return  view;
}

public void updateTextView(String text){
    profile.setText(text);
}

My profilefragment.xml has a textview with id profileData. In my ProfileFragment java class, I introduced a method updateTextView to update the profile layout but I don't know where or how to call this method in my mainactivity.java. I've searched several questions on this topic and tried the different solutions proposed on stackoverflow but I keep getting a null pointer exception error whenever i try to call that method in my mainactivity. Please can someone help me?

A: Following changes you need to make in MainActivity:
Get your fragment (i.e ProfileFragment) by tag using method:
Profile Fragment fragment =  (ProfileFragment)getSupportFragmentManager().findFragmentByTag("tag");
 if(fragment != null)
 fragment.updateTextView();

Here tag is a String constant that you need to add while replacing fragment as
below:
In your code make following changes
FragmentTransaction ft = fragmentManager.beginTransaction();
    if (ft != null) {
        ft.replace(R.id.main_container, fragment,"tag");

A: Create a getInstance() function in Fragment
public static ProfileFragment mProfileFragment =null;
public static ProfileFragment getInstance(){
if(mProfileFragment == null){
mProfileFragment = new ProfileFragment();
}
return mProfileFragment;
}

And in your Activity class when you are trying to set text value check first instance of Fragment is null or not. If not null set text value.
if(ProfileFragment.getInstance() != null){
textview.SetText("Your Text Value here");
}

A: When replacing a container's content with a Fragment, you can always get the currently displayed Fragment by calling getSupportFragmentManaget().findFragmentById(...) with that container's ID. You can then check if the current Fragment is a ProfileFragment and, if so, make your update:
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
    if (fragment instanceof ProfileFragment) {
        ((ProfileFragment) fragment).updateTextView(text);
    }


text:
Q: Function executes when maximizing the window I have the following script which redirects the user to another slide within my presentation when  scrolling to the bottom of the page. ( i am using Reveal.js )
jQuery(function ($) {
  $("#creation").on("scroll", function () {
    if (
      Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >=
      Math.round($(this)[0].scrollHeight, 10)
    ) {
      location.hash = "#film";
    }
  });
});

If the browser it's not in fullscreen and the user has scrolled down a bit, then makes the window fullscreen again, the script will automatically trigger.
Can someone help me avoiding this behaviour when resizing the window to fullscreen?