Search Results

Search found 2030 results on 82 pages for 'params'.

Page 11/82 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • PowerShell Script To Find Where SharePoint 2010 Features Are Activated

    - by Brian Jackett
    The script on this post will find where features are activated within your SharePoint 2010 farm.   Problem    Over the past few months I’ve gotten literally dozens of emails, blog comments, or personal requests from people asking “how do I find where a SharePoint feature has been activated?”  I wrote a script to find which features are installed on your farm almost 3 years ago.  There is also the Get-SPFeature PowerShell commandlet in SharePoint 2010.  The problem is that these only tell you if a feature is installed not where they have been activated.  This is especially important to know if you have multiple web applications, site collections, and /or sites.   Solution    The default call (no parameters) for Get-SPFeature will return all features in the farm.  Many of the parameter sets accept filters for specific scopes such as web application, site collection, and site.  If those are supplied then only the enabled / activated features are returned for that filtered scope.  Taking the concept of recursively traversing a SharePoint farm and merging that with calls to Get-SPFeature at all levels of the farm you can find out what features are activated at that level.  Store the results into a variable and you end up with all features that are activated at every level.    Below is the script I came up with (slight edits for posting on blog).  With no parameters the function lists all features activated at all scopes.  If you provide an Identity parameter you will find where a specific feature is activated.  Note that the display name for a feature you see in the SharePoint UI rarely matches the “internal” display name.  I would recommend using the feature id instead.  You can download a full copy of the script by clicking on the link below.    Note: This script is not optimized for medium to large farms.  In my testing it took 1-3 minutes to recurse through my demo environment.  This script is provided as-is with no warranty.  Run this in a smaller dev / test environment first.   001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 function Get-SPFeatureActivated { # see full script for help info, removed for formatting [CmdletBinding()] param(   [Parameter(position = 1, valueFromPipeline=$true)]   [Microsoft.SharePoint.PowerShell.SPFeatureDefinitionPipeBind]   $Identity )#end param   Begin   {     # declare empty array to hold results. Will add custom member `     # for Url to show where activated at on objects returned from Get-SPFeature.     $results = @()         $params = @{}   }   Process   {     if([string]::IsNullOrEmpty($Identity) -eq $false)     {       $params = @{Identity = $Identity             ErrorAction = "SilentlyContinue"       }     }       # check farm features     $results += (Get-SPFeature -Farm -Limit All @params |              % {Add-Member -InputObject $_ -MemberType noteproperty `                 -Name Url -Value ([string]::Empty) -PassThru} |              Select-Object -Property Scope, DisplayName, Id, Url)     # check web application features     foreach($webApp in (Get-SPWebApplication))     {       $results += (Get-SPFeature -WebApplication $webApp -Limit All @params |                % {Add-Member -InputObject $_ -MemberType noteproperty `                   -Name Url -Value $webApp.Url -PassThru} |                Select-Object -Property Scope, DisplayName, Id, Url)       # check site collection features in current web app       foreach($site in ($webApp.Sites))       {         $results += (Get-SPFeature -Site $site -Limit All @params |                  % {Add-Member -InputObject $_ -MemberType noteproperty `                     -Name Url -Value $site.Url -PassThru} |                  Select-Object -Property Scope, DisplayName, Id, Url)                          $site.Dispose()         # check site features in current site collection         foreach($web in ($site.AllWebs))         {           $results += (Get-SPFeature -Web $web -Limit All @params |                    % {Add-Member -InputObject $_ -MemberType noteproperty `                       -Name Url -Value $web.Url -PassThru} |                    Select-Object -Property Scope, DisplayName, Id, Url)           $web.Dispose()         }       }     }   }   End   {     $results   } } #end Get-SPFeatureActivated   Snippet of output from Get-SPFeatureActivated   Conclusion    This script has been requested for a long time and I’m glad to finally getting a working “clean” version.  If you find any bugs or issues with the script please let me know.  I’ll be posting this to the TechNet Script Center after some internal review.  Enjoy the script and I hope it helps with your admin / developer needs.         -Frog Out

    Read the article

  • why my code still cannot connect with database? [closed]

    - by Wen Teng
    package com.mems.travis; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; public class UserRegister extends Activity { JSONParser jsonParser = new JSONParser(); EditText inputName; EditText inputUsername; EditText inputEmail; EditText inputPassword; RadioButton button1; RadioButton button2; Button button3; int success = 0; // url to create new product private static String url_register_user = "http://192.168.1.100/MEMS/add_user.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_register); // Edit Text inputName = (EditText) findViewById(R.id.nameTextBox); inputUsername = (EditText) findViewById(R.id.usernameTextBox); inputEmail = (EditText) findViewById(R.id.emailTextBox); inputPassword = (EditText) findViewById(R.id.pwTextBox); // Create button //RadioButton button1 = (RadioButton) findViewById(R.id.studButton); // RadioButton button2 = (RadioButton) findViewById(R.id.shopownerButton); Button button3 = (Button) findViewById(R.id.regSubmitButton); // button click event button3.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String name = inputName.getText().toString(); String username = inputUsername.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); if (name.contentEquals("")||username.contentEquals("")||email.contentEquals("")||password.contentEquals("")) { AlertDialog.Builder builder = new AlertDialog.Builder(UserRegister.this); // 2. Chain together various setter methods to set the dialog characteristics builder.setMessage(R.string.nullAlert) .setTitle(R.string.alertTitle); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button } }); // 3. Get the AlertDialog from create() AlertDialog dialog = builder.show(); } else { new RegisterNewUser().execute(); } } }); } class RegisterNewUser extends AsyncTask<String, String, String>{ protected String doInBackground(String... args) { String name = inputName.getText().toString(); String username = inputUsername.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); // getting JSON Object // Note that create product url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_register_user, "GET", params); // check log cat for response Log.d("Send Notification", json.toString()); try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully created product Intent i = new Intent(getApplicationContext(), StudentLogin.class); startActivity(i); finish(); } else { // failed to register } } catch (Exception e) { e.printStackTrace(); } return null; } } }

    Read the article

  • java client program to send digest authentication request using HttpClient API

    - by Rajesh
    I have restlet sample client program which sends the digest request. Similar to this I need java client program which sends a digest request using HttpClient api. Can anybody send me sample code. Thanks in advance. Reference reference = new Reference("http://localhost:8092/authenticate"); Client client = new Client(Protocol.HTTP); Request request = new Request(Method.GET, reference); Response response = client.handle(request); System.out.println("response: "+response.getStatus()); Form form = new Form(); form.add("username", "rajesh"); form.add("uri", reference.getPath()); // Loop over the challengeRequest objects sent by the server. for (ChallengeRequest challengeRequest : response .getChallengeRequests()) { // Get the data from the server's response. if (ChallengeScheme.HTTP_DIGEST .equals(challengeRequest.getScheme())) { Series<Parameter> params = challengeRequest.getParameters(); form.add(params.getFirst("nonce")); form.add(params.getFirst("realm")); form.add(params.getFirst("domain")); form.add(params.getFirst("algorithm")); form.add(params.getFirst("qop")); } } // Compute the required data String a1 = Engine.getInstance().toMd5( "rajesh" + ":" + form.getFirstValue("realm") + ":" + "rajesh"); String a2 = Engine.getInstance().toMd5( request.getMethod() + ":" + form.getFirstValue("uri")); form.add("response", Engine.getInstance().toMd5( a1 + ":" + form.getFirstValue("nonce") + ":" + a2)); ChallengeResponse challengeResponse = new ChallengeResponse( ChallengeScheme.HTTP_DIGEST, "", ""); challengeResponse.setCredentialComponents(form); // Send the completed request request.setChallengeResponse(challengeResponse); response = client.handle(request); // Should be 200. System.out.println(response.getStatus());

    Read the article

  • how to show a large jpg image to the right in jqGrid's edit form ?

    - by cLee
    Is it possible to show a large (i.e. bigger than a thumbnail) jpeg image in the right-hand side of jqGrid's edit form ? Users want to look at a photo while entering data into fields ... they are describing things in the photo. I'm sure all things are possible with jQuery, but I don't know where to begin. thanks ... html: function afterSubmit(r, data, action) { // if session timeout returned: if (r.responseText == "logout") { window.location = '../scripts/logout.php'; } // if an error message is returned: if (r.responseText != "") { $('#submit_errors').html('Alert:'+r.responseText+''); // show div with error message $('#submit_errors').slideDown(); // hide error div after 10 seconds window.setTimeout(function() { $('#submit_errors').slideUp(); }, 10000); return false; // don't remove this! } return true; // don't remove this! } var lastsel; jQuery(document).ready(function(){ var mygrid = jQuery("#mobile_incidents").jqGrid({ url:'list.php?q=e', editurl:'edit.php', datatype: "json", // note: all column names are required even though some columns are hidden colNames:['Rec#','Date','Line','Photo'], colModel:[{ name:'id', index:'id', editable:true, editoptions: {readonly:'readonly'} }, { name:'mobile_discoveryDate', index:'mobile_discoveryDate', sortable:false, editable:true, edittype:'text', formatter:'date', formatoptions:{ srcformat:'Y/m/d', newformat:'m/d/Y' }, editoptions:{ size:12, maxlength:10, dataInit: function(element) { $(element).blur(); $(element).datepicker({dateFormat:'mm/dd/yyyy'}) } } }, { name:'mobile_lineName', index:'mobile_lineName', editable:true, sortable:false}, { name:'mobile_photo_name', index:'mobile_photo_name', editable:false, sortable:false} ], pager: '#mobile_incidents_pager', altRows: false, rowNum:10, rowList:[10,20], imgpath: '../include/images/jqgrid', viewrecords: true, emptyrecords:'No submissions found!', height: 260, sortname: 'id', sortorder: 'desc', gridview: true, scrollrows: true, autowidth: true, rownumbers: false, multiselect: false, subGrid:false, caption: '' }) .navGrid('#mobile_incidents_pager', // params: {add:false, edit:true, del:false, search:false, view:false, refresh:true, alertcap:' to edit:', alerttext:' . . . click on a row to highlight' }, // edit params: {top:50, left:5, editCaption: 'Edit Submission', bSubmit: 'Approve/Save', closeAfterEdit:true, afterSubmit:function(r,data){return afterSubmit(r,data,'edit');} }, {}, // add params {}, // delete params // search params: {multipleSearch: false}, // view params: {top: 150, left: 5, caption: 'View Mobile Rail Submission'} ); });

    Read the article

  • Having trouble setting up API call using array of parameters

    - by Josh
    I am building a class to send API calls to Rapidshare and return the results of said call. Here's how I want the call to be done: $rs = new rs(); $params = array( 'sub' => 'listfiles_v1', 'type' => 'prem', 'login' => '10347455', 'password' => 'not_real_pass', 'realfolder' => '0', 'fields' => 'filename,downloads,size', ); print_r($rs->apiCall($params)); And here's the class so far: class RS { var $baseUrl = 'http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub='; function apiCall($params) { $newUrl = $baseUrl; $keys = array_keys($params); $count = count($params); for($i = 0; $i < $count; $i++) { $newUrl .= $keys[$i]; $newUrl .= '&'; $newUrl .= $params[$keys[$i]]; } return $newUrl; } } Obviously i'm returning $newUrl and using print_r() to test the query string, and this is what it comes out as with the code shown above: sub&listfiles_v1type&premlogin&10347455password&_not_real_passrealfolder&0fields&filename,downloads,size When it should be: http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=listfiles_v1&type=prem&login=10347455&password=not_real_pass&realfolder=0&fields=filename,downloads,size Hopefully you can see what I'm trying to do here :P It's probably a silly mistake that I'm failing to find or a logical error. Thanks in advance.

    Read the article

  • Rails paginate array items one-by-one instead of page-by-page

    - by hnovick
    Hi Guys, I have a group of assets, let's call them "practitioners". I'm displaying these practitioners in the header of a calendar interface. There are 7 columns to the calendar. 7 columns = 7 practitioners per view/page. Right now: if the first page shows you practitioners 1-7, when you go the next page you will see practitioners 8-15, next page 16-23, etc. etc. i am wondering how to page the practitioners so that if the first page shows you practitioners 1-7, the next page will show you practitioners 2-8, then 3-9, etc. etc. i would greatly appreciate any help you can offer. here is the rails code i am working with. best regards, harris novick # get the default sort order sort_order = RESOURCE_SORT_ORDER # if we've been given asset ids, start our list with them unless params[:asset_ids].blank? params[:asset_ids] = params[:asset_ids].values unless params[:asset_ids].is_a?(Array) sort_order = "#{params[:asset_ids].collect{|id| "service_provider_resources.id = #{id} DESC"}.join(",")}, #{sort_order}" end @asset_set = @provider.active_resources(:include => {:active_services => :latest_approved_version}).paginate( :per_page => RESOURCES_IN_DAY_VIEW, :page => params[:page], :order => sort_order )

    Read the article

  • Help Modifying Generic REST Helper PHP Example Code to Support XML DOM

    - by Jennifer Baker
    Hi! I found this example PHP source code at HTTP POST from PHP, without cURL I need some help modifying the example PHP source to support XML DOM for manipulating a REST API. I thought that if I update the CASE statement for the XML section below from $r = simplexml_load_string($res); to $r = new DOMDocument(); $r->load($res); that it would work but it doesn't. :( Any help would be appreciated. function rest_helper($url, $params = null, $verb = 'GET', $format = 'xml') { $cparams = array( 'http' => array( 'method' => $verb, 'ignore_errors' => true ) ); if ($params !== null) { $params = http_build_query($params); if ($verb == 'POST') { $cparams['http']['content'] = $params; } else { $url .= '?' . $params; } } $context = stream_context_create($cparams); $fp = fopen($url, 'rb', false, $context); if (!$fp) { $res = false; } else { // If you're trying to troubleshoot problems, try uncommenting the // next two lines; it will show you the HTTP response headers across // all the redirects: // $meta = stream_get_meta_data($fp); // var_dump($meta['wrapper_data']); $res = stream_get_contents($fp); } if ($res === false) { throw new Exception("$verb $url failed: $php_errormsg"); } switch ($format) { case 'json': $r = json_decode($res); if ($r === null) { throw new Exception("failed to decode $res as json"); } return $r; case 'xml': $r = simplexml_load_string($res); if ($r === null) { throw new Exception("failed to decode $res as xml"); } return $r; } return $res; }

    Read the article

  • Group and sort blog posts by date in Rails

    - by Senthil
    I've searched all over web and have not found the answer. I'm trying to have a very standard archive option for my blog based on date. A request to url blog.com/archive/2009 shows all posts in 2009, blog.com/archive/2009/11 shows all posts in November 2009 etc. I found two different of code but not very helpful to me. def display_by_date year = params[:year] month = params[:month] day = params[:day] day = '0'+day if day && day.size == 1 @day = day if (year && month && day) render(:template => "blog/#{year}/#{month}/#{date}") elsif year render(:template => "blog/#{year}/list") end end def archive year = params[:year] month = params[:month] day = params[:day] day = '0'+day if day && day.size == 1 if (year && month && day) @posts_by_month = Blog.find(:all, :conditions => ["year is?", year]) else @posts_by_month = Blog.find(:all).group_by { |post| post.created_at.strftime("%B") } end end Any help is appreciated.

    Read the article

  • Http authentication with apache httpcomponents

    - by matdan
    Hi, I am trying to develop a java http client with apache httpcomponents 4.0.1. This client calls the page "https://myHost/myPage". This page is protected on the server by a JNDIRealm with a login form authentication, so when I try to get https://myHost/myPage I get a login page. I tried to bypass it unsuccessfully with the following code : //I set my proxy HttpHost proxy = new HttpHost("myProxyHost", myProxyPort); //I add supported schemes SchemeRegistry supportedSchemes = new SchemeRegistry(); supportedSchemes.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); supportedSchemes.register(new Scheme("https", SSLSocketFactory .getSocketFactory(), 443)); // prepare parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes); DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); //I add my authentication information httpclient.getCredentialsProvider().setCredentials( new AuthScope("myHost/myPage", 443), new UsernamePasswordCredentials("username", "password")); HttpHost host = new HttpHost("myHost", 443, "https"); HttpGet req = new HttpGet("/myPage"); //show the page ResponseHandler<String> responseHandler = new BasicResponseHandler(); String rsp = httpClient.execute(host, req, responseHandler); System.out.println(rsp); When I run this code, I always get the login page, not myPage. How can I apply my credential parameters to avoid this login form? Any help would be fantastic

    Read the article

  • Paperclip: Stay put on edit

    - by EricR
    When a user edits something in my application, they're forced to re-upload their image via paperclip even if they aren't changing it. Failing to do so will cause an error, since I validate_presence_of :image. This is quite annoying. How can I make it so Paperclip won't update its attributes if a user simply doesn't supply a new image on an edit? The photo controller is fresh out of Rails' scaffold generator. The rest of the source code is provided below. models/accommodation.rb class Accommodation < ActiveRecord::Base attr_accessible :photo validates_presence_of :photo has_one :photo has_many :notifications belongs_to :user accepts_nested_attributes_for :photo, :allow_destroy => true end controllers/accommodation_controller.rb class AccommodationsController < ApplicationController def index @accommodations = Accommodation.all end def show @accommodation = Accommodation.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:error] = "Accommodation not found." redirect_to :home end def new @accommodation = current_user.accommodations.build @accommodation.build_photo end def create @accommodation = current_user.accommodations.build(params[:accommodation]) if @accommodation.save flash[:notice] = "Successfully created your accommodation." redirect_to @accommodation else @accommodation.build_photo render :new end end def edit @accommodation = Accommodation.find(params[:id]) @accommodation.build_photo rescue ActiveRecord::RecordNotFound flash[:error] = "Accommodation not found." redirect_to :home end def update @accommodation = Accommodation.find(params[:id]) if @accommodation.update_attributes(params[:accommodation]) flash[:notice] = "Successfully updated accommodation." redirect_to @accommodation else @accommodation.build_photo render :edit end end def destroy @accommodation = Accommodation.find(params[:id]) @accommodation.destroy flash[:notice] = "Successfully destroyed accommodation." redirect_to :inkeep end end models/photo.rb class Photo < ActiveRecord::Base attr_accessible :image, :primary belongs_to :accommodation has_attached_file :image, :styles => { :thumb=> "100x100#", :small => "150x150>" } end

    Read the article

  • multiple-to-one relationship mysql, submissions

    - by Yulia
    Hello, I have the following problem. Basically I have a form with an option to submit up to 3 images. Right now, after each submission it creates 3 records for album table and 3 records for images. I need it to be one record for album and 3 for images, plus to link images to the album. I hope it all makes sense... Here is my structure. TABLE `albums` ( `id` int(11) NOT NULL auto_increment, `title` varchar(50) NOT NULL, `fullname` varchar(40) NOT NULL, `email` varchar(100) NOT NULL, `created_at` datetime NOT NULL, `theme_id` int(11) NOT NULL, `description` int(11) NOT NULL, `vote_cache` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; TABLE `images` ( `id` int(11) NOT NULL auto_increment, `album_id` int(11) NOT NULL, `name` varchar(30) NOT NULL, and my code function create_album($params) { db_connect(); $query = sprintf("INSERT INTO albums set albums.title = '%s', albums.email = '%s', albums.discuss_url = '%s', albums.theme_id = '%s', albums.fullname = '%s', albums.description = '%s', created_at = NOW()", mysql_real_escape_string($params['title']), mysql_real_escape_string($params['email']), mysql_real_escape_string($params['theme_id']), mysql_real_escape_string($params['fullname']), mysql_real_escape_string($params['description']) ); $result = mysql_query($query); if(!$result) { return false; } $album_id = mysql_insert_id(); return $album_id; } if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i])) { $warning = 'No file uploaded'; } elseif is_valid_file_size($_FILES['userfile']['size'][$i])) { $_POST['album']['theme_id'] = $theme['id']; create_album($_POST['album']); mysql_query("INSERT INTO images(name) VALUES('$newName')"); copy($_FILES['userfile']['tmp_name'][$i], './photos/'.$original_dir.'/' .$newName.'.jpg');

    Read the article

  • Rails - Searching multiple textboxes and fields

    - by ChrisWesAllen
    I have a model of events that has various information such as date, location, and description of whats going on. I would like for my users to be able to search through the events list through a set of different textboxes but I having a hard time getting the syntax just right in my view I have... <% form_tag users_path, :method => 'get' do %> (<%= text_field_tag :search_keyword, params[:search_keyword] %>) + (<%= text_field_tag :search_zip, params[:search_zip] %>) <%= submit_tag "Find Events!", :name => nil %> <% end %> and in the controller I'm trying to query through the results.... if params[:search_keyword] @events = Event.find(:all, :conditions => [' name LIKE ? ', "%#{params[:search_keyword]}%"]) elsif params[:search_zip] @events = Event.find(:all, :origin=> params[:search_zip], :within=>50 ) else @events = Event.find(:all) end How do I code it so that it will perform the search only if the textbox isnt empty? also if both textboxes are filled then @events should be the product of BOTH queries? if have no idea if this would work =(???@event = @event+ event.find.....???

    Read the article

  • Sharing cookies/session from WebView to HttpClient doesn't work

    - by Toni Kanoni
    I know this question has been asked a hundred times, and I've read and tried for 2 hours now, but I can't find my error :-( I am trying to create a simple webbrowser and therefore have a webview, where I login on a site and get access to a picture area. With help of a DefaultHttpClient, I want to make it possible to download pictures in the secured area. Therefore I am trying to share the cookies from the webview and pass them on to the HttpClient, so that it is authenticated and able to download. But whatever I try and do, I always get a 403 response back... Basically the steps are the following: 1) Enter URL, webview loads website 2) Enter login details in a form 3) Navigate to picture and long hold for context menu 4) Retrieve the image URL and pass it on to AsynTask for downloading Here's the code of the AsyncTask with the Cookie stuff: protected String doInBackground(String... params) { //params[0] is the URL of the image try { CookieManager cookieManager = CookieManager.getInstance(); String c = cookieManager.getCookie(new URL(params[0]).getHost()); BasicCookieStore cookieStore = new BasicCookieStore(); BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); String[] cookieParts = null; String cookies[] = null; cookies = c.split(";"); for(int i=0;i<cookies.length;i++) { cookieParts = cookies[i].split("="); BasicClientCookie sessionCookie = new BasicClientCookie(cookieParts[0].trim(), cookieParts[1].trim()); sessionCookie.setDomain(new URL(params[0]).getHost()); cookieStore.addCookie(sessionCookie); } DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.setCookieStore(cookieStore); HttpGet pageGet = new HttpGet(new URL(params[0]).toURI()); HttpResponse response = httpClient.execute(pageGet, localContext); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) -- NEVER Happens, always get 403 .) One of the problems is that the webview saves some cookies for the host *www.*example.com, but the image-URL to download (params[0]) is *static.*example.com. The line cookieManager.getCookie(new URL(params[0]).getHost()); returns null, because there is no cookie for static.example.com, but only for www.example.com. .) When I manually say cookieManager.getCookie("www.example.com"); I get some cookies back, which I add to the HttpClient cookie store: There are 5 cookies added - testcookie = 0 - PHPSESSID = 320947238someGibberishSessionId - email = [email protected] - pass = 32423te32someEncodedPassGibberish - user = 345542 So although these cookies, a session ID and other stuff, get added to the HttpClient, it never get's through to download an image. Im totally lost... though I guess that it either has something to do with the cookies domains, or that Im still missing other cookies. But from where the heck should I know which cookies exist in the webview, when I have to specify a specific URL to get a cookie back?? :-( Any advice?

    Read the article

  • Having trouble understanding some code (Ruby on Rails)

    - by user284194
    I posted a question awhile ago asking how I could limit the rate at which a form could be submitted from a rails application. I was helped by a very patient user and their solution works great. The code was for my comments controller, and now I find myself wanting to add this functionality to another controller, my Messages controller. I immediately tried reusing the working code from the comments controller but I couldn't get it to work. Instead of asking for the working code, could someone please help me understand my working comment controller code? class CommentsController < ApplicationController #... before_filter :post_check def record_post_time cookies[:last_post_at] = Time.now.to_i end def last_post_time Time.at((cookies[:last_post_at].to_i rescue 0)) end MIN_POST_TIME = 2.minutes def post_check return true if (Time.now - last_post_time) > MIN_POST_TIME flash[:warning] = "You are trying to reply too fast." @message = Message.find(params[:message_id]) redirect_to(@message) return false end #... def create @message = Message.find(params[:message_id]) @comment = @message.comments.build(params[:comment]) if @comment.save record_post_time flash[:notice] = "Replied to \"#{@message.title}\"" redirect_to(@message) else render :action => "new" end end def update @message = Message.find(params[:message_id]) @comment = Comment.find(params[:id]) if @comment.update_attributes(params[:comment]) record_post_time redirect_to post_comment_url(@message, @comment) else render :action => "edit" end end #... end My Messages controller is pretty much a standard rails generated controller with a few before filters and associated private methods for DRYing up the code and a redirect for non existent pages. I'll explain how much of the code I understand. When a comment is created, a cookie is created with a last_post_time value. If they try to post another comment, the cookie is checked if the last one was made in the last two minutes. If it was a flash warning is displayed and no comment is recorded. What I don't really understand is how the post_check method works and how I can adapt it for my simpler posts controller. I thought I could reuse all the code in the message controller with the exception of the line: @message = Message.find(params[:message_id]) # (don't need the redirect code) in the post_check method. But it trips up on the "record_post_time" in the create action/method. I really want to understand this. Can someone explain why this doesn't work? I greatly appreciate you reading my lengthy question.

    Read the article

  • How to extend a file definition from an existing module in the node?

    - by c33s
    I use an older version of the example42 mysql module, which defines the mysql.conf file but not its content. Mmy goal is to just include the mysql module and add a content definition in the node. class mysql { ... file { "mysql.conf": path => "${mysql::params::configfile}", mode => "${mysql::params::configfile_mode}", owner => "${mysql::params::configfile_owner}", group => "${mysql::params::configfile_group}", ensure => present, require => Package["mysql"], notify => Service["mysql"], } ... } node xyz { include mysql File["mysql.conf"] { content => template("mymodule/mysql.conf.erb")} } The above code produces a "Only subclasses can override parameters" What is the correct way to just add a content definition to an existing file definition?

    Read the article

  • Get the touch position inside the imageview in android

    - by Manikandan
    I have a imageview in my activity and I am able to get the position where the user touch the imageview, through onTouchListener. I placed another image where the user touch over that image. I need to store the touch position(x,y), and use it in another activity, to show the tags. I stored the touch position in the first activity. In the first activity, my imageview at the top of the screen. In the second activity its at the bottom of the screen. If I use the position stored from the first acitvity, it place the tag image at the top, not on the imageview, where I previously clicked in the first activity. Is there anyway to get the position inside the imageview. FirstActivity: cp.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub Log.v("touched x val of cap img >>", event.getX() + ""); Log.v("touched y val of cap img >>", event.getY() + ""); x = (int) event.getX(); y = (int) event.getY(); tag.setVisibility(View.VISIBLE); int[] viewCoords = new int[2]; cp.getLocationOnScreen(viewCoords); int imageX = x - viewCoords[0]; // viewCoods[0] is the X coordinate int imageY = y - viewCoords[1]; // viewCoods[1] is the y coordinate Log.v("Real x >>>",imageX+""); Log.v("Real y >>>",imageY+""); RelativeLayout rl = (RelativeLayout) findViewById(R.id.lay_lin); ImageView iv = new ImageView(Capture_Image.this); Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.tag_icon_32); iv.setImageBitmap(bm); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params.leftMargin = x; params.topMargin = y; rl.addView(iv, params); Intent intent= new Intent(Capture_Image.this,Tag_Image.class); Bundle b=new Bundle(); b.putInt("xval", imageX); b.putInt("yval", imageY); intent.putExtras(b); startActivity(intent); return false; } }); In TagImage.java I used the following: im = (ImageView) findViewById(R.id.img_cam22); b=getIntent().getExtras(); xx=b.getInt("xval"); yy=b.getInt("yval"); im.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int[] viewCoords = new int[2]; im.getLocationOnScreen(viewCoords); int imageX = xx + viewCoords[0]; // viewCoods[0] is the X coordinate int imageY = yy+ viewCoords[1]; // viewCoods[1] is the y coordinate Log.v("Real x >>>",imageX+""); Log.v("Real y >>>",imageY+""); RelativeLayout rl = (RelativeLayout) findViewById(R.id.lay_lin); ImageView iv = new ImageView(Tag_Image.this); Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.tag_icon_32); iv.setImageBitmap(bm); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( 30, 40); params.leftMargin =imageX ; params.topMargin = imageY; rl.addView(iv, params); return true; } });

    Read the article

  • Rails: (Devise) Two different methods for new users?

    - by neezer
    I have a Rails 3 app with authentication setup using Devise with the registerable module enabled. I want to have new users who sign up using our outside register form to use the full Devise registerable module, which is happening now. However, I also want the admin user to be able to create new users directly, bypassing (I think) Devise's registerable module. With registerable disabled, my standard UsersController works as I want it to for the admin user, just like any other Rail scaffold. However, now new users can't register on their own. With registerable enabled, my standard UsersController is never called for the new user action (calling Devise::RegistrationsController instead), and my CRUD actions don't seem to work at all (I get dumped back onto my root page with no new user created and no flash message). Here's the log from the request: Started POST "/users" for 127.0.0.1 at 2010-12-20 11:49:31 -0500 Processing by Devise::RegistrationsController#create as HTML Parameters: {"utf8"=>"?", "authenticity_token"=>"18697r4syNNWHfMTkDCwcDYphjos+68rPFsaYKVjo8Y=", "user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "role"=>"manager"}, "commit"=>"Create User"} SQL (0.9ms) ... User Load (0.6ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 2) LIMIT 1 SQL (0.9ms) ... Redirected to http://test-app.local/ Completed 302 Found in 192ms ... but I am able to register new users through the outside form. How can I get both of these methods to work together, such that my admin user can manually create new users and guest users can register on their own? I have my Users controller setup for standard CRUD: class UsersController < ApplicationController load_and_authorize_resource def index @users = User.where("id NOT IN (?)", current_user.id) # don't display the current user in the users list; go to account management to edit current user details end def new @user = User.new end def create @user = User.new(params[:user]) if @user.save flash[:notice] = "#{ @user.email } created." redirect_to users_path else render :action => 'new' end end def edit end def update params[:user].delete(:password) if params[:user][:password].blank? params[:user].delete(:password_confirmation) if params[:user][:password].blank? and params[:user][:password_confirmation].blank? if @user.update_attributes(params[:user]) flash[:notice] = "Successfully updated User." redirect_to users_path else render :action => 'edit' end end def delete end def destroy redirect_to users_path and return if params[:cancel] if @user.destroy flash[:notice] = "#{ @user.email } deleted." redirect_to users_path end end end And my routes setup as follows: TestApp::Application.routes.draw do devise_for :users devise_scope :user do get "/login", :to => "devise/sessions#new", :as => :new_user_session get "/logout", :to => "devise/sessions#destroy", :as => :destroy_user_session end resources :users do get :delete, :on => :member end authenticate :user do root :to => "application#index" end root :to => "devise/session#new" end

    Read the article

  • Getting Query Parameters in Javascript

    - by PhubarBaz
    I find myself needing to get query parameters that are passed into a web app on the URL quite often. At first I wrote a function that creates an associative array (aka object) with all of the parameters as keys and returns it. But then I was looking at the revealing module pattern, a nice javascript design pattern designed to hide private functions, and came up with a way to do this without even calling a function. What I came up with was this nice little object that automatically initializes itself into the same associative array that the function call did previously. // Creates associative array (object) of query params var QueryParameters = (function() {     var result = {};     if (window.location.search)     {         // split up the query string and store in an associative array         var params = window.location.search.slice(1).split("&");         for (var i = 0; i < params.length; i++)         {             var tmp = params[i].split("=");             result[tmp[0]] = unescape(tmp[1]);         }     }     return result; }()); Now all you have to do to get the query parameters is just reference them from the QueryParameters object. There is no need to create a new object or call any function to initialize it. var debug = (QueryParameters.debug === "true"); or if (QueryParameters["debug"]) doSomeDebugging(); or loop through all of the parameters. for (var param in QueryParameters) var value = QueryParameters[param]; Hope you find this object useful.

    Read the article

  • A Cautionary Tale About Multi-Source JNDI Configuration

    - by scott.s.nelson(at)oracle.com
    Here's a bit of fun with WebLogic JDBC configurations.  I ran into this issue after reading that p13nDataSource and cgDataSource-NonXA should not be configured as multi-source. There were some issues changing them to use the basic JDBC connection string and when rolling back to the bad configuration the server went "Boom".  Since one purpose behind this blog is to share lessons learned, I just had to post this. If you write your descriptors manually (as opposed to generating them using the WLS console) and put a comma-separated list of JNDI addresses like this: <jdbc-data-source-params> <jndi-name>weblogic.jdbc.jts.commercePool,contentDataSource, contentVersioningDataSource,portalFrameworkPool</jndi-name> <algorithm-type>Load-Balancing</algorithm-type> <data-source-list>portalDataSource-rac0,portalDataSource-rac1</data-source-list> <failover-request-if-busy>false</failover-request-if-busy> </jdbc-data-source-params> so long as the first address resolves, it will still work. Sort of.  If you call this connection to do an update, only one node of the RAC instance is updated. Other wonderful side-effects include the server refusing to start sometimes. The proper way to list the JNDI sources is one per node, like this: <jdbc-data-source-params> <jndi-name>weblogic.jdbc.jts.commercePool</jndi-name> <jndi-name>contentDataSource</jndi-name> <jndi-name>contentVersioningDataSource</jndi-name> <jndi-name>portalFrameworkPool</jndi-name> <algorithm-type>Load-Balancing</algorithm-type> <data-source-list>portalDataSource-rac0, portalDataSource-rac1, portalDataSource-rac2 </data-source-list> <failover-request-if-busy>false</failover-request-if-busy> </jdbc-data-source-params>(Props to Sandeep Seshan for locating the root cause)

    Read the article

  • AJAX driven "page complete" function? Am I doing it right?

    - by Julian H. Lam
    This one might get me slaughtered, since I'm pretty sure it's bad coding practice, so here goes: I have an AJAX driven site which loads both content and javascript in one go using Mootools' Request.HTML. Since I have initialization scripts that need to be run to finish "setting up" the template, I include those in a function called pageComplete(), on every page Visiting one page to another causes the previous pageComplete() function to no longer apply, since a new one is defined. The javascript function that loads pages dynamically calls pageComplete() blindly when the AJAX call is completed and is loaded onto the page: function loadPage(page, params) { // page is a string, params is a javascript object if (pageRequest && pageRequest.isRunning) pageRequest.cancel(); pageRequest = new Request.HTML({ url: '<?=APPLICATION_LINK?>' + page, evalScripts: true, onSuccess: function(tree, elements, html) { // Empty previous content and insert new content $('content').empty(); $('content').innerHTML = html; pageComplete(); pageRequest = null; } }).send('params='+JSON.encode(params)); } So yes, if pageComplete() is not defined in one the pages, the old pageComplete() is called, which could potentially be disastrous, but as of now, every single page has pageComplete() defined, even if it is empty. Good idea, bad idea?

    Read the article

  • ??GoldenGate??Manager??

    - by Liu Maclean(???)
    ???????OGG?????????????MGR(Manager)???????,????????./dirprm/mgr.prm???? ????????manager?????: ggsci > edit params mgr ??ggsci edit params???????,???????????? OGG??????????????????????? ???mgr.prm????,??????./dirprm??OGG???????? ???Manager?????????,????????????????????? ????????????????,??????????????????????????????,???????????? PORT 7809 –??MGR?PORT????????,????????TCP?????,?????????????7809?????????? DYNAMICPORTLIST 9101 – 9356DYNAMICPORTSREASSIGNDELAY 5 –???????????source????????,??????target????????? PURGEOLDEXTRACTS ./dirdat/*, usecheckpoints, minkeephours 96 Manager????trail?????????,minkeephours 96????96????4???trail LAGINFOSECONDS 15LAGCRITICALMINUTES 2 ??2??????LAG REPORT????? BOOTDELAYMINUTES 3 ??BOOTDELAYMINUTES??windows??,??Windows??3????BOOT OGG MGR AUTOSTART ER * AUTOSTART ???MGR????????EXTRACT?REPLICAT AutoRestart ER *, WaitMinutes 5, Retries 3 AUTORESTART ?????????OGG??,?????????? PurgeMarkerHistory MinKeepDays 3, MaxKeepDays 7, FrequencyMinutes 120 ??PurgeMarkerHistory?????DDL?????? CHECKMINUTES 10 CHECKMINUTES ??? MGR????????,?????10???? DOWNCRITICAL ?????OGG???abend??????????,?????DOWNCRITICAL??,??????? ??Manager?????????,???????????,manager????????? OGG??????Manager????????????Extract?Replicat?Manager??????,??Manager????????Manager????,????????????????,Refresh???MGR?????????? ??????MGR PARAMS GGSCI (XIANGBLI-CN) 2> view params mgr Port 7809 UserId goldengate, Password goldengate CheckMinutes 10PurgeOldExtracts ./dirdat/*, UseCheckpoints, MinKeepHours 96PurgeMarkerHistory MinKeepDays 3, MaxKeepDays 7, FrequencyMinutes 120AutoRestart ER *, WaitMinutes 5, Retries 3LagInfoMinutes 0LagReportMinutes 10 GGSCI (XIANGBLI-CN) 4> start mgr Manager started.

    Read the article

  • Why wont this sort in Solr work?

    - by Camran
    I need to sort on a date-field type, which name is "mod_date". It works like this in the browser adress-bar: http://localhost:8983/solr/select/?&q=bmw&sort=mod_date+desc But I am using a phpSolr client which sends an URL to Solr, and the url sent is this: fq=+category%3A%22Bilar%22+%2B+car_action%3AS%C3%A4ljes&version=1.2&wt=json&json.nl=map&q=%2A%3A%2A&start=0&rows=5&sort=mod_date+desc // This wont work and is echoed after this in php: $queryString = http_build_query($params, null, $this->_queryStringDelimiter); $queryString = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $queryString); This wont work, I dont know why! Everything else works fine, all right fields are returned. But the sort doesn't work. Any ideas? Thanks BTW: The field "mod_date" contains something like: 2010-03-04T19:37:22.5Z EDIT: First I use PHP to send this to a SolrPhpClient which is another php-file called service.php: require_once('../SolrPhpClient/Apache/Solr/Service.php'); $solr = new Apache_Solr_Service('localhost', 8983, '/solr/'); $results = $solr->search($querystring, $p, $limit, $solr_params); $solr_params is an array which contains the solr-parameters (q, fq, etc). Now, in service.php: $params['version'] = self::SOLR_VERSION; // common parameters in this interface $params['wt'] = self::SOLR_WRITER; $params['json.nl'] = $this->_namedListTreatment; $params['q'] = $query; $params['sort'] = 'mod_date desc'; // HERE IS THE SORT I HAVE PROBLEM WITH $params['start'] = $offset; $params['rows'] = $limit; $queryString = http_build_query($params, null, $this->_queryStringDelimiter); $queryString = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $queryString); if ($method == self::METHOD_GET) { return $this->_sendRawGet($this->_searchUrl . $this->_queryDelimiter . $queryString); } else if ($method == self::METHOD_POST) { return $this->_sendRawPost($this->_searchUrl, $queryString, FALSE, 'application/x-www-form-urlencoded'); } The $results contain the results from Solr... So this is the way I need to get to work (via php). This code below (also on top of this Q) works but thats because I paste it into the adress bar manually, not via the PHPclient. But thats just for debugging, I need to get it to work via the PHPclient: http://localhost:8983/solr/select/?&q=bmw&sort=mod_date+des // Not via phpclient, but works UPDATE (2010-03-08): I have tried Donovans codes (the urls) and they work fine. Now, I have noticed that it is one of the parameters causing the 'SORT' not to work. This parameter is the "wt" parameter. If we take the url from top of this Q, (fq=+category%3A%22Bilar%22+%2B+car_action%3AS%C3%A4ljes&version=1.2&wt=json&json.nl=map&q=%2A%3A%2A&start=0&rows=5&sort=mod_date+desc), and just simply remove the "wt" parameter, then the sort works. BUT the results appear differently, thus making my php code not able to recognize the results I believe. Donovan would know this I think. I am guessing in order for the PHPClient to work, the results must be in a specific structure, which gets messed up as soon as I remove the wt parameter. Donovan, help me please... Here is some background what I use your SolrPhpClient for: I have a classifieds website, which uses MySql. But for the searching I am using Solr to search some indexed fields. Then Solr returns an array of ID:numbers (for all matches of the search criteria). Then I use those ID:numbers to find everything in a MySql db and fetch all other information (example is not searchable information). So simplified: Search - Solr returns all matches in an array of ID:nrs - Id:numbers from Solr are the same as the Id numbers in the MySql db, so I can just make a simple match agains every record with the ID matching the ID from the Solr results array. I don't use Faceting, no boosting, no relevancy or other fancy stuff. I only sort by the latest classified put, and give the option to users to also sort on the cheapest price. Nothing more. Then I use the "fq" parameter to do queries on different fields in Solr depending on category chosen by users (example "cars" in this case which in my language is "Bilar"). I am really stuck with this problem here... Thanks for all help

    Read the article

  • what does calling ´this´ outside of a jquery plugin refer to

    - by Richard
    Hi, I am using the liveTwitter plugin The problem is that I need to stop the plugin from hitting the Twitter api. According to the documentation I need to do this $("#tab1 .container_twitter_status").each(function(){ this.twitter.stop(); }); Already, the each does not make sense on an id and what does this refer to? Anyway, I get an undefined error. I will paste the plugin code and hope it makes sense to somebody MY only problem thusfar with this plugin is that I need to be able to stop it. thanks in advance, Richard /* * jQuery LiveTwitter 1.5.0 * - Live updating Twitter plugin for jQuery * * Copyright (c) 2009-2010 Inge Jørgensen (elektronaut.no) * Licensed under the MIT license (MIT-LICENSE.txt) * * $Date: 2010/05/30$ */ /* * Usage example: * $("#twitterSearch").liveTwitter('bacon', {limit: 10, rate: 15000}); */ (function($){ if(!$.fn.reverse){ $.fn.reverse = function() { return this.pushStack(this.get().reverse(), arguments); }; } $.fn.liveTwitter = function(query, options, callback){ var domNode = this; $(this).each(function(){ var settings = {}; // Handle changing of options if(this.twitter) { settings = jQuery.extend(this.twitter.settings, options); this.twitter.settings = settings; if(query) { this.twitter.query = query; } this.twitter.limit = settings.limit; this.twitter.mode = settings.mode; if(this.twitter.interval){ this.twitter.refresh(); } if(callback){ this.twitter.callback = callback; } // ..or create a new twitter object } else { // Extend settings with the defaults settings = jQuery.extend({ mode: 'search', // Mode, valid options are: 'search', 'user_timeline' rate: 15000, // Refresh rate in ms limit: 10, // Limit number of results refresh: true }, options); // Default setting for showAuthor if not provided if(typeof settings.showAuthor == "undefined"){ settings.showAuthor = (settings.mode == 'user_timeline') ? false : true; } // Set up a dummy function for the Twitter API callback if(!window.twitter_callback){ window.twitter_callback = function(){return true;}; } this.twitter = { settings: settings, query: query, limit: settings.limit, mode: settings.mode, interval: false, container: this, lastTimeStamp: 0, callback: callback, // Convert the time stamp to a more human readable format relativeTime: function(timeString){ var parsedDate = Date.parse(timeString); var delta = (Date.parse(Date()) - parsedDate) / 1000; var r = ''; if (delta < 60) { r = delta + ' seconds ago'; } else if(delta < 120) { r = 'a minute ago'; } else if(delta < (45*60)) { r = (parseInt(delta / 60, 10)).toString() + ' minutes ago'; } else if(delta < (90*60)) { r = 'an hour ago'; } else if(delta < (24*60*60)) { r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago'; } else if(delta < (48*60*60)) { r = 'a day ago'; } else { r = (parseInt(delta / 86400, 10)).toString() + ' days ago'; } return r; }, // Update the timestamps in realtime refreshTime: function() { var twitter = this; $(twitter.container).find('span.time').each(function(){ $(this).html(twitter.relativeTime(this.timeStamp)); }); }, // Handle reloading refresh: function(initialize){ var twitter = this; if(this.settings.refresh || initialize) { var url = ''; var params = {}; if(twitter.mode == 'search'){ params.q = this.query; if(this.settings.geocode){ params.geocode = this.settings.geocode; } if(this.settings.lang){ params.lang = this.settings.lang; } if(this.settings.rpp){ params.rpp = this.settings.rpp; } else { params.rpp = this.settings.limit; } // Convert params to string var paramsString = []; for(var param in params){ if(params.hasOwnProperty(param)){ paramsString[paramsString.length] = param + '=' + encodeURIComponent(params[param]); } } paramsString = paramsString.join("&"); url = "http://search.twitter.com/search.json?"+paramsString+"&callback=?"; } else if(twitter.mode == 'user_timeline') { url = "http://api.twitter.com/1/statuses/user_timeline/"+encodeURIComponent(this.query)+".json?count="+twitter.limit+"&callback=?"; } else if(twitter.mode == 'list') { var username = encodeURIComponent(this.query.user); var listname = encodeURIComponent(this.query.list); url = "http://api.twitter.com/1/"+username+"/lists/"+listname+"/statuses.json?per_page="+twitter.limit+"&callback=?"; } $.getJSON(url, function(json) { var results = null; if(twitter.mode == 'search'){ results = json.results; } else { results = json; } var newTweets = 0; $(results).reverse().each(function(){ var screen_name = ''; var profile_image_url = ''; if(twitter.mode == 'search') { screen_name = this.from_user; profile_image_url = this.profile_image_url; created_at_date = this.created_at; } else { screen_name = this.user.screen_name; profile_image_url = this.user.profile_image_url; // Fix for IE created_at_date = this.created_at.replace(/^(\w+)\s(\w+)\s(\d+)(.*)(\s\d+)$/, "$1, $3 $2$5$4"); } var userInfo = this.user; var linkified_text = this.text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) { return m.link(m); }); linkified_text = linkified_text.replace(/@[A-Za-z0-9_]+/g, function(u){return u.link('http://twitter.com/'+u.replace(/^@/,''));}); linkified_text = linkified_text.replace(/#[A-Za-z0-9_\-]+/g, function(u){return u.link('http://search.twitter.com/search?q='+u.replace(/^#/,'%23'));}); if(!twitter.settings.filter || twitter.settings.filter(this)) { if(Date.parse(created_at_date) > twitter.lastTimeStamp) { newTweets += 1; var tweetHTML = '<div class="tweet tweet-'+this.id+'">'; if(twitter.settings.showAuthor) { tweetHTML += '<img width="24" height="24" src="'+profile_image_url+'" />' + '<p class="text"><span class="username"><a href="http://twitter.com/'+screen_name+'">'+screen_name+'</a>:</span> '; } else { tweetHTML += '<p class="text"> '; } tweetHTML += linkified_text + ' <span class="time">'+twitter.relativeTime(created_at_date)+'</span>' + '</p>' + '</div>'; $(twitter.container).prepend(tweetHTML); var timeStamp = created_at_date; $(twitter.container).find('span.time:first').each(function(){ this.timeStamp = timeStamp; }); if(!initialize) { $(twitter.container).find('.tweet-'+this.id).hide().fadeIn(); } twitter.lastTimeStamp = Date.parse(created_at_date); } } }); if(newTweets > 0) { // Limit number of entries $(twitter.container).find('div.tweet:gt('+(twitter.limit-1)+')').remove(); // Run callback if(twitter.callback){ twitter.callback(domNode, newTweets); } // Trigger event $(domNode).trigger('tweets'); } }); } }, start: function(){ var twitter = this; if(!this.interval){ this.interval = setInterval(function(){twitter.refresh();}, twitter.settings.rate); this.refresh(true); } }, stop: function(){ if(this.interval){ clearInterval(this.interval); this.interval = false; } } }; var twitter = this.twitter; this.timeInterval = setInterval(function(){twitter.refreshTime();}, 5000); this.twitter.start(); } }); return this; }; })(jQuery);

    Read the article

  • best practice for initializing class members in php

    - by rgvcorley
    I have lots of code like this in my constructors:- function __construct($params) { $this->property = isset($params['property']) ? $params['property'] : default_val; } Is it better to do this rather than specify the default value in the property definition? i.e. public $property = default_val? Sometimes there is logic for the default value, and some default values are taken from other properties, which was why I was doing this in the constructor. Should I be using setters so all the logic for default values is separated?

    Read the article

  • OIM 11g notification framework

    - by Rajesh G Kumar
    OIM 11g has introduced an improved and template based Notifications framework. New release has removed the limitation of sending text based emails (out-of-the-box emails) and enhanced to support html features. New release provides in-built out-of-the-box templates for events like 'Reset Password', 'Create User Self Service' , ‘User Deleted' etc. Also provides new APIs to support custom templates to send notifications out of OIM. OIM notification framework supports notification mechanism based on events, notification templates and template resolver. They are defined as follows: Ø Events are defined as XML file and imported as part of MDS database in order to make notification event available for use. Ø Notification templates are created using OIM advance administration console. The template contains the text and the substitution 'variables' which will be replaced with the data provided by the template resolver. Templates support internationalization and can be defined as HTML or in form of simple text. Ø Template resolver is a Java class that is responsible to provide attributes and data to be used at runtime and design time. It must be deployed following the OIM plug-in framework. Resolver data provided at design time is to be used by end user to design notification template with available entity variables and it also provides data at runtime to replace the designed variable with value to be displayed to recipients. Steps to define custom notifications in OIM 11g are: Steps# Steps 1. Define the Notification Event 2. Create the Custom Template Resolver class 3. Create Template with notification contents to be sent to recipients 4. Create Event triggering spots in OIM 1. Notification Event metadata The Notification Event is defined as XML file which need to be imported into MDS database. An event file must be compliant with the schema defined by the notification engine, which is NotificationEvent.xsd. The event file contains basic information about the event.XSD location in MDS database: “/metadata/iam-features-notification/NotificationEvent.xsd”Schema file can be viewed by exporting file from MDS using weblogicExportMetadata.sh script.Sample Notification event metadata definition: 1: <?xml version="1.0" encoding="UTF-8"?> 2: <Events xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:noNamespaceSchemaLocation="../../../metadata/NotificationEvent.xsd"> 3: <EventType name="Sample Notification"> 4: <StaticData> 5: <Attribute DataType="X2-Entity" EntityName="User" Name="Granted User"/> 6: </StaticData> 7: <Resolver class="com.iam.oim.demo.notification.DemoNotificationResolver"> 8: <Param DataType="91-Entity" EntityName="Resource" Name="ResourceInfo"/> 9: </Resolver> 10: </EventType> 11: </Events> Line# Description 1. XML file notation tag 2. Events is root tag 3. EventType tag is to declare a unique event name which will be available for template designing 4. The StaticData element lists a set of parameters which allow user to add parameters that are not data dependent. In other words, this element defines the static data to be displayed when notification is to be configured. An example of static data is the User entity, which is not dependent on any other data and has the same set of attributes for all event instances and notification templates. Available attributes are used to be defined as substitution tokens in the template. 5. Attribute tag is child tag for StaticData to declare the entity and its data type with unique reference name. User entity is most commonly used Entity as StaticData. 6. StaticData closing tag 7. Resolver tag defines the resolver class. The Resolver class must be defined for each notification. It defines what parameters are available in the notification creation screen and how those parameters are replaced when the notification is to be sent. Resolver class resolves the data dynamically at run time and displays the attributes in the UI. 8. The Param DataType element lists a set of parameters which allow user to add parameters that are data dependent. An example of the data dependent or a dynamic entity is a resource object which user can select at run time. A notification template is to be configured for the resource object. Corresponding to the resource object field, a lookup is displayed on the UI. When a user selects the event the call goes to the Resolver class provided to fetch the fields that are displayed in the Available Data list, from which user can select the attribute to be used on the template. Param tag is child tag to declare the entity and its data type with unique reference name. 9. Resolver closing tag 10 EventType closing tag 11. Events closing tag Note: - DataType needs to be declared as “X2-Entity” for User entity and “91-Entity” for Resource or Organization entities. The dynamic entities supported for lookup are user, resource, and organization. Once notification event metadata is defined, need to be imported into MDS database. Fully qualified resolver class name need to be define for XML but do not need to load the class in OIM yet (it can be loaded later). 2. Coding the notification resolver All event owners have to provide a resolver class which would resolve the data dynamically at run time. Custom resolver class must implement the interface oracle.iam.notification.impl.NotificationEventResolver and override the implemented methods with actual implementation. It has 2 methods: S# Methods Descriptions 1. public List<NotificationAttribute> getAvailableData(String eventType, Map<String, Object> params); This API will return the list of available data variables. These variables will be available on the UI while creating/modifying the Templates and would let user select the variables so that they can be embedded as a token as part of the Messages on the template. These tokens are replaced by the value passed by the resolver class at run time. Available data is displayed in a list. The parameter "eventType" specifies the event Name for which template is to be read.The parameter "params" is the map which has the entity name and the corresponding value for which available data is to be fetched. Sample code snippet: List<NotificationAttribute> list = new ArrayList<NotificationAttribute>(); long objKey = (Long) params.get("resource"); //Form Field details based on Resource object key HashMap<String, Object> formFieldDetail = getObjectFormName(objKey); for (Iterator<?> itrd = formFieldDetail.entrySet().iterator(); itrd.hasNext(); ) { NotificationAttribute availableData = new NotificationAttribute(); Map.Entry formDetailEntrySet = (Entry<?, ?>)itrd.next(); String fieldLabel = (String)formDetailEntrySet.getValue(); availableData.setName(fieldLabel); list.add(availableData); } return list; 2. Public HashMap<String, Object> getReplacedData(String eventType, Map<String, Object> params); This API would return the resolved value of the variables present on the template at the runtime when notification is being sent. The parameter "eventType" specifies the event Name for which template is to be read.The parameter "params" is the map which has the base values such as usr_key, obj_key etc required by the resolver implementation to resolve the rest of the variables in the template. Sample code snippet: HashMap<String, Object> resolvedData = new HashMap<String, Object>();String firstName = getUserFirstname(params.get("usr_key"));resolvedData.put("fname", firstName); String lastName = getUserLastName(params.get("usr_key"));resolvedData.put("lname", lastname);resolvedData.put("count", "1 million");return resolvedData; This code must be deployed as per OIM 11g plug-in framework. The XML file defining the plug-in is as below: <?xml version="1.0" encoding="UTF-8"?> <oimplugins xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <plugins pluginpoint="oracle.iam.notification.impl.NotificationEventResolver"> <plugin pluginclass= " com.iam.oim.demo.notification.DemoNotificationResolver" version="1.0" name="Sample Notification Resolver"/> </plugins> </oimplugins> 3. Defining the template To create a notification template: Log in to the Oracle Identity Administration Click the System Management tab and then click the Notification tab From the Actions list on the left pane, select Create On the Create page, enter values for the following fields under the Template Information section: Template Name: Demo template Description Text: Demo template Under the Event Details section, perform the following: From the Available Event list, select the event for which the notification template is to be created from a list of available events. Depending on your selection, other fields are displayed in the Event Details section. Note that the template Sample Notification Event created in the previous step being used as the notification event. The contents of the Available Data drop down are based on the event XML StaticData tag, the drop down basically lists all the attributes of the entities defined in that tag. Once you select an element in the drop down, it will show up in the Selected Data text field and then you can just copy it and paste it into either the message subject or the message body fields prefixing $ symbol. Example if list has attribute like First_Name then message body will contains this as $First_Name which resolver will parse and replace it with actual value at runtime. In the Resource field, select a resource from the lookup. This is the dynamic data defined by the Param DataType element in the XML definition. Based on selected resource getAvailableData method of resolver will be called to fetch the resource object attribute detail, if method is overridden with required implementation. For current scenario, Map<String, Object> params will get populated with object key as value and key as “resource” in the map. This is the only input will be provided to resolver at design time. You need to implement the further logic to fetch the object attributes detail to populate the available Data list. List string should not have space in between, if object attributes has space for attribute name then implement logic to replace the space with ‘_’ before populating the list. Example if attribute name is “First Name” then make it “First_Name” and populate the list. Space is not supported while you try to parse and replace the token at run time with real value. Make a note that the Available Data and Selected Data are used in the substitution tokens definition only, they do not define the final data that will be sent in the notification. OIM will invoke the resolver class to get the data and make the substitutions. Under the Locale Information section, enter values in the following fields: To specify a form of encoding, select either UTF-8 or ASCII. In the Message Subject field, enter a subject for the notification. From the Type options, select the data type in which you want to send the message. You can choose between HTML and Text/Plain. In the Short Message field, enter a gist of the message in very few words. In the Long Message field, enter the message that will be sent as the notification with Available data token which need to be replaced by resolver at runtime. After you have entered the required values in all the fields, click Save. A message is displayed confirming the creation of the notification template. Click OK 4. Triggering the event A notification event can be triggered from different places in OIM. The logic behind the triggering must be coded and plugged into OIM. Examples of triggering points for notifications: Event handlers: post process notifications for specific data updates in OIM users Process tasks: to notify the users that a provisioning task was executed by OIM Scheduled tasks: to notify something related to the task The scheduled job has two parameters: Template Name: defines the notification template to be sent User Login: defines the user record that will provide the data to be sent in the notification Sample Code Snippet: public void execute(String templateName , String userId) { try { NotificationService notService = Platform.getService(NotificationService.class); NotificationEvent eventToSend=this.createNotificationEvent(templateName,userId); notService.notify(eventToSend); } catch (Exception e) { e.printStackTrace(); } } private NotificationEvent createNotificationEvent(String poTemplateName, String poUserId) { NotificationEvent event = new NotificationEvent(); String[] receiverUserIds= { poUserId }; event.setUserIds(receiverUserIds); event.setTemplateName(poTemplateName); event.setSender(null); HashMap<String, Object> templateParams = new HashMap<String, Object>(); templateParams.put("USER_LOGIN",poUserId); event.setParams(templateParams); return event; } public HashMap getAttributes() { return null; } public void setAttributes() {} }

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >