text:
Q: Gradient / shadows in UIImageView like Flipboard I'm looking to create a shadow-like-gradient in my UIImageView like how it is in Flipboard.
An example of it is a picture in the this image

As you can see on the right iPhone, there is a darker gradient at the top and bottom. This is so that if the picture is white, the white text can still be seen.
Anybody have any suggestions on how I can implement this? I am new to iOS development thus clueless about this. Thanks!

A: nowadays this work properly applying right into UIImageView layer
// Set image over layer
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = imageView.frame;

// Add colors to layer
UIColor *centerColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.25];
UIColor *endColor = [UIColor grayColor];
gradient.colors = [NSArray arrayWithObjects:
                               (id)[endColor CGColor],
                               (id)[centerColor CGColor],
                               (id)[endColor CGColor],
                               nil];

[imageView.layer insertSublayer:gradient atIndex:0];

take it from here

A: You could use CAGradientLayer:

*

*Add QuartzCore.framework to your project. (See Linking to Library or Framework).

*Import the QuartzCore header:
#import <QuartzCore/QuartzCore.h>

*Add a CAGradientLayer to the view in question. For example, for a simple gradient from gray to white:
- (void)addGradientToView:(UIView *)view
{
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = view.bounds;
    gradient.colors = @[(id)[[UIColor lightGrayColor] CGColor],
                        (id)[[UIColor whiteColor] CGColor]];
    [view.layer insertSublayer:gradient atIndex:0];
}

Or from one shade of gray, to another, and back:
- (void)addGradientToView:(UIView *)view
{
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = view.bounds;
    gradient.colors = @[(id)[[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0] CGColor],
                        (id)[[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0] CGColor],
                        (id)[[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0] CGColor]];
    [view.layer insertSublayer:gradient atIndex:0];
}

Just change the colors in your array of colors to alter the gradient to achieve the desired effect. You may want to put the image view in a container view and apply the gradient to the container view, not the image view. Furthermore, presumably obvious, but this assumes that the images you are using in your UIImageView employ transparent backgrounds. If they don't, you'll have to alter them either (a) build the gradient right into the image; or (b) replace the background of the image with a transparency so the above CAGradientLayer effect can be seen.

A: SWIFT 3
    let gradient = CAGradientLayer()
    gradient.frame = imageView.bounds

    let startColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.25)
    let endColor = UIColor.gray

    gradient.colors = [startColor.cgColor, endColor.cgColor]
    imageView.layer.insertSublayer(gradient, at: 0)

A: I've done this effect in my applications before simply by overlaying a transparent image containing the darkened areas over the photo. Implementation wise, that generally means inserting another UIImageView above your photo's view in the view hierarchy.

A: Translated to Swift:
var gradient = CAGradientLayer()
gradient.frame = imageView.bounds
let startColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.25)
let endColor = UIColor.grayColor()
gradient.colors = [startColor, endColor]
imageView.layer.insertSublayer(gradient, atIndex: 0)


text:
Q: How to write ng repeat for below Json Data? My data is coming as below from service. I have tried key, value but its not working.
I want to display all Product_Groups using ng-repeat in a dropdown.
I am using
ng-repeat="value.Product_Group for (key, value) in pgroup track by $index"

A: Try this

    {{item.Product_Group}}

instead of
ng-repeat="value.Product_Group for (key, value) in pgroup track by $index"

DEMO

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
    $scope.pgroup = [
     {Product_Group: "TrueBeam"},
     {Product_Group: "TrueBeam1"},
     {Product_Group: "TrueBeam2"}
    ];
});

    {{item.Product_Group}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to make a function to test the ssh connect-ability of devices on the network without typing in the individual device? I am working on a program where connecting over SSH to a raspberry pi is necessary to run the program through my GUI app window in python, here is what I have right now to "test" ssh connections on all devices but i have to type in the actual IP of the pi itself. I need to make this where it just tests connection of everything on the network and connects to the available device.
Any help?
def raspi_connecter():
    for n in range(1, 255):
        server_ip= "10.0.0.153".format(n)
        subprocess.Popen('ssh' + ' ' + 'dev@' + server_ip, shell= True)

A: Here's python2 program (I've never reworked it for python3) that finds your Raspberries. It runs nmap to create XML output then crudely parses that.
It needs the iproute module sudo apt install python{,3}-pyroute
#!/usr/bin/python2

from pyroute2 import IPRoute
import socket
import subprocess
import xml.etree.ElementTree as ET

ip = IPRoute()
for x in ip.get_addr(label='eth0',family=socket.AF_INET):
  ipa =x.get_attr('IFA_ADDRESS')+"/"+str(x['prefixlen'])

print ipa
process = subprocess.Popen(['sudo','nmap','-oX', '/tmp/nmap.xml','-sn',ipa],stdout=subprocess.PIPE)
process.wait()

tree = ET.parse('/tmp/nmap.xml')
for node in tree.iter('address'):
    try:
        if node.attrib['addrtype'] == "ipv4":
        ip = node.attrib['addr']
    except:
        pass
    try:
        if node.attrib['vendor'] == "Raspberry Pi Foundation":
        print "IP:", ip
    except:
        pass

Once you have an IP address for a Raspberry then you can run ssh with subprocess (or ping or netcat). It will need additional testing for Raspberry Pi 4 and Pi400 devices (as I don't have either of those (which use the new MAC OUI).


text:
Q: SQL update query for balances using Access raises 'Operation must use an updateable query' I have the following query (MS Access 2010) which I'm trying to use to update a table with a running balance:
UPDATE Accounts a SET a.CurrentBalance =
(SELECT sum(iif(c.categoryid = 2,t.Amount * -1, t.Amount)) +
        (select a1.openingbalance
         from accounts a1 where a1.accountid = a.accountid) AS TotalAmount
FROM transactions t inner join (
     transactiontypes tt inner join
     categories c on c.categoryid = tt.categoryid)
     on t.transactiontypeid = tt.transactiontypeid);

The tables used are:

A: A work around for the "Query must use an updateable query" is to use a temporary table and then update the final target data based on the aggregated data in the temporary table. In your case, as mwolfe suggests, you have an aggregate function in the inner select query. The workaround could provide a quick fix for this situation, as it has for me.
Ref: http://support.microsoft.com/kb/328828
This article helped me understand the specifics of the situation and provided the work around:
http://www.fmsinc.com/MicrosoftAccess/query/non-updateable/index.html

A: You cannot use aggregate functions (like SUM) in an update query.  See Why is my query read-only? for a full list of conditions that will cause your query to be "non-updateable".

A: The Access db engine includes support for domain functions (DMax, DSum, DLookup, etc.).  And domain functions can often allow you to circumvent non-updateable query problems.
Consider DSum() with these 3 rows of data in MyTable.
id MyNumber
 1        2
 2        3
 3        5

Then in the Immediate window, here are 2 sample DSum() expressions.
? DSum("MyNumber", "MyTable")
 10

? DSum("IIf(id=1,MyNumber * -1, MyNumber)", "MyTable")
 6

I think you may be able to use something like that second expression as a replacement for the sum(iif(c.categoryid = 2,t.Amount * -1, t.Amount) part of your query.
And perhaps you can use a DLookup() expression to get your TotalAmount value.  Unfortunately I got frustrated trying to translate your current SQL to domain functions.  And I realize this isn't a complete solution, but hope it will point you to something useful.  If you edit your question to show us brief samples of the starting data and what you hope to achieve from your UPDATE statement based on that sample data, I would be willing to have another look at this.
Finally, consider whether you absolutely must store CurrentBalance in a table.  As a rule of thumb, avoid storing derived values.  Instead, use a SELECT query to compute the derived value when you need it.  That approach would guarantee CurrentBalance is always up-to-date whenever you retrieve it.  It would also spare you the effort to create a working UPDATE statement.


text:
Q: How location tracking is different than other background task? In Windows Phone 8, it is suggested that, if I use LocationTracking as suggested in following code, my application will get location information continuously.
<BackgroundExecution>
<ExecutionType Name="LocationTracking" />
</BackgroundExecution>

Now, Background Agent only executed after ~30 mins, and which is also with lots of limitations, like, it may run or may not run depending on OS.
How LocationTracking is different than Background Agent. Will it gives location every time location changes, or still it may invoke after 30 min.
Thanks.

A: As MSDN says:

On Windows Phone 8, a location-tracking app can continue to run in the background after the user navigates away, as long as the app continues to actively track location. This feature enables scenarios such as an app that provides turn-by-turn directions. For a walkthrough of creating a simple app that runs in the background, see How to run location-tracking apps in the background for Windows Phone 8.

There are also more differences and you must look out for API restrictions.
You can compare it with Background agent unsupported api.
And you should also be aware of some Additional requirements for specific app types.


text:
Q: Universal norm of global function field. The kernel of global reciprocity map for a global field $k$ is given by intersection of norm groups of finite extension of $k$. In the case of number field I know that this is non-trivial and even has some explicit description. However, I managed to find no result in the case of global function field, other than the fact that the element in the universal norm group must be and $n$th power for any positive integer $n$.
So I would like to know:
$1.$ Is universal norm non-trivial in the case of global function field?
$2.$ If so is there an explicit description?

A: I found that from Cohomology of number fields that this group is indeed trivial.


text:
Q: Search in .txt file in c++ only get's the first line I got some sort of room reservation program so i wanna search in .txt file so i can find the pre reserved rooms .
the Problem is:
The search function only reads the first line in the .txt file
so when i enter a duplicated information it checks only the first line
can u help me out with it Thanks
int search(int search_num){
string search= to_string(search_num);
int offset;
string line ;
ifstream myfile;
myfile.open("booked.txt", ios::app);
ofstream booked ("booked.txt", ios ::app);
     if(myfile.is_open())
{
    while(!myfile.eof())
    {
        getline(myfile,line);
        if((offset=line.find(search,0))!=string :: npos)
        {
            return 1;
        }
        else {
            return 2;
            }
    }
    myfile.close();
}

else
    cout <<"Couldn't open" << endl;

}

A: You are ending the execution of the function by returning a value in both cases of the if statement. Returning a value will end the execution of the function, so you always end after reading the first line. My guess is you want to move the return 2; to the very end of your function.
Note that this way you also always return without ever calling myfile.close() which might cause problems elsewhere. While I don't understand the meaning of your return values 1 and 2, I suggest this:
int search(int search_num){
 string search= to_string(search_num);
 int offset;
 string line ;
 ifstream myfile;
 myfile.open("booked.txt", ios::app);
 int return_value = 2;
 ofstream booked ("booked.txt", ios ::app);
 if(myfile.is_open()) {
    while(!myfile.eof()) {
        getline(myfile,line);
        if((offset=line.find(search,0))!=string :: npos) {
            return_value = 1;
            break;
        }
    }
    myfile.close();
 } else {
    cout <<"Couldn't open" << endl;
 }
 return return_value;
}


text:
Q: Redux/Saga/React initialize a component with dispatch props using mapDispatchToProps I'm using React with Redux and Saga. My component needs to dispatch an action when user clicks so I use the mapDispatchToProps to map the action into props.
If I use that component from other component, IDE will warn me that I need pass in this dispatch props. However I think dispatch props should be initialized by itself so I don't need to pass in from outside.
Am I understanding correctly?
Example below: I have a DispatchComponent that has a dispatch props. I want to use DispatchComponent in RootComponent. However I have to pass in sendAction in RootComponent otherwise it will not initialize properly.
DispatchComponent.tsx
type DispatchProps = {
    sendAction: () => void;
};

export const DispatchComponent: React.FunctionComponent<DispatchProps> = (props) => {
    return (
        <Button onClick={props.sendAction}>Click me</Button>
    );

};

const mapDispatchToProps = (dispatch: Dispatch<Action>) => ({
    sendAction: () =>
        dispatch(setAction)
});

export default connect(
    null,
    mapDispatchToProps)
(DispatchComponent);

RootComponent.tsx
export const RootComponent = () => {
    return (
        <DispatchComponent/> // IDE here will warn me that I need to pass in `sendAction`
    );

};

export default connect(
    null,
    null)
(RootComponent);

A: You can add a type to the connected props
https://redux.js.org/recipes/usage-with-typescript/#typing-the-connect-higher-order-component
and make sure you are importing the default component (connected one)


text:
Q: Java: String.toCharArray() with unicode characters I know that char cannot contain Unicode characters (like char c = '\u1023'). So how would I go about doing
    String s = "ABCDEFG\u1023";
    char[] c = s.toCharArray();

I would like to convert s to a CharArray for performance reasons as I have to loop through every character in a potentially very long string which is inefficient. Anything which achieves the same result is fine.
Thanks a lot!
EDIT:
Actually char can contain unicode chars. I'm just being stupid. Thanks to those who helped out anyway.

A: Three things:

*

*A char most certainly can have u1023.

*toCharArray() will return a char array that is virtually the same as UTF16

*Since a char is 16 bit, and the Unicode spans 21 bits, the characters outside the BMP are encoded as two surrogate chars. Java 1.5 onwards has APIs for this, for example String.codePointAt(...). If you are using Java 1.4 or earlier, look into ICU4J.

A: In Java, a char is essentially an unsigned short.  In order to iterate through a string that has unicode characters outside of the range supported by char (the first 65536), you should use the following pattern, which stores each codepoint as an int.
for (int i = 0; i < str.length();) {
    int ch = str.codePointAt(i);
    // do stuff with ch...
    i += Character.charCount(ch);
}

Java was designed with first-class support for the first 65536 characters, which at the time was an improvement over C/C++, which had first-class support for only the first 128 or 256 characters.  Unfortunately, it means that the above pattern is necessary in Java to support the out-of-range characters that are becoming more common.

A: Java char can contain the most Unicode characters as the others have already mentioned, but the characters outside of Basic Multilingual Plane (BMP) are split into multiple chars and handling them independently might break the string.
To be safe you can split the string into string array:
String[] c = s.codePoints()
    .mapToObj(cp -> new String(Character.toChars(cp)))
    .toArray(size -> new String[size]);

... or use isSurrogate, isLowSurrogate and isHighSurrogate methods of Character object to prevent alteration of a single char within the pair:
Character.isSurrogate('a');

A: Whoever told you that in Java char can't contain Unicode characters, was wrong:

The values of the integral types are integers in the following ranges:

*

*For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to
  65535


text:
Q: Get Areas associated with an MVC project Is there a way I can get the names of the areas in an MVC project?
Here's a few ways I can think of:
a) If I had the source, I could browse through the project folder structure and enumerate the folders under the Areas folder. But that wouldn't guarantee all the folders represent areas unless I also enumerated the Controllers and Views folder under each of the sub-folders. This approach, as you can tell, sucks.
b) From the binary, I could enumerate all namespaces that match the criteria RootNamespaceOfProject.Areas.*.
Or, I am sure there's a more elegant way. There must be some dictionary in the ASP.NET MVC framework that keeps a record of all the areas.
Secondly, is there also a programmatic construct in the MVC framework that represents an area? I can't seem to find one. There are only four constructs that are related to areas:
 1. AreaRegistration
 2. AreaRegistrationContext
 3. IRouteWithArea
 4. AreaHelpers (an internal class)

If there were one, would it be possible, say, to enumerate all the controllers within that area?
Edited
I just noticed that there's this file called MVC-AreaRegistrationTypeCache.xml in the folder \Windows\Microsoft.NET\Framework\v4.x.x\Temporary ASP.NET Files\root\RandomlyGeneratedHash1\RandomlyGeneratedHash2\UserCache.
This folder has two files:
a) MVC-AreaRegistrationTypeCache.xml: This file has the list of all the areas in all the assemblies on the machine that have areas.
b) MVC-ControllerTypeCache.xml: This file lists the controllers within the areas of the assemblies.
Now, the only thing to find out is if there's some programmatic way to have the MVC framework read these files and tell me if a certain area exists in a binary.
I am thinking that the AreaRegistration class might be the one. Exploring it further...

A: It would seem that the only way you will be able to retrieve the routes registered in your project is by enumerating the project for types which inherit AreaRegistration, there does not appear to be any object private or public which tracks currently registered areas.
Long explanation follows...
One hurdle to keep in mind here is that areas are little more than a coupling between an arbitrary string and a list of namespaces. When an area is registered it is merely extending the route collection for the application with some new rules identifiable by a unique "area" DataToken.
If you look at the process for registering an area, you must inherit from System.Web.Mvc.AreaRegistration and override RegisterArea(). RegisterArea() receives an AreaRegistrationContext which defines an area name, route collection and object state, but if you observe the format for implementing RegisterArea(), it returns void and does nothing to preserve the context object. What's more, if you look at the code which runs before RegisterArea() is fired (Reflector), you can see that the AreaRegistrationContext object which is passed to RegisterArea() is never permanently tracked.
internal static void RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, object state)
{
    foreach (Type type in TypeCacheUtil.GetFilteredTypesFromAssemblies("MVC-AreaRegistrationTypeCache.xml", new Predicate<Type>(AreaRegistration.IsAreaRegistrationType), buildManager))
    {
        ((AreaRegistration) Activator.CreateInstance(type)).CreateContextAndRegister(routes, state);
    }
}

internal void CreateContextAndRegister(RouteCollection routes, object state)
{
    AreaRegistrationContext context = new AreaRegistrationContext(this.AreaName, routes, state);
    string str = base.GetType().Namespace;
    if (str != null)
    {
        context.Namespaces.Add(str + ".*");
    }
    this.RegisterArea(context);
}

As you can see, a call to the static method RegisterAllAreas() invokes the internal RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, object state), which then calls the internal CreateContextAndRegister(RouteCollection routes, object state), which creates the AreaRegistrationContext and passes it to RegisterArea().
As far as I can tell, never, at any point, is the AreaRegistrationContext created for each area stored permanently.

A: You could do what MVC is doing, iterate all the referenced assemblies and look for classes that inherit from AreaRegistration. Then you can simply get the AreaRegistration.AreaName.
I'm planning on doing this to build my top-level navbar using Twitter Bootstrap.

A: This thread was helpful in finding the answer, but nobody here posted it explicitly. Here is what I came up with, but do note you may need to adjust it depending on whether all of your areas are in the same assembly.
private IEnumerable<AreaRegistration> GetAllAreasRegistered()
{
    var assembly = this.GetType().Assembly;
    var areaTypes = assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(AreaRegistration)));
    var areas = new List<AreaRegistration>();
    foreach (var type in areaTypes)
    {
        areas.Add((AreaRegistration)Activator.CreateInstance(type));
    }
    return areas;
}


text:
Q: Using metric spring_cloud_stream_binder_kafka_offset for kafka lag I have an application consuming kafka messages for a long time without any restart.
Also I have a dash that monitors the consumer lag by the property "spring_cloud_stream_binder_kafka_offset".
When I had to restart it recently, I realized that some topics that I haven't sent messages for more than a month, started reporting some "strange values" on the same metric.
I ran the following command to check the lags on the topic and then I realized this topic with "strange values" the column current-offset was empty "-", but i'm sure that this messages were processed in the past.
kafka-consumer-groups --bootstrap-server <server> --group group-test --describe --offsets --command-config

GROUP
TOPIC
PARTITION
CURRENT-OFFSET
LOG-END-OFFSET
LAG

group-test
TEST
1
6468
6468
0

group-test
TEST
2
6396
6396
0

group-test
TEST1
0
-
88
-

group-test
TEST1
1
-
78
-

As I know, and I might be wrong, that this information about the current offset is stored inside a kafka topic.
This topic also have an expire within 7 days since nothing is consumed.
My doubt is this: As the current offset has been "cleand up", shouldnt the property "spring_cloud_stream_binder_kafka_offset" reflects somehow this? Because its leading to some misunderstanding about the metric, since I don't have this lag.
**** UPDATE ****
Described a little more about the situation.
When the MS started again, and the name of the consumer is the same, its not processing this messages that its understanding as lag.
What I mean, the MS is up and running, with the same consumer name, the topic is configured to be monitored and nothing is consumed. I have other topics inside this same MS that are processing correctly.
An extra point, is that I use the confluent cloud to check this lag and there the information show no lag, as I expected.
What I realized is that for some specific partition that received another message, the currently offset gets its value updated with the LOG-END-OFFSET and everything works fine.
My doubt is really about how this metric works with this situation, it seems to loose its reference and shows everything is lag.

A: See offset.retention.minutes. https://kafka.apache.org/documentation/#brokerconfigs_offsets.retention.minutes
It is 7 days by default, meaning the offsets are retained for 7 days after the last consumer left the group (with recent broker versions - since 2.1 if I recall correctly).
When the offsets are removed, it is as if the group never consumed anything from the topic/partition and, if started again, it will receive all the records in the topic/partition.


text:
Q: Broken jQuery Tab Switcher Liver Demo: https://tornhq.com/WorkingOn/InteractiveMap/Replaced-With-Divs.html
jQuery Tab Switch Code ignore lines 2-6
$(function () {
    $("#clickme").toggle(function () {
        $(this).parent().animate({right:'-300px'}, {queue: false, duration: 500});
    }, function () {
        $(this).parent().animate({right:'-0px'}, {queue: false, duration: 500});
    });
    $('#tab-content div').hide();
    $('#tab-content div:last').show();

    $('#Info-Side-Tabs li').click(function() {
        $('#Info-Side-Tabs li').removeClass("current");
        $(this).find('li').addClass("current");
        $('#tab-content div').hide();

        var indexer = $(this).index(); //gets the current index of (this) which is #nav li
        $('#tab-content div:eq(' + indexer + ')').fadeIn(); //uses whatever index the link has to open the corresponding box
    });
});

I am having trouble implementing a jQuery tab switch into my website:
"$(this).find('li').addClass("current");"

is used to find 'a', however I need it to change the class of the li and not the a.
The only tab switch content which is showing is part of the second one from the top and not all of it. I am just very confused at this moment in time and could really do with some help.

Update:
    $('#Info-Side-Tabs li').removeClass("current");

Seems to be removing the class upon clicking, however

    $(this).find('li').addClass("current");

Does not seem to add the class to the new clicked tab.

    $("#tab-3").toggle(function () {
        // $('#Map-Selection-Info').animate({right:'-976px'}, {queue: false, duration: 500});
        $('#Map-Selection-Info').animate({marginLeft: '976px'}, 1000).addClass('current');
    }, function () {
        $('#Map-Selection-Info').animate({right:'670px'}, {queue: false, duration: 500});
    });

I am trying to apply the above to the 'Hide This' tab, so when you click on it, it move further right out of view and recliick to show.

Full Script So Far:
$(function () {
    $("#tab-3").toggle(function () {
        // $('#Map-Selection-Info').animate({right:'-976px'}, {queue: false, duration: 500});
        $('#Map-Selection-Info').animate({marginLeft: '976px'}, 1000).addClass('current');
    }, function () {
        $('#Map-Selection-Info').animate({right:'670px'}, {queue: false, duration: 500});
    });
    $('#tab-content div').hide();
    $('#tab-content div:last').show();

    $('#Info-Side-Tabs li').click(function() {
        $('#Info-Side-Tabs li').removeClass("current");
        $(this).find('li').addClass("current");
        $('#tab-content div').hide();
        var href = $(this).find('a').attr("href");
        $('#tab-content div' + href).fadeIn().find('*').show();
    });
});

A: Remove .find('li').
You don't need that as the click event is fired on the li element. So $(this) IS the li element.
Then you do:
$('#Info-Side-Tabs li').click(function() {
    $('#Info-Side-Tabs li').removeClass("current");
    $(this).addClass("current");
    $('#tab-content div').hide();
    var href = $(this).find('a').attr("href");
    $('#tab-content div' + href).fadeIn()
});

That works for me, other than there being no "#tab2" and "#tab3" content divs.
The index code wouldnt work because the index is numerical and you are trying to match a content div, it won't match because the divs have string id's
Edit
You can show all child elements using the following:
$('#tab-content div' + href).fadeIn().find('*').show();
Edit 2
The :last selector is finding the deepest div element inside #tab-content and showing it, which is: <div id="Social-Fun" style="display: none;">
That's why you don't see anything.
You could add a class to each div, something like class='country' and then you could do:
$('#tab-content div.country').last().show()


text:
Q: Android layout designing I am new to Android development. Can you give me some tips on creating UI layout as shown on the image below? Thanks for any help!

A: Try this layout design
  <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_below="@+id/imgLogo"
        android:background="#092EA1"
        android:orientation="vertical"
        android:paddingBottom="10dp"
        android:layout_marginTop="30dp"
        android:paddingLeft="10dp"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:paddingRight="10dp" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:layout_marginTop="10dp"
                android:gravity="center_horizontal"
                android:text="@string/login"
                android:textColor="@android:color/white"
                android:textSize="25sp" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white" >

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="260dp"
                android:layout_height="40dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="13dp"
                android:layout_marginRight="13dp"
                android:layout_marginTop="15dp"
                android:background="@drawable/user_name" />

            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/imageView1"
                android:layout_alignLeft="@+id/imageView1"
                android:layout_alignRight="@+id/imageView1"
                android:layout_alignTop="@+id/imageView1"
                android:layout_marginLeft="40dp"
                android:maxLines="1"
                android:background="@android:drawable/editbox_background"
                android:id="@+id/textUserName"
                android:hint="@string/username" />

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="260dp"
                android:layout_height="40dp"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/imageView1"
                android:layout_marginLeft="13dp"
                android:layout_marginRight="13dp"
                android:layout_marginTop="15dp"
                android:background="@drawable/password"  />

            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/imageView2"
                android:layout_alignLeft="@+id/imageView2"
                android:layout_alignRight="@+id/imageView2"
                android:layout_alignTop="@+id/imageView2"
                android:layout_marginLeft="40dp"
                android:maxLines="1"
                android:background="@android:drawable/editbox_background"
                android:hint="@string/password"
                android:id="@+id/textPassword"
                android:inputType="textWebPassword" />

            <ImageView
                android:id="@+id/btn_login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/imageView2"
                android:layout_below="@+id/imageView2"
                android:layout_marginTop="26dp"
                android:src="@drawable/button_login" />

            <TextView
                android:id="@+id/forgotPass"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/btn_login"
                android:layout_alignRight="@+id/imageView2"
                android:text="@string/forgotText"
                android:layout_marginRight="10dp"
                android:textSize="15dp" />

            <TextView
                android:id="@+id/error_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textPassword"
                android:layout_alignRight="@+id/forgotPass"
                android:layout_below="@+id/imageView2"
                android:textColor="#f51313"
                android:text="" />

        </RelativeLayout>

    </LinearLayout>

Set the postion as you want to get

A: Come on, google around a bit before just asking questions like this.
Read these two answers (btw, found by typing "android iphone-like ui elements" in Google search):

*

*https://stackoverflow.com/a/11647020/375929

*https://stackoverflow.com/a/7212532/375929
They've got all you need, including the explanations on why it's a very bad idea to make Android apps look like iOS.
Brief summary: it's because the users of the app will hate both you as a developer and your employer/owner_of_the_app so much both of you'll be having hiccups 24/7.
And, to top that off, your app will get bad ratings and sink to the bottom of the Play Store, which is very hard to recover from --- you know, if you get 1 star in any of the reviews, you're never getting 5.0 average unless the user changers their mind and rating - and they won't, because they'll never take another look at it once they see iOS-derived UI. Also, goes without saying, no Android app with UI directly ported from iOS will ever get featured.
So please, if you're in a position where you can suggest the app owner to just use native  Android controls or, better yet, redesign the app to conform to the Android UI Design guide, please do convince them to do so and be proud for boldly taking your part in fighting the global diabolic evil.
PS I know you're probably not the one calling shots about the app --- otherwise you wouldn't be porting iOS UI to Android. It's a typical contractor thing to do that, I've had my share of it.
PPS Here's a very good lean explanation of the don't-copy-design-of-other-platforms approach to usability by Google: Pure Android


text:
Q: AJAX Pagination jQuery-2.1.4.min.js: 500 (Internal Server Error) i am working with this ajax Pagination in Codeigniter HMVC. i get the output i wanted.. BUT only on the first link. then after that, the next pages dont open. or when i click them nothing happens. i checked the element and it has errors.
Failed to load resource: the server responded with a status of http://http://localhost/TLC_HR/Job_Titles/ajaxPaginationData/10 500 (Internal Server Error)
jQuery-2.1.4.min.js:4 POST http://localhost/TLC_HR/Job_Titles/ajaxPaginationData/10 500 (Internal Server Error)k.cors.a.crossDomain.send @ jQuery-2.1.4.min.js:4n.extend.ajax @ jQuery-2.1.4.min.js:4n.(anonymous function) @ jQuery-2.1.4.min.js:4onclick @ Job_Titles:524

here are my codes.
Job_Titles.php - controller
<?php

class Job_Titles extends MY_Controller{

    public function __construct(){

        parent::__construct();
        $this->load->model('Job_Titles_Model');
        $this->load->library('Ajax_pagination');
        $this->perPage = 10;

    }

// VIEW REDIRECTING /////////////////////////////////////////////////////////

    public function index(){

    /// view ajax config/////

    $data = array();

    //total row count
    $totalRec = count($this->Job_Titles_Model->getRows());

    //configuration
    $config['first_link'] = 'First';
    $config['div'] = 'postList'; //parent div tag id
    $config['base_url'] = base_url().'Job_Titles/ajaxPaginationData';
    $config['total_rows'] = $totalRec;
    $config['per_page'] = $this->perPage;

    $this->ajax_pagination->initialize($config);

    //get data // must pass this to $this->load->view('content_view') and make it $this->load->view('content_view',$data,false)
    $data['job_titles'] = $this->Job_Titles_Model->getRows(array('limit'=>$this->perPage,$this->uri->segment(3)));

    $data['content_view'] = 'Job_Titles/jobtitles_read';
    $this->templates->admin_template($data);

    }

    public function add_view(){

    $data['content_view'] = 'Job_Titles/add_view';
    $this->templates->admin_template($data);

    }

//// pagination

    public function ajaxPaginationData(){

    $page = $this->input->post('page');
        if(!$page){
            $offset = 0;
        }else{
            $offset = $page;
        }

        //total row count
        $totalRec = count($this->Job_Titles_Model->getRows());

        //pagination config
        $config['first_link'] = 'First';
        $config['div'] = 'postList'; //parent div tag id
        $config['base_url'] = base_url().'Job_Titles/ajaxPaginationData';
        $config['total_rows'] = $totalRec;
        $config['per_page'] = $this->perPage;

        $this->ajax_pagination->initialize($config);

        //get post data

        $data['job_titles'] = $this->Job_Titles_Model->getRows(array('start'=>$offset,'limit'=>$this->perPage));

        //load the view
        $data['content_view'] = "'Job_Titles/jobtitles_read', $data, false";
        $this->templates->admin_template($data);

    }

}

?>

Job_Titles_Model.php --  model
<?php

class Job_Titles_Model extends CI_Model{

    function __construct() {
        $this->table = 'job_titles';
    }
/////  VIEW PAGINATION /////////////////////////////////////////////////////////

        public function getRows($params = array()){

        $this->db->select('*');
        $this->db->from($this->table);

        if(array_key_exists("start", $params) && array_key_exists("limit", $params)){

            $this->db->limit($params['limit'],$params['start']);
        }elseif (!array_key_exists("start", $params) && array_key_exists("limit", $params)) {
            $this->db->limit($params['limit']);
        }

        $query = $this->db->get();

        return ($query->num_rows() > 0)?$query->result_array():FALSE;
    }

}

?>

admin_template.php --- template

            <a href="<?php echo base_url(); ?>Job_Titles">Job Titles

              <?php $this->load->view($content_view); ?>

and add_view.php --- where pagination will show.
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/bootstrap/css/inputfield.css">

        <fieldset>

                <?php

                    echo form_open('Job_Titles/create');
                ?>

                    *Job Code:
                    <input type = "text" name="JOB_CODE" class ="textbox-300">
                    <?php echo form_error("JOB_CODE"); ?>

                    *Job Name:
                    <input type = "text" name="JOB_NAME" class ="textbox-300">
                    <?php echo form_error("JOB_NAME"); ?>

                <?php
                    echo form_submit('submit','Save');
                    echo form_close();
                ?>

        </fieldset>

A: i've to give an answer base on my comment (i will extend my answer based on your reply because we have to start somewhere to clean this mess ;))
first of all in your Job Titles Controller replace the part with your content view as a string with the following line of code
$data['content_view'] = array(
    "url" => "Job_Titles/jobtitles_read",
    "data" => $data,
    "blnReturnAsAString" => false
);

and in your view you should write this
$this->load->view($content_view["url"], $content_view["data"], $content_view["blnReturnAsAString"]);


text:
Q: Get content from url after redirected I am trying to set up a tool to get someone's Twitter ID without using twitter's API.
In my example, my username is quixthe2nd.
So if you enter someone's twitter username in this link:
https://twitter.com/quixthe2nd/profile_image?size=original

It would redirect to:
https://pbs.twimg.com/profile_images/1116692743361687553/0P-dk3sF.jpg

The ID is 1116692743361687553. It is listed after https://pbs.twimg.com/profile_images/.
My code is:
$url = "https://twitter.com/quixthe2nd/profile_image?size=original";
function get_redirect_target($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $headers = curl_exec($ch);
    curl_close($ch);
    // Check if there's a Location: header (redirect)
    if (preg_match('/^Location: (.+)$/im', $headers, $matches))
        return trim($matches[1]);
    // If not, there was no redirect so return the original URL
    // (Alternatively change this to return false)
    return $url;
}
function get_redirect_final_target($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
    curl_exec($ch);
    $target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    if ($target)
        return $target;
    return false;
}

    $s = $target;
    if(preg_match('/profile_images\/\K[^\/]+/',$s,$matches)) {
        print($matches[0]);
    }

My code doesn't output anything. How would I be able grab that via PHP?

A: You can use this regex and grab your value from group1,
profile_images\/([^\/]+)

Regex Demo
Alternatively, you can use \K so your full match is your intended text.
profile_images\/\K[^\/]+

Regex Demo using \K
PHP Code Demo
$s = "https://pbs.twimg.com/profile_images/1116692743361687553/0P-dk3sF.jpg";
if(preg_match('/profile_images\/\K[^\/]+/',$s,$matches)) {
    print($matches[0]);
} else {
    echo "Didn\'t match";
}

Prints,
1116692743361687553


text:
Q: Lat, Lon, Values CSV to Raster Map Using Python If I have a CSV Dataset with Lat, Lon, and Value fields, what is the best approach on generating a raster map using python? The raster Z field can be any column within this table..
L5  L6  L7  L8  L9  L10 L11 L12 L13 L14 LAT LON
3.571732    1.338448    0   9.96921E+36 -3.482845   -1.42944    133.229919  141.246002  67.685631   5.059844    24.335797   -95.088764
3.571732    1.338448    0   9.96921E+36 -3.420345   -1.42944    132.749512  140.641464  67.318848   5.105563    24.335107   -95.060013
3.571732    1.338448    0   9.96921E+36 -3.420345   -1.42944    132.230164  140.047211  67.318848   5.063346    24.334408   -95.031263
3.571732    1.338448    0   9.96921E+36 -3.420345   -1.42944    132.230164  139.463104  67.318848   5.063346    24.333701   -95.002512
3.509232    1.369698    0   9.96921E+36 -3.357845   -1.42944    131.702133  137.82196   66.940475   5.021552    24.332986   -94.973763
3.509232    1.369698    0   9.96921E+36 -3.357845   -1.49194    131.702133  137.26651   66.043732   5.021552    24.332263   -94.945013
3.509232    1.369698    0   9.96921E+36 -3.357845   -1.49194    131.165268  136.72081   66.043732   4.980192    24.331531   -94.916265
3.509232    1.338448    0   9.96921E+36 -3.357845   -1.49194    131.165268  136.184738  66.043732   4.980192    24.330792   -94.887516

Keep in mind, These are numpy arrays

A: There are two options depending on your Lat, Lon coordinates. When the Lat, Lon coordinates form an equidistant grid you can use this first option, otherwise you can use the second option below.

first option
I create the array below with values in the first column and Lat, Lon in the 2nd and 3rd column:
import numpy as np

lat = np.arange(0, 15, 5)
lon = np.arange(0, 10, 5)
val = np.random.randint(0,10, size =len(lat)*len(lon))
xx, yy = np.meshgrid(lon, lat)
array = np.array([val,  yy.ravel(), xx.ravel()]).T
print(array)

>>> array([[ 7,  0,  0],
           [ 8,  0,  5],
           [ 7,  5,  0],
           [ 3,  5,  5],
           [ 2, 10,  0],
           [ 8, 10,  5]])

When your Lat, Lon coordinates are neatly sorted you can reshape the values to get a grid array like this:
no_lon = len(np.unique(array[:,-1]))
no_lat = len(np.unique(array[:,-2]))
grid_array = array[:,0].reshape((no_lat,no_lon))[::-1]
print(grid_array)
>>> array([[2, 8],
           [7, 3],
           [7, 8]])

second option
When you have a bunch of random Lat, Lon coordinates with values like the one created here:
array = np.random.randint(0,10, size =(6,3))
print(array)
>>> array([[9 6 0]
           [7 8 8]
           [6 0 9]
           [7 7 4]
           [2 4 3]
           [0 2 9]])

you can convert this to a grid by using interpolation like this:
from scipy import interpolate

lon_list = np.arange(3, 6, 1)
lat_list = np.arange(4, 8, 1)

lon_2d, lat_2d = np.meshgrid(lon_list, lat_list)
grid_array = interpolate.griddata((array[:,-1], array[:,-2]), array[:,0],
                                  (lon_2d, lat_2d))[::-1]
print(grid_array)

>>> [[  nan  7.    6.72]
     [ 6.    5.4   5.6 ]
     [ 4.    3.8   4.  ]
     [ 2.    2.2   2.4 ]]

Note that you get nan values if your grid cells are not within the bounds of your points.
You can visualize the results using plt.imshow
import matplotlib.pyplot as plt
plt.imshow(grid_array)


text:
Q: ElasticSearch query trouble After creating my index in elastic search with the next default settings:
{    "autosuggest_destination": {
      "aliases": {},
      "mappings": {
         "destination": {
            "properties": {
               "city": {
                  "type": "string"
               },
               "country": {
                  "type": "string"
               },
               "id": {
                  "type": "string"
               },
               "state": {
                  "type": "string"
               }
            }
         }
      },
      "settings": {
         "index": {
            "creation_date": "1459329252404",
            "number_of_shards": "1",
            "number_of_replicas": "0",
            "version": {
               "created": "1070299"
            },
            "uuid": "_1D7ZW0dQwy9kiKn0kKrLw"
         }
      },
      "warmers": {}    } }

after insert data to index and verified.
I get this problem while trying to search for an auto complete word:
when i try to search for 'new' it founds matches (New York). but if i
  tries to add a space and first letter after 'new y', it founds
  nothing. and after it tries to add a space and two letters after 'new
  yo' it works.
The main problem is understand why the first letter after a word with
  a space is not a match?
example :

    GET autosuggest_destination/destination/_search {    "query": {
        "match": {
          "city": {
            "query": "new",
            "type": "phrase_prefix"
          }

           } }

    Result : New York

    GET autosuggest_destination/destination/_search {    "query": {
        "match": {
          "city": {
            "query": "new y",
            "type": "phrase_prefix"
          }

           } }

    No Result

    GET autosuggest_destination/destination/_search {    "query": {
        "match": {
          "city": {
            "query": "new yo",
            "type": "phrase_prefix"
          }

           } }

Result : New York

Does anyone have any idea what should be the problem?

A:
Elasticsearch at indexing a document is using an Analyzer (a default one or a custom one) when you search for some values it splits the document into terms and then it will make the matching with what you wanted to search.
 In your example:
New York is analyzed with the default analyzer takes place and it will split your document into 2 terms New, York.
 When you search for New it will find you the first term New, so it will give you the response New York.
If you search by New Y it will split the search into 2 terms: New, Y or New, Yo and it will try to find documents that match these 2 terms. The problem that you encounter it may be from max_expansions param.
Take a look here http://elasticsearch-users.115913.n3.nabble.com/How-exactly-works-quot-max-expansions-quot-in-match-phrase-prefix-query-td4030146.html
Also regarding the analyzer.

https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-analyzers.html

A: If i would like to query partial word such as "ork"   to (result execpted : New York)
then there's no hits.
I was looking for guide in the documation and all i could find is change the query to a wildcard which will allow me to do that.
But i wish to use phrase_prefix with just an ability to search via partial word also.
Is that possible?


text:
Q: Is it safe to run a PC fan with power low enough to stall it? I have a "6V 4.5W" solar panel (Generic) and a 12V PC cooling fan (Evercool PWR-1225H12B) that consumes 450mA at 12V full speed.

Running the fan directly from the solar panel in full sun works decently; enough to push air at an acceptable rate. It is a "permanent" setup, with the fan and solar panel always being connected.
My question is: Would there be a premature aging issue to either fan or panel if there is only partial sun?
There is a bit of hysteresis because it of course takes more power to start the fan than to keep it running. So if it stalls, it can stay stalled for quite some time before it gets going again (if at all before next sun-up).
I think the panel will be fine, as I've read that short-circuits are not inherently bad for them, so the increased stall current should be no issue.
However, I'm more concerned about the fan circuitry. Since they are designed to run from a regulated 12V supply, I wonder if the drivers will have an issue running with only partial power and a stalled fan.
I realize that it can depend on the specifics of the fan I'm using, and that the innards are not disclosed. I imagine the fans are typically similar though, so anyone who has an understanding of how a typical PC fan works may be able to shed some wisdom as to why it would or would not be an issue to stall a PC fan for extended periods.

A: Should not be a problem for either panel or fan. Note, that "stall" does not mean "short circuit", not even in brushed motors, and PC fans are brushless.

A: You are stall safe with all PC fan implementations.
Most PC fans are in fact 2 phase motors.
A good reference chip to understand is the DIODES AH2985, this chip works from 2.5 to 15 VDC and is very common in both the 5 Volt and 12 Volt fans.

The driver chips have inbuilt stall detection and restart logic, so won't overheat under any circumstances.
If you are concerned enough you can simply test the fans you use with an adjustable power supply. Bring the voltage slowly up from zero and measure the current, it will soon be apparent if you have a voltage/power/start problem.

A: There will be heat loss generated by stalled fans perhaps at 15% of the applied voltage and thus the switching transistors will be warm and heat add it to the base but this should not affect the reliability of the fan if the stall starting voltage is < 1/3Vcc
The BLDC drivers may depend on air flow for cooling and Pd is dumped on these devices in stall mode while they are buried inside fan so you cannot sense Tjcn so my values above are based on this. This may be only a problem if RdsOn or Rce of drivers is not much less <10% of coil DCR . Designers should remember this ratio in future BLDC design of drivers. Thus if so, the coil absorbs the power and with no air flow may be safe.
Since fan load increases with RPM and DC motors draw less current with RPM the motor current is somewhat constant or slightly linear with RPM above stall speed.
Variations depend on Fan design.
Without detailed fan specs this accurately describes the heat and thus reliability risk with fans at stall threshold on starting.


text:
Q: Multi-column index order in Rails I understand why the index order matters in Rails (from answers like these), for example, if I have:
add_index :admin_users_pages, ["user_id", "page_id"]

So I'm supposed to put the field that "narrows down the number of rows" fastest, but I'm not sure what does that mean. Say I have 2 users, with 2 unique IDs, and 300 pages, with 300 unique IDs, which one would be a smarter choice to put first? Say I have 150 pages for the first user and 150 pages for the second user, would the index look something like:
user_id page_id
1       1
1       2
1       3

or the page_id won't be sorted at all, only the index so I should get something like:
user_id page_id
1       143
1       93
1       31

A: If for a given user you want to find its pages, use [:user_id, :page_id].
If for a given page you want to find its users, use [:page_id, :user_id].
If you want to do both, then create [:user_id, :page_id] and [:page_id, :user_id].
If you have a user_id and a page_id and you want to find that row (not a very likely situation, IMHO), then for a balanced tree index it doesn't matter which order you have chosen. The entries are sorted within the index for both the first and the second and subsequent columns.
In some situations it is arguable that the least selective should go first (for Oracle compressed b-tree indexes or for Oracle skip-scan access), but in general it really doesn't matter.

A: In your case the selectivity of page_id will be better, because it narrows down number of rows extremely fast (down to 2). It means that if you are given a page_id than you can take 2 records from from table and then filter them by user_id, but if you have user_id then you will take 150 records and filter them. So it is better to put 'page_id' first.


text:
Q: grid point algorithm (finding the point in grid) I am searching for an algorithm such as the closest pair of points algorithm
Instead of an arbitrary distance between all of the points, I have a grid system set up with the 4 points being the top-right, bottom-right, top-left, and bottom-left respectively. This keeps the distance between all the points constant.
say for example if I were to put an outside point on this grid, I need to find which grid square it would be in, assuming by finding the closest 4 points (giving me the end points of the grid square).
I was going to implement the algorithm for closest points, but since the points are all the same distance away from each other all the time I didn't know if this would merit a different more efficient algorithm.
I don't really need a detailed explanation of the answer, just a point in the right direction.

A: I assume this is in 2 dimensions? Very simply, you could do this -- I used a similar technique to quickly optimize spatial clustering in a large scale data mining project.
Divide your coordinate space into a fixed number of grid lines in the X and Y directions (which it seems you have already done, by equally spacing these 4 points).
When you insert a point, divide its distance (integer division) from the origin in the X and Y direction by your grid step interval. Then you're left with two coordinates that identify the nearest X/Y grid intersection. Use the remainder to establish which side of the grid intersection your point belongs in.
If you want to get really complicated you could start using kD-Trees, etc... but I think this example is simple enough not to warrant any more complicated spatial partitioning.


text:
Q: Google play store is giving extra credits to user? We are using server side validation for validating in-app subscription in play store. Google returned such a response for one of the requests -

{
kind: "androidpublisher#subscriptionPurchase",
initiationTimestampMsec: "1363062617125",
validUntilTimestampMsec: "1365762617125",
autoRenewing: true
}
Its a monthly subscription and if you convert the timestamps, validUntilTimestampMsec is 6 hours more than a month, any idea why?


text:
Q: CSV DictWriter not moving to next row and deleting previous values I have this code:
os.truncate('cookies.csv', 0)
fieldnames = ['domain', 'expiry', 'httpOnly', 'name', 'path', 'secure', 'value']

def open_csv(value):
    with open('cookies.csv', 'r+') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writerow(value)

cookie = driver.get_cookie('example cookie')  # get cookie from selenium chrome webdriver
driver.close()
open_csv(cookie)

It should write in this format, values aren't accurate just example:
'domain': google.com, 'expiry': 123456, 'httpOnly': true, 'name': cookie1, 'path':/, 'secure': true, 'value': 123abc
'domain': google.com, 'expiry': 123457, 'httpOnly': true, 'name': cookie2, 'path':/, 'secure': true, 'value': 456def

However, it only writes in the first row, so after writing cookie1 it will then write cookie2 in its place.

A: You need to open the file for appending, using the a+ file mode. See this SO answer for detailed explanation.


text:
Q: Perl, multiple match string in multiple files I would like to use
 myscript.pl targetfolder/* > result.csv

to grep some number from multiple ASCII files.
The data table is like

|   44.2 | 3123.7 |   3123 |
  +--------+--------+--------+

--> this is the end of data table is like
myscript.pl
#!/usr/bin/env perl

use warnings;
use strict;
use Data::Dumper;  # for debugging

$Data::Dumper::Useqq=1;

#####start######

Title1();
Title2();

print "\n";

#####Grep#######

foreach my $currentfile (@ARGV) {     # ARGV is the target files list
    print Dumper($currentfile);       # debug
    open my $filehanlder, '<', $currentfile or die "$currentfile: $!";

    while ($r <= $#fswf) {      #judge end of the open file
        Value1();
        Value2();
        Print1();
        Print2();
        print "\n";
        $r++;
    }                 #go next line output

    Close $filehanlder;
}

#####sub#######
sub Title1 {
    print "title1,title2";
}

sub Title2{
    print "title5,title6,title7,title8";
}

sub Value1 {
    my ($line);
    while ($line = <$filehanlder>)) {
        if ($line =~ /^\|\sMachine\:(\S+)\s+Release\:(\S+)\s+/) {
            our ($machine) = $1;our ($sw) = $2;
        }
    }
}

sub Value2 {
    my ($line);
    while ($line = <$filehanlder>)) {
        if ($line =~ /^\|\sProduction\sResult\s+\|\s(\S+)\s+\|/) {
            next if 1..4;
            my (@b) = "";
            $r = 1
            @result1 = @result2 = @result3 = @result4 = "";

            while ($line !~ /\+\-/) {
                chomp $line;
                @b = split / *\| */, $line;
                our ($result1[$r]) = $b[1];
                our ($result2[$r]) = $b[2];
                our ($result3[$r]) = $b[3];
                our ($result4[$r]) = $b[4];
                $r++;
                $line = (<$filehanlder>);
                @b = "";
            }
        }
    }
}

##I need a value as file counter, but not sure where to put it.

Sub Print1 {
    print "$machine,$sw,";   # this keeps same cross lines from same file
}

Sub Print2 {
    print "$result1[$r],$result2[$r],$result3[$r],$result4[$r],";  # change every line
}

#####sub#######

I don't know is this correct way to pass the $filehander to the subroutine and pass it throught different subroutine.
@Dave Cross: Thanks for pointing out. Exactly as you said. If I do loop in the subroutine, then one subroutine will go to the end of file, other subroutine get nothing. So shall I do while loop in the main ? Or shall I do open in every subroutines? so I can reset the filehandler to the 1st line of the file in every subroutine.   If I have multiple @result as I grep in the sub values2 , how I can print them with the max lines number of these @result.  For example, I have @result5[7] ,@result6[12], so I would like to print 12 lines record, the first 7 lines with result5 grep result, the last 5 line ,result5 column keeps empty and result6 column continue printout.

A: Your filehandle is just stored in a scalar variable ($filehanlder) so it can be passed into a subroutine in exactly the same way as any other variable.
some_subroutine($filehanlder);

And, inside the subroutine:
sub some_subroutine {
  my ($fh) = @_;

  # do something with $fh
}

But I think you have more serious problems to worry about. You have two subroutines that have a while (<$filehanlder>) loop in them. The first of those to be called, will go to the end of the file, leaving the second with no data to process.
You probably want to rethink the design of this code.


text:
Q: Calling a Java class from Adobe Air app I have to develope a simple desktop application. I have to call my Jar behind it. I am thinking that I should have Adobe Air interface that will call my Jar.
Is it possible in Air. If yes, then I am going to learn Adobe Air, otherwise I will develope it in Swing.
Thanks.

A: I appreciate this is an old question, but you don't need to use Merapi.
Native processes are supported from Air 2.0 onwards.
See the API docs for the NativeProcess object.
Also, take a look at this video, which demonstrates starting tomcat by invoking a jar.  So what Tahir Akram is asking is definitely possible now (although I don't think it was possible in 2009).

A: Air won't know what to do with the jar file.  If it was allowed Air could call java and pass it the jar (assuming java was installed), but I don't believe AIR apps have the capability to do system calls.
You're probably best off just sticking with Java, or replacing the jar with a flash library that accomplishes the same thing.  You really don't want to mix technologies if you can avoid it.

A: I am new to AIR and I was also looking how to integrate AIR and JAVA , I found this website, which may be of  help
http://merapiproject.net/
Merapi is a technology that can be used as a messaging bridge between applications that run in the Adobe Flash player or Adobe AIR and applications written in Java.

A: You certainly can call your Jar files using NativeProcess. Like Python, you will need to create frozen binaries of your jar files into an .exe file.  I think JSMooth is a Java executable wrapper that converts jar to exe.
In fact, JSmooth will look for the JVM and if it's not installed, it will redirect user to fetch the download.
The nice thing with Python, you can bundle the python program in with your .py files with the help of py2exe.


text:
Q: Resetting MySQL Root Password with XAMPP on Localhost So for the past hour I've been trying to figure out how to reset my 'root' password for MySQL as I cannot log into PHPMyAdmin. I've tried changing the password in the config.inc.php file and searching through other methods. I cannot find a successful way. A few months ago I changed it as a test password but now I forget what it was. If anyone can help, that would be great. (I'm running on a Windows computer).

A: You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"
change this line:
$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command within the Shell:
mysqladmin.exe -u root password WhateverPassword

where WhateverPassword is your new password.

A: For me much better way is to do it using terminal rather then PhpMyAdmin UI.
The answer is copied from "https://gist.github.com/susanBuck/39d1a384779f3d596afb19fcad6b598c" which I have tried and it works always, try it out..

*

*Open C:\xampp\mysql\bin\my.ini (MySQL config file)

*Find the line [mysqld] and right below it add skip-grant-tables. Example:
[mysqld]
skip-grant-tables
port= 3306
socket = "C:/xampp/mysql/mysql.sock"
basedir = "C:/xampp/mysql"
tmpdir = "C:/xampp/tmp"
[...etc...]

*This should allow you to access MySQL if you don't know your password.

*Stop and start MySQL from XAMPP to make this change take effect.

*Next, in command line, connect to MySQL:

C:\xampp\mysql\bin\mysql.exe --user=root

*

*Once in MySQL command line "select" the mysql database:

USE mysql;

*

*Then, the following command will list all your MySQL users:

SELECT * FROM user \G;

*

*You can scan through the rows to see what the root user's password is set to. There will be a few root users listed, with different hosts.

*To set root user's to have a password of your choice, run this command:

UPDATE user SET password = PASSWORD('secret_pass') WHERE user = 'root';

*

*-OR- To set all root user's to have a blank password, run this command:

UPDATE user SET password = '' WHERE user = 'root';
When you're done, run exit; to exit the MySQL command line.
Next, re-enable password checking by removing skip-grant-tables from C:\xampp\mysql\bin\my.ini.
Save changes, restart MySQL from XAMPP.

A: Reset XAMPP MySQL root password through SQL update phpmyadmin to work with it:
-Start the Apache Server and MySQL instances from the XAMPP control panel.
After the server started, open any web browser and go to http://localhost/phpmyadmin/. This will open the phpMyAdmin interface. Using this interface we can manager the MySQL server from the web browser.
-In the phpMyAdmin window, select SQL tab from the right panel. This will open the SQL tab where we can run the SQL queries.
-Now type the following query in the textarea and click Go

*

*"UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';"

*hit go

*"FLUSH PRIVILEGES;"

*hit go
-Now you will see a message saying that the query has been executed successfully.
-If you refresh the page, you will be getting a error message. This is because the phpMyAdmin configuration file is not aware of our newly set root passoword. To do this we have to modify the phpMyAdmin config file.
-Open the file C:\xampp\phpMyAdmin\config.inc.php in your favorite text editor.
Search for the string:
$cfg\['Servers'\]\[$i\]['password'] = ''; and change it to like this,
$cfg\['Servers'\]\[$i\]['password'] = 'password'; Here the 'password' is what we set to the root user using the SQL query.
$cfg['Servers'][$i]['AllowNoPassword'] = false; // set to false for password required
$cfg['Servers'][$i]['auth_type'] = 'cookie'; // web cookie auth

-Now all set to go. Save the config.inc.php file and restart the XAMPP server.
Modified from Source: https://veerasundar.com/blog/how-to-change-the-root-password-for-mysql-in-xampp/

A: If you indeed forgot the root password to the MySQL server, you need to start it with the option skip-grant-tables. Search for the appropriate Ini-File my.ini (C:\ProgramData\MySQL Server ... or something like this) and add skip-grant-tables to the section [mysqld] like so:
[mysqld]
skip-grant-tables

A: 1.-In XAMPP press button Shell
2.-place command:
mysqladmin -u root password
New password: aqui colocar password ejemplo ´09876´
3.-go on the local disk c: xampp \ phpMyAdmin
open config.inic.php with notepad ++
5.- add the password and in AllowNoPassword change to false
/* Authentication type and info */

$cfg['Servers'][$i]['auth_type'] = 'cookie';

$cfg['Servers'][$i]['user'] = 'root';

$cfg['Servers'][$i]['password'] = '09876';

$cfg['Servers'][$i]['extension'] = 'mysqli';

$cfg['Servers'][$i]['AllowNoPassword'] = false;

$cfg['Lang'] = '';

6.- save changes, clear browser cache and restart xampp

A: On xampp -> Phpmyadmin -> config.inc 21st line you see:
$cfg['Servers'][$i]['password'] = '';

Add your password here and restart your xampp.
The password will change.

A: *

*Start the Apache Server and MySQL instances from the XAMPP control panel.

*Now goto to your localhost.

*Click on user accounts -> Click on Edit privileges -> You will find an option change password just change password as you want click on go. Image are given below

*If you refresh the page, you will be getting a error message. This is because the phpMyAdmin configuration file is not aware of our newly set root passoword. To do this we have to modify the phpMyAdmin config file.

*Open terminal window (not mac default terminal please check attached image)

*Then Run apt-get update in the newly opened terminal.

*Then run apt-get install nano this will install nano

*CD to cd ../opt/lampp/phpmyadmin

*Open and Edit nano config.inc.php and save.

A: Steps:

*

*Open your phpMyadmin dashboard

*go to user accounts

*on the user section Get the root user and click [ Edit privileges ]

*in the top section you will find change password button [ click on it ]

*make a good pass and fill 2 pass field .

*now hit the Go button.

7 . now open your xampp dir ( c:/xampp ) -->
8 .   to phpMyadmin dir  [C:\xampp\phpMyAdmin]

*open  [ config.inc.php ] file with any text editor

10 .find [ $cfg['Servers'][$i]['auth_type'] = 'config'; ]line and replace 'config' to 'cookie'

*go to [ $cfg['Servers'][$i]['AllowNoPassword'] = true; ] this line change 'true' to 'false'.

last : save the file .
here is a video link in case you want to see it in Action [ click Here ]

A: Try this:sudo /Applications/XAMPP/xamppfiles/xampp security
Then follow the instructions

A: Open the file C:\xampp\phpMyAdmin\config.inc.php in your text editor. Search for the tags below and edit accordingly
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'password';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

Where 'password' is your new password. In-between quotes.
GO to your browser and visit link http://localhost/phpmyadmin/. Click on 'GO' without your new password. It would log you in and you would be able to see the "CHANGE PASSWORD". Proceed to change your password and you are done.

A: You can configure it with the "XAMPP Shell" (command prompt).
Open the shell and execute this command:
mysqladmin.exe -u root password secret

A: Follow the following steps:

*

*Open the XAMPP control panel and click on the shell and open the shell.

*In the shell run  the following :
mysql -h localhost -u root -p
and press enter. It will as for a password, by default the password is blank so just
press enter

*Then just run the following query
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpassword');
and press enter and your password is updated for root user on localhost

A: 2020 Sep

*

*launch xamp control panel

*press admin in mysql row

*in opened phpmyadmin press house icon on top left corner

*in the top middle you will see user accounts tab and tap it

*see in 'new' panel under the table to add a   new user for your dbs
and set access permissions

A: On Dashboard,
Go to User Accounts,
Select user,
Click Change Password,
Fill the New Password,
Go.

A: Here, I tried to follow the instruction [1], and I couldn't do that somehow. Then I tired following steps and it worked!
Resetting MySQL password

*

*Stop the MySQL server.

*Open C:\<xampp_installed_directory>\mysql\bin\my.ini file and add the following under [mysqld]
 -----
 [mysql]
 skip-grant-tables
 port= 3306
 socket = "C:/xampp/mysql/mysql.sock"
 -----

*Start the MySQL Server

Resetting the root password
Here, I couldn't use the default command (mysqladmin) suggested in previous steps. Then I followed following steps.

*

*cd into mysql bin directory inside the XAMPP directory.
 > cd C:\<xampp_installed_directory>\mysql\bin\

*Run the following command in order to log into MySQL server via the command line without the password,
 > mysql

*Run the following commands in order to reset the password [2],
 > USE mysql
 > FLUSH PRIVILEGES;
 > ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
 > exit

*Verify the credentials by running the following command and enter the password you set in previous step.
 > mysql -u root -p

If you can see the MySQL prompt. Then you're good to go!

Resetting the changes

*

*After that, remove the line you added to MySQL config file at C:\<xampp_installed_directory>\mysql\bin\my.ini

*Restart the server (Stop the server and Start the server) to affect the changes.

Change the auto login feature to login using credentials
Seems like by default phpMyAdmin has enabled the auto login [3]. Disabled that feature as following,

*

*Edit the phpMyAdmin config file at C:\<xampp_installed_directory>\phpMyAdmin and find the auth_type config and change it as following (you can refer to the steps mentioned in [3] as well)
 $cfg['Servers'][$i]['auth_type'] = 'cookie';

*Restart the Apache server (Stop the server and Start the server) to affect the changes.

References:

*

*[1]. https://dev.mysql.com/doc/mysql-windows-excerpt/5.7/en/resetting-permissions-windows.html

*[2]. https://dev.mysql.com/doc/refman/8.0/en/resetting-permissions.html

*[3]. set login enable for phpmyadmin

A: SIMPLE STRAIGHT FORWARD WORKING SOLUTION AND OUT OF THE BOX:
1 - Start the Apache Server and MySQL instances from the XAMPP control panel.
2 - After the server started, open any web browser and give http://localhost/phpmyadmin/. This will open the phpMyAdmin interface. Using this interface we can manage the MySQL server from the web browser.
3 - In the phpMyAdmin window, select SQL tab from the top panel. This will open the SQL tab where we can run the SQL queries.
4 - Now type the following query in the text area and click Go

UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
  FLUSH PRIVILEGES;

5 - Now you will see a message saying some thing like: the query has been executed successfully.
6 - If you refresh the page, you will be getting a error message. This is because the phpMyAdmin configuration file is not aware of our newly set root passoword. To do this we have to modify the phpMyAdmin config file.
7 - Open the file [XAMPP Installation Path]/phpmyadmin/config.inc.php in your favorite text editor (e.g: C:\xampp\phpMyAdmin\config.inc.php).
8 - Search for the string

$cfg['Servers'][$i]['password'] = '';

and change it to like this,

$cfg['Servers'][$i]['password'] = 'password';

Here the 'password' is what we set to the root user using the SQL query.
9 - Now all set to go. Save the config.inc.php file and restart the XAMPP apache and mysql servers. It should work!
Source: https://veerasundar.com/blog/2009/01/how-to-change-the-root-password-for-mysql-in-xampp/
DONE!


text:
Q: jQuery plugin for datatables I am working on a datatable which is not very big and I need to implement the following UI

*

*Draggable Columns

*Resizable Columns

*UI has to have memory across sessions.

I have gone through the list of jQuery plugins for datatables and I am not really satisfied with what I was getting.
Things like flexigrid and others with YUI or EXTJS are obviously an overkill for this.
There are simple solutions for making draggable columns but none of them has all the features that I want.
Does anybody know of a plugin that might help?
TIA

A: jQgrid will do the trick very well.


text:
Q: How is spatial search implemented at the code level in solar or elasticsearch Since lucene is developed purely in java , can i find out how spatial is implemented by solar or elasticsearch since they are using lucene

A: While this is a very broad question, a good place to start is the github repo for Lucene and Solr. Searching for Solr Spatial will give you the code for Solr's interface to the Lucene Spatial functionality, and gives you the names of classes (and by looking at the imports, what the important parts in the Lucene code base is).
After digging through a bit of code, looking at AbstractSpatialFieldType for fields defined as spatial field types in Solr seems to be a good place to dig further into the Solr implementation.
In addition I can recommend looking up the spatial talks from the previous years of Lucene Solr Revolution, where you should be able to find down-to-the-metal-talks about the implementation (and the evolution it has been through the last years). David Smiley has been heading the implementation from the Solr side (which also includes a lot of the Lucene side as far as I understand).


text:
Q: Is it possible for a Telegram Bot to send any type of message without users trigger? So I need my Telegram bot to ask a question from user (send any message of any possible type) without any initiation from a user. Is it possible? I cant find anything about this.

A: If the user interacted with your bot before you just need to use their user_id and send your message. You can't however send message to a user who has never interacted with your bot.

A: Telegram BOT never can take an action before user interact with bot. because most of available method need "chat_id". if you dont have "chat_id", you can only run simple method like getMe, getUpdates,etc.


text:
Q: replace value in an numpy ndarrary suppose I have an n dimensions numpy array as below, is there a way I can change all 255 in the last element of the nested arrary to 0? thanks
[
[1,2,3,255],
[1,2,3,234],
[1,2,3,255],
]

A: >>> a = np.array([[1,255,3,255], [1,2,3,234], [1,2,3,255],])
>>> a
array([[  1, 255,   3, 255],
       [  1,   2,   3, 234],
       [  1,   2,   3, 255]])

>>> a[a[:,-1] == 255, -1] = 0  # <---
>>> a
array([[  1, 255,   3,   0],
       [  1,   2,   3, 234],
       [  1,   2,   3,   0]])

A: Create a view that contains values in the last columns, than change the values by boolean array:
import numpy as np
a = np.array([[255,2,3,255], [1,2,3,234], [1,2,3,255]])
b = a[:, -1]
b[b==255] = 0
print a

result:
array([[255,   2,   3,   0],
       [  1,   2,   3, 234],
       [  1,   2,   3,   0]])


text:
Q: Relativity Proof with Defining interval I have started reading Landau & Lifshitz Vol. 2 (fields theory) and I've got confused about something I read.
to prove the Lorentz transform, it defines interval:
$$ds^{2} = c^{2} dt^{2} - dr^{2}\tag{2.4}$$
for a pulse that moves the length $dr$ in $dt$ in our coordinates (and its velocity can be different from light).
Also $c$ is the maximum velocity of propagation in the space, and it defines it for two coordinates $K$ & $K'$ and says if $ds = 0$, then $ds' = 0$ too. So $$ds = a ~ ds'.$$
here it says $a$ is only a function of properties of these two coordinates and it doesn't relate to the pulse properties (f.e $dr$,$dr'$,$dt$, or $dt'$) And I couldn't find a reason for it. Would anyone say why $a$ can't depend on these parameters?


text:
Q: Trying to sign up in AWS cognito using a nodejs server usign JSON POST request Trying to sign up into AWS Cognito using email as username attribute Getting an error message : "User email should be empty or same as username, since username attribute is email."
Tried making it blank as well adding a same username attribute in JSON no fix yet.
defaults: async (Username) => {
        const definitions = {
            Pool: new AmazonCognitoIdentity.CognitoUserPool({
                UserPoolId: 'xxxxxxxxxxxxxxxx',
                ClientId: 'xxxxxxxxxxxxxxxx',
            })
        };
        if (Username) {
            definitions.cognitoUser = new AmazonCognitoIdentity.CognitoUser({ Username, Pool: definitions.Pool });
        }
        return definitions;
    }
const formData = req.body;
        const mail = formData.email;
        const { Pool } = await module.exports.defaults();
        const attributeList = [];
        const general = ['email', 'phone_number', 'name'];
        const custom = ['company_name', 'country', 'last_name', 'city', 'role'];
        const must = ['picture', 'profile', 'locale', 'birthdate', 'address'];
        general.map(g => {
            attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({
                Name: g,
                Value: formData[g].toUpperCase()
            }));
        });
        must.map(m => {
            attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({
                Name: m,
                Value: ''
            }));
        });
        custom.map(c => {
            attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({
                Name: `custom:${c}`,
                Value: formData[c].toUpperCase()
            }));
        });
        if (validEmail.email(mail)) {
            Pool.signUp(formData.email, formData.password, attributeList, null, (err, result) => {
                if (err) {
                    res.status(500).send({ message: err.message });
                    return;
                }
                cognitoUser = result.user;
                res.send({ message: cognitoUser.getUsername() + " " + "successfully registered" });
            });
        }

    },

format of the JSON im sending in POST
{
    "name": "ashish",
    "email": "ashishkumar.senapati@gmail.com",
    "phone_number": "+918249167823",
    "company_name": "Microsoft",
    "country": "INDIA",
    "last_name": "kumar",
    "city": "BANGALORE",
    "role": "COUNTRY EXECUTIVE",
    "password": "Ashish@123"
}

A: while setting up cognito user pool, you get the option to set your username attribute. check that if its set to email id.


text:
Q: get all text variations from string in javascript How can I get in javascript all variations of string with structure like:
"{Here|This|This Really} is {example|Instance |Illustration }"

example:
Here is example

Here is Instance

This is example

...

A: Use split('|') for both of the options and loop through them to get all the combinations:

var option1 = "Here|This|This Really";
var option2 = "example|Instance |Illustration";
var combination = [];
option1.split('|').forEach((str1) => {
  option2.split('|').forEach((str2) => {
     combination.push(str1 + ' is ' +str2);
  });
});

console.log(combination);

A: Modern Javascript:

const s = "{Here|This|This Really} is {example|Instance |Illustration }"
const [a, b, c] = s.match(/\{(.+)\}(.+)\{(.+)\}/).slice(1),
    combine = [].concat(...a.split('|').map(d => [...c.split('|').map(e => `${d}${b}${e}`)]));
console.log(combine);


text:
Q: Reading certificate in certificate store using PHP How can I read a secure certificate in windows certificate store from PHP (running IIS)
I know how to read it from a certificate file, but I am trying to read it directly from the certificate store.
is this able to be done?

A: This is not directly supported by PHP. You may be able to utilize one of the Win32 PECL extensions to call the required functions in Windows.
If these don't support what you need, you may have to write your own extension.


text:
Q: How can I pass cascading parameters from ASP.NET to SSRS I am trying to build web application (ASP.NET) that will be used to display an SSRS report.
My report has 4 cascading parameters - A,B,C and D. C and D "depend" logically on the value of A (this means that the DataSets of C and D are filtered based on the value of A). Programatically (in SSRS) B depends on A, C depends on B and D depends on C.
I am trying to set them in advance the following way:
ReportParameter rp0 = new ReportParameter("Project", "P1");
ReportParameter rp1 = new ReportParameter("TopX", "Top5");
ReportParameter rp2 = new ReportParameter("Companies", "Company1");
MyReportViewer.ShowParameterPrompts = false;
MyReportViewer.ServerReport.SetParameters(new ReportParameter[] {rp0, rp1, rp2});
MyReportViewer.ServerReport.Refresh();

When I do that I get a mistake that TopX parameter has no value. This is the second parameter - it has a default value (="Top1").
Could anybody assist? Is there any way to dynamically query the SSRS report for the values available for each parameter and then select a value?

A: The correct way to do this was to set the parameters one by one.
I created the following method:
public void setSingleValueParameter(String name, String value) {
    ParameterValue[] parameter = new ParameterValue[1];
    parameter[0] = new ParameterValue();
    parameter[0].setName(name);
    parameter[0].setValue(value);
    service.setExecutionParameters(parameter,"en-us");
}

And then I call the method for each parameter in the order they appear in the SSRS report


text:
Q: Python convert string to object I am using pandas/sql alchemy to write a table to an sql database.
Here is some sample code below:
df.to_sql('table', connection, schema=None, dtype={
    'id': sa.types.VARCHAR(length=100),
    'value1': sa.types.Float(),
    'value2': sa.types.Float()})

I have a csv file where the data type for each column is defined, I would like to be able to read the csv file using pandas and then convert the table to a dictionary which would be passed to the to_sql() method.
If I were to do that directly, the data type, for example sa.types.VARCHAR(length=100) would appear as a string. How can I convert this string so that it can be passed as an appropriate data type.
To clarify if i read the data from a csv table, the dtype dictionary will look like this:
{'id': 'sa.types.VARCHAR(length=100)'}

instead of the current:
{'id': sa.types.VARCHAR(length=100)}

A: This solution is hacky and I have to believe there's a better way if we had all of the information, but short of that, here goes.
I would create a dictionary similar to:
type_dict = {
   'VARCHAR' : sa.types.VARCHAR,
   'Float'   : sa.types.Float,
   ... }

Then, break up that string to get the main info you're looking for (I'm sure there's a better regex way to do this, but it's past my bedtime):
dtype = string.split('(')[0].split('.')[-1]
var   = string.split('(')[1].split('=').split(')')[0]

Then:
sql_dict = { 'id' : type_dict[dtype](var) }


text:
Q: Collapsable block for custom language in notepad++ I'm trying to create a custom highlighter for notepad++. I know how to do most of it, but I cant figure out how to set up code blocks like loops so that they can be collapsed. Is this possible?
Edit: Looking into it further, I think it might be folder open/close. Is this correct?

A: Correct. In User-Defined window, go to tab Folder&Default and you have three sections there like:

*

*Open is the beginning of the collapsible section.

*Middle is useful for cases like IF - ELSE - ENDIF.

*Close is closing of the collapsible section.
One of three sections is for comments, other two are for your priamry language structures.


text:
Q: IEnumerable EntityFramework Collection Confusion I have a bit of a strange issue with two bits of code that I thought should do the same thing. Could anyone shed any light on why this code takes ages to execute:
IEnumerable<Account> acc_list = null;
acc_list = dbContext.Accounts;
acc_list = acc_list.Where(a => !a.Transactions.Any(t => t.isClosureTransaction));
int count = acc_list.Count();

While this code is instant:
IEnumerable<Account> acc_list = null;
acc_list = dbContext.Accounts.Where(a => !a.Transactions.Any(t => t.isClosureTransaction));
int count = acc_list.Count();

After some investigation using the sql profiler the second piece of code is executed in one sql, while the first one executes multiple queries for every transaction on every account.

A: IQueryable always uses deferred execution because it deals in expression trees. When you assign your DbSet to an IEnumerable it enumerates the full set which means you'll enumerate each account and will do the same when you filter and then count.
The second code sample filters the set first (you access it via the property which is an IDbSet which extends IQueryable) and so when you perform the count you are only doing it on the filtered result set.
You'll probably get better performance again by doing the following:
dbContext.Accounts.Count(a => !a.Transactions.Any(t => t.isClosureTransaction));

This will execute a count in the DB directly.
This blog post does a good job of explaining things.


text:
Q: How to access nested document objects in the same DOM console? I'm trying to access the contents contained in a nested document which is deep inside the html. I've just located the selector using document.getElementsByClassName('top')

However I noticed it is recieving a nested document from the src url.

I need to some how query the document in the same console, for a couple reasons. Firstly because the url version of the document doesn't actually contain all the contents of the document, and secondly because I haven't be able to communicate between two separate page consoles.
Here are the inner contents of the document, standard header and body tags.

I also tried to access the document like so with no luck (not too surprised)
document.getElementsByClassName('top').querySelector('#document')

The only option I found was to enter the document by returning the url
document.getElementsByClassName('top').src

And opening in a new tab. But of course I can't proceed further with this method.

A: You can access the information in an iframe by accessing the contentWindow property:
// reference to iframe with id 'ifrm'
var ifrm = document.getElementById('ifrm');
// using reference to iframe (ifrm) obtained above
var win = ifrm.contentWindow; // reference to iframe's window
// reference to document in iframe
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
// reference to form named 'demoForm' in iframe
var form = doc.getElementById('demoForm');

Taken from here.
But this is only if you have permitted access to the URL specified in src. Otherwise, it's a huge security risk.


text:
Q: Getting issue in NSNotificationCenter NSNotificationCenter selector method is never called.
PostNotification is follow:
- (IBAction)go:(id)sender {
AnotherViewController *obj = [self.storyboard instantiateViewControllerWithIdentifier:@"AnotherViewController"];

[[NSNotificationCenter defaultCenter]
 postNotificationName:@"TestNotification"
 object:self];

[self.navigationController pushViewController:obj animated:YES];

}

Observe Notification in AnotherViewController.m:
  - (void)viewDidLoad {
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(receiveTestNotification:)
                                             name:@"TestNotification"
                                           object:nil];

// Do any additional setup after loading the view.
  }

and receiveTestNotification is :
- (void) receiveTestNotification:(NSNotification *) notification
{

if ([[notification name] isEqualToString:@"TestNotification"])
    NSLog (@"Successfully received the test notification!");
 }

What is the problem? Thanks

A: You should move the add observer method to initialisation of the view controller. Because you are posting the notification before the AnotherViewController registers itself to receive the notification.
   - (instancetype)initWithCoder:(NSCoder *)aDecoder
    {
        self = [super initWithCoder:aDecoder];
        if (self) {
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(receiveTestNotification:)
                                                         name:@"TestNotification"
                                                       object:nil];
        }
        return self;
    }


text:
Q: Remove admin bar for subscribers I have a membership site. I need to disable the admin bar for the subscribers.
I have used this code below:
add_action('after_setup_theme', 'remove_admin_bar');

function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
  show_admin_bar(false);
}
}

which removes the admin bar from the frontend for the subscriber, but when they go to their profile page wp-admin/profile.php, the admin bar is still showing there.
I am using Paid Membership Pro plugin which I think made the code not working on the backend for subscribers.
Also, I have used this code to remove the admin bar from everywhere:
if (!function_exists('disableAdminBar')) {

    function disableAdminBar(){

    remove_action( 'admin_footer', 'wp_admin_bar_render', 1000 );

    function remove_admin_bar_style_backend() {
      echo '<style>body.admin-bar #wpcontent, body.admin-bar #adminmenu { padding-top: 0px !important; }</style>';
    }

    add_filter('admin_head','remove_admin_bar_style_backend');

  }

}

add_filter('admin_head','remove_admin_bar_style_backend');

But this code is also not working.
I just want to remove the admin bar for the subscribers from both the frontend and backend pages.
Is there any specific code I am missing? I am using Paid membership Pro.
Thank you for helping.

A: To hide admin bar from non admin users, add the following code to you functions.php file
// show admin bar only for admins
if (!current_user_can('manage_options')) {
    add_filter('show_admin_bar', '__return_false');
}
// show admin bar only for admins and editors
if (!current_user_can('edit_posts')) {
    add_filter('show_admin_bar', '__return_false');
}

A: The PMPro team made a plugin to do this:
https://wordpress.org/plugins/hide-admin-bar-from-non-admins/
The includes the PHP and CSS code needed to fully hide the admin bar:
https://plugins.svn.wordpress.org/hide-admin-bar-from-non-admins/trunk/hide-admin-bar-from-non-admins.php
function habfna_hide_admin_bar_settings()
{
?>
    <style type="text/css">
        .show-admin-bar {
            display: none;
        }
    </style>
<?php
}
function habfna_disable_admin_bar()
{
    if(!current_user_can('administrator'))
    {
        add_filter( 'show_admin_bar', '__return_false' );
        add_action( 'admin_print_scripts-profile.php', 'habfna_hide_admin_bar_settings' );
    }
}
add_action('init', 'habfna_disable_admin_bar', 9);

A: I had to do the same but keep the bar for editors & admins but remove for others roles. I did it like that :
in functions.php
function check_user_role($roles, $user_id = null) {
    if ($user_id) $user = get_userdata($user_id);
    else $user = wp_get_current_user();
    if (empty($user)) return false;

    foreach ($user->roles as $role) {
        if (in_array($role, $roles)) {
            return true;
        }
    }
    return false;
}

also in functions.php
// show admin bar only for admins and editors
if (!check_user_role(array('administrator','editor'))) {
  add_filter('show_admin_bar', '__return_false');
}

A: show_admin_bar(false) doesn't work on backend pages. You'll have to remove the admin bar hooks if you want to remove them from the backend.
function remove_admin_bar_hooks() {

    // Removes the hooks that render the admin bar.
    remove_action('template_redirect','_wp_admin_bar_init', 0);
    remove_action('admin_init','_wp_admin_bar_init');
    remove_action('before_signup_header','_wp_admin_bar_init');
    remove_action('activate_header','_wp_admin_bar_init');
    remove_action('wp_body_open','wp_admin_bar_render',0);
    remove_action('wp_footer','wp_admin_bar_render',1000);
    remove_action('in_admin_header', 'wp_admin_bar_render', 0);

    // Removes the admin bar class from the body tag.
    add_filter('body_class',function($wp_classes, $extra_classes) {
        // Deletes the admin-bar class from the arrays if present.
        return array_diff(
            array_merge( $wp_classes, (array) $extra_classes ),
            array('admin-bar')
        );
    },10000,2);
}

You can refer to this article for more information: https://blog.terresquall.com/2021/09/remove-the-admin-bar-on-the-wordpress-admin-backend/

A: // Disable admin topbar for all roles except admins:
add_action('after_setup_theme', 'remove_admin_bar');

function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
    show_admin_bar(false);
}

}

A: I did a quick research on this and I don't think you can with a function, as said in the codex.

Note: It is no longer possible to hide the Toolbar when viewing the Administration Screens, but users can disable it on the front-end of the site in their Profile screen.

Disabling in the frontend results in the same as you've already done.
I would suggest hiding it with css.
#wpadminbar {
    display: none;
}
html {
    padding-top: 0; // Move up the page's content by the bar's height
}


text:
Q: Does the distance between the slits, in the double slit experiment, affect the pattern displayed? Does the distance between the slits affect the pattern displayed?
I want a pattern where light parts and dark parts are equal, and I don't want the light parts to be bigger than dark parts.

A: The distance between the fringes is inversely proportional to the separation of the slits.

I want a pattern where light parts and dark parts are equal, and I don't want the light parts to be bigger than dark parts.

Unfortunately, one cannot always get what one wants.
The fringes from a two slit arrangement are not sharp and so such a diagram may be misleading.

The theoretical intensity pattern depends on the separation of the slits and the width of the slits as shown in the diagram below.

Photographing the interference pattern is very difficult due to the range of light intensities involved.
The photographs above have been overexposed in the centre region (high intensity) so that the outer regions (low intensity) are visible.


text:
Q: Revert local Sourcetree repo to master I'm new to Sourcetree and have created a mess locally, with 7 ahead commits compared to the origin/master.  I want to ignore and remove everything I've done locally and start again by reverting my local repo to the origin/master as it currently stands.  How do I do this?
Remark:  I know the origin/master is correct since I have another machine next to me which I don't use to do commits and just did a pull from the origin/master, and the local repo is correct on this other machine.

A: You can set your current master to match the origin master by:
Check out the master branch. Double click the branch, or open the terminal and type git checkout master
Then reset the branch to origin master. Locate origin/master in the log, right click, click "Reset current branch to this commit" and select hard from the dialog that comes up. Or use the command git reset --hard origin/master


text:
Q: Usage of Simple Present between speakers Is the use of "Do" in the begining of interrogative sentence necessary? I means, casual conversation.

Does he play tennis?
He plays tennis?

A: He plays tennis? does not involve merely deleting the supporting do at the head of the sentence—that would yield

He play tennis?

without the 3d-person singular present inflection -s on play. That would be an example of conversational-deletion. This is comparatively rare with 3d-person questions like this, but it might arise in contexts like these:

A: I can't find anybody to partner with for the tournament.
B: Hmm. What about Brian? He play tennis?
A: This new guy's quite an athlete: played football at Tech.
B: He play tennis?

Your sentence is something quite different, an echoic question. This has the syntactic structure of an ordinary declarative He plays tennis, spoken with a rising intonation at the end—that's what the ? signifies. Such questions demand confirmation of what has just been spoken:

A: I see Brian's entered the company tennis tournament.
B: He plays tennis? I thought he had a bum knee.