w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How To Assign an Existing Record to Another Record in Active Record
According to your models your Host must have a student_id. It's unclear from your example, but it seems like your student_id in Host.first is not Student.last.id. Another point which was touched on a bit by @kobaltz comment is that your Post model has the host_id and student_id. This looks like you are using it as an association. So your model should probably look like this. post.rb belongs_to :host belongs_to :student student.rb has_many :posts has_many :hosts, :through => :posts host.rb has_many :posts has_many :students, :through => :posts

Categories : Ruby On Rails

Formula to get the first cell with a numerical value from a selection?
You can simplify the last number formula by using LOOKUP, i.e. =LOOKUP(9.99999999999999E+307,B:B) and for the first number try this =INDEX(B:B,MATCH(1,INDEX(ISNUMBER(B:B)+0,0),0))

Categories : Excel

fill in a null cell with cell from previous record
It might look something like this: select person, house, coalesce(from_date, prev_to_date) from_date, case when rn = 1 then coalesce (to_date, '9999-01-01') else coalesce(to_date, next_from_date) end to_date from (select person, house, from_date, to_date, lag(to_date) over (partition by person order by from_date nulls last) prev_to_date, lead(from_date) over (partition by person order by from_date nulls last) next_from_date, row_number() over (partition by person order by from_date desc nulls last) rn from temp ) t The above is not tested but it might give you an idea. I hope in your actual table you have a column other than to_date and from_date that allows you to order rows for each person, otherwise you'll have trouble sorting NULL dates, as you have no way of knowing th

Categories : SQL

If then record selection with multiple conditions
Where abouts are you inputting your formula within crystal? It is very important. You should be able to achieve what you want by using conditional suppression in the details section of your report. Something like this... //Untested// IF {V_JOB.TASK} LIKE "*IN" AND {V_JOB.CLOSED} = "Y" AND {V_JOB.DATE} >= {?FrDate} AND {V_JOB.DATE} <= {?ToDate} THEN False ELSE True This will suppress results where they do not equate to the above conditions. I found your question a little unclear so this answer might not be perfect for your needs, but hopefully it's a shove in the right direction.

Categories : Mysql

ladder-like record selection without looping
You can use recursive CTE to achieve this: http://msdn.microsoft.com/en-us/library/ms186243(v=sql.105).aspx ;WITH RCTE AS ( SELECT * FROM Table1 WHERE A = 3 UNION ALL SELECT t.* FROM RCTE r INNER JOIN Table1 t ON r.B = t.A ) SELECT * FROM RCTE SQLFiddle DEMO

Categories : SQL

"You cannot add or change a record because a related record is required", but related record exists?
Both tables include a text field named LanID. You are using that field in this relationship, which enforces referential integrity: The problem you're facing is due to the Lookup field properties. This is the Row Source: SELECT [LanID].ID, [LanID].LanID FROM LanID ORDER BY [LanID]; But the value which gets stored (the Bound Column property) is the first column from that SELECT statement, which is the Long Integer [LanID].ID. So that number will not satisfy the relationship, which requires results.LanID = [LanID].LanID. You must change the relationship or change the Lookup properties so both reference the same field value. But if it were me, I would just eliminate the Lookup on the grounds that simple operations (such as this) become unnecessarily confusing when Lookup fields

Categories : Ms Access

Active Record date range selection
Assuming that you have an attribute called date_end: t = Time.now.in_time_zone("Bangkok") scope :seven_days, lambda { where("date_start >= ? AND date_start <= ? OR date_start <= ? AND date_end >= ?", t-7.days, t+7.days, t-7.days, t+7.days) }

Categories : Ruby On Rails

Awk: Drop last record separator in one-liner
Instead of egrep, uniq, awk, sed etc, all this can be done in one single awk command: awk -F":" '!($1 in a){l=l $1 ","; a[$1]} END{sub(/,$/, "", l); print l}' /etc/password

Categories : Bash

How to create such form: each db record has selection, with django forms?
I've found a quick solution like this: FRUITS = [ 'apples', 'lemons', 'strawberries', ] # hardcoded like here or from db ANSWERS = [ (0, u''), (1, u'selling'), (2, u'making'), (3, u'both'), ] # hardcoded like here or from db class ProblematicForm(forms.Form): # regluar fields goes here, like: regular_field = forms.CharField() def __init__(self, *args, **kwargs): super(ProblematicForm, self).__init__(*args, **kwargs) for name in FRUITS: # Here we add our problematic fields self.fields[name] = forms.ChoiceField(choices=ANSWERS) This won't give fieldset (like in linked example), but it wouldn't have. That's it o/

Categories : Django

Find Each Record in DB, Identify and Delete part of a String, then resave record to DB
try the below: '_v1363823750/ll9z2kvmtubfkugmtues.png'.split('/').last # => "ll9z2kvmtubfkugmtues.png" or s = '_v1363823750/ll9z2kvmtubfkugmtues.png' s[s.index('/')+1..-1] # => "ll9z2kvmtubfkugmtues.png" or (In this case the below would be the best way to go using File#basename) File.basename('_v1363823750/ll9z2kvmtubfkugmtues.png') # => "ll9z2kvmtubfkugmtues.png"

Categories : Ruby

record not added to model when i call save() on a new record in Ember-Data
I don't know if it's a typo, but the computed property is defined the wrong way and should be like this: App.QuestionController = Ember.ObjectController.extend({ needs: 'userstats', choice: 'controllers.userstats.choice', chosen: function(key, value) { ... }.property('choice') ... }); Inside the property() you should also define properties that trigger the computed property if they change. This way if choice changes the chosen cp will be triggered. Please let me know if it helps.

Categories : Ember Js

SQL query: How to select record from other table where no record exist or count = 0 (conditional)
Use a LEFT JOIN and check for a NULL primary key on the joined table: SELECT StaffDB.* FROM StaffDB LEFT JOIN EmploymentHistory ON StaffDB.SID = EmploymentHistory.SID AND EmploymentHistory.isCurrent = 1 WHERE EmploymentHistory.HistID IS NULL Or use EXISTS - this will possibly be more performant, although not as easily readable (subjective): SELECT * FROM StaffDB WHERE NOT EXISTS (SELECT 1 FROM EmploymentHistory WHERE EmploymentHistory.SID = StaffDB.SID AND EmploymentHistory.isCurrent = 1)

Categories : SQL

How to format node.js sqlite3 record set as a JSON object of record arrays
Based on what I know of JSON I was expecting the whole recordset to be enclosed with curly brackets, and each record to be enclosed with a square bracket. However I'm seeing the opposite. Nope, you have it backward. Database results will be modeled as an array of objects - 1 array represents the results of the entire query, and each object in that array represents a single result record. In JSON, Arrays use square brackets, objects use curly braces (Same as actual JavaScript code).

Categories : Json

Entity Framework Navigational property record moving from one record to another "Wait operation timed out"
Incresing time out time will not resolve this, there is problem with code, Dont use .Tolist(), I have modified above code, try it, may it help you public void MigrateDataForInd(Individu from.Gifts, Individu1 to){ foreach (var item in from.Gifts) { to.Gifts.Add(item); } this.SaveChanges(); } I am considering here Individu is list object which having another list Gift

Categories : C#

Kshell read a file and define record length then strip ascii 20 characters from the end of each record
You can use sed: sed -i -r 's/(.{319})x14(.*)$/12/' file This command will read first 319 character followed by x14 (ASCII 20) and then rest of the line. It will then put back matched group # 1 and matched group # 2. This will leave out x20. -i flag (inline) of sed will save the changed file back. EDIT: Try this sed on AIX: sed 's/(.{319})'$'x14''(.*)$/12/' file > _temp && mv _temp file Final Solution: After investigations (see comments) it was found that file had trailing spaces (hex 20) instead of ASCII 20. Once it was established following solution worked: sed 's/ *$//' file > _temp && mv _temp file

Categories : Linux

flag record as delete instead of deleting the record from mysql table
Easiest way is to add a new BOOL column to the table like enabled with a default value of 1. Then UPDATE table_name SET enabled = 0 when you would like to "delete" the row. And filter out "deleted" rows in your queries like: SELECT * FROM table_name WHERE ... AND enabled = 1

Categories : PHP

error: You cannot add or change a record because a related record is required in table
You apparently have a database Relationship defined between the [LoginLogTable] and [Privileges] tables that is attempting to enforce Referential Integrity. The unknown Manager has no matching row in [Privileges], so when you try to add his (non-existent) UserName into [LoginLogTable] the database won't let you. If you want to log access attempts from unknown Managers then you should disable "Enforce Referential Integrity" for that Relationship. If you don't want to log those attempts then you could do a lookup in the [Privileges] table to see if the UserName exists before proceeding. If the UserName does not exist then you could have the program simply terminate (since you have already told them that they "have entered incorrect credentials").

Categories : C#

rails 3 find single record from active record collection
Simply do this: @customer = Customer.find(customer_id) For example: @customer = Customer.find(1) # => will return the customer with the id equal to 1

Categories : Ruby On Rails

AngularJS pattern for persisting record selection through multiple asynchronous calls?
I think u could maintain a separate collection of selected names. So the next time you filter the list, you just need to lookup in the collection in order to keep the item selected. That you can do by binding some variable (arrSelected) in the controller or you can create a separate service also.

Categories : Angularjs

Is this the proper way to select the previous and next record given an ID for the current record?
Your approach can be rewritten more shortly like this: var ProductID = 10; var Results = (from p in DB.Products where p.ProductID >= ProductID - 1 && p.ProductID <= ProductID + 1 select new Product { ProductID = p.ProductID, ProductTitle = p.ProductTitle, Views = p.Views, }); But note, this will return what you need only if none of the records corresponding to the specified productIDs have been deleted from the Products table.

Categories : C#

Displaying a record in a report when selecting the record ID in a combo box
Use the combo box selection with DoCmd.OpenReport as the WhereCondition option. So if the report's record source table or query includes a numeric field named product_code and your combo box is named cboProductCode ... DoCmd.OpenReport "YourReport", _ WhereCondition:="[product_code] = " & Me.cboProductCode If the field is text rather than numeric, add quotes around the value in the WhereCondition. WhereCondition:="[product_code] = '" & Me.cboProductCode & "'"

Categories : Ms Access

Active Record, count of grandchild association record
In your models you can define a through association. class Town < ActiveRecord::Base has_many :citizens has_many :cars , :through => :citizens end And query like this. @town.cars.count or Town.find("town id").cars.count

Categories : Ruby On Rails

Why do I get this error when inserting a record: duplicate value for a record with unique key
You say: If I specify a value for one of the columns, no matter what the value, it will always throw the [-239 / -100] error. Remember, when you insert into a table, you insert entire rows. Even if you specify a value for only one of the columns, a default value (often NULL) is inserted into the other columns. (There's also a chance I'm misinterpreting what you mean; you might be saying that if you specify values for all columns except one specific one, the INSERT works; if you specify a value for the specific column too, the INSERT always fails. You might need to run SELECT COUNT(*), COUNT(DISTINCT problem_column) FROM <table> to help determine the trouble.) There are no primary keys. There are 10 indexes, none of which are tied to the column that's having the problem.

Categories : Dotnet

Magical Record, CoreData, deleting a record and renumbering
Instead of doing lots of different fetches, just do one fetch to get all of the objects that need to be updated, then iterate over them and perform the updates. Depending on the number if items you can batch the response from the fetch or return the items as faults and then batch the saves.

Categories : Objective C

What is a good way to edit a record in a database and preserve the former record
One method I can think of is to have a lookup table and a data table **DataTable** -DataID -ColumnA -ColumnB -ColumnC -... **LookupTable** -RecordID (This is the important ID for you) -DataID (Key From DataTable) -Modified DateTime (or could be revisionID or something like that to allow for order of change) I think it's pretty self-explanatory from here, to get a new record, you select the most recenlty modfied date (or highest revision number) of the record ID you want, and join it with the dataTable

Categories : Database

Update more record in one query with Active Record in Rails
You should check out the acts_as_list gem. It does everything you need and it uses 1-3 queries behind the scenes. Its a perfect match to use with jquery sortable plugin. It relies on incrementing/decrementing the position (sort_order) field directly in SQL. This won't be a good solution for you, if your UI/UX relies on saving the order manually by the user (user sorts out the things and then clicks update/save). However I strongly discourage this kind of interface, unless there is a specific reason (for example you cannot have intermediate state in database between old and new order, because something else depends on that order). If thats not the case, then by all means just do an asynchronous update after user moves one element (and acts_as_list will be great to help you accomplish tha

Categories : SQL

How to Update a record if it exists otherwise insert a new record in MySQL
DECLARE theCount INT; SELECT COUNT(*) INTO theCount FROM phone_calls WHERE account_id = 8 AND call_code_id = 5 AND status = 1 IF(theCount=0) THEN -- DoLogic; ELSE -- DoSomeOtherLogic; END IF

Categories : Mysql

Trying to maintain a record of data in an excel cell
You cannot squeeze more than one value into a cell. You could write VBA code that could, for example, use the Change event of the worksheet to add a comment to the cell and append the previous value to this comment. Or use this event to copy the previous value to a, perhaps hidden, worksheet. For completeness I should mention that there is a Track Changes feature in Excel but it requires the workbook to be shared - which I do not recommend. Excel is not designed to work with multiple-users.

Categories : Excel

**SOLVED** excel vba get address of cell linked to selection in data valuation drop down
There is really no need to use VBA for this, a simple vlookup will suffice. =VLOOKUP(Sheet1!A1,Sheet2!A1:C20,2,0) Where sheet1!A1 is the data validation cell, Sheet2!A1:C20 is you data range on sheet 2 hopefully with the validation data source in column A, 2 is the column of data you want to return (2=B,3=C), and 0 ensures an exact match.

Categories : Excel

Finding the correct 'record' and using ONLY the data from that record
You could use the following query: SELECT products.* FROM products INNER JOIN (SELECT name, MIN(totalprice) min_price FROM products WHERE quantity>0 GROUP BY name) m ON products.name=m.name AND products.totalprice=min_price In the subquery I calculate the minimum total price for every name, then I'm joining this subquery with the products table, to return only the rows that have the minimum total price for that name. If there are more than one row with the minimum price, they all will be shown. Please see fiddle here.

Categories : SQL

Does not insert as a new record instead replaces a previous record
I do not think the QueryBuilder supports insert queries at this time. Assuming you have an Experiment entity with setters, have you tried public function setExperimentData($name, $type, $description) { $em = $this->getDoctrine()->getManager(); $experiment = new Experiment(); $experiment->setName($name); $experiment->setType($type); $experiment->setDescription($description); $em->persist($experiment); $em->flush(); }

Categories : Symfony2

Delete a record when no corresponding record exists in first table
You can use the DCount Function in Access SQL, and it will work regardless of whether the query is run from within an Access session or externally from VB.Net or other client code. Start with a SELECT query to confirm it targets the correct TableB rows. SELECT b.* FROM TableB AS b WHERE DCount("*", "TableA", "foreignID =" & b.recordID) = 0; In human language, that DCount expression means "Give me the count of TableA rows where the foreignID value matches the recordID value of the current TableB row." You want to identify the TableB rows where that count is zero. Note I assumed numeric data types for both foreignID and recordID. If they are text, you will have to enclose the value of b.recordID in quotes. When you're ready to pull the trigger, convert to a DELETE query. DELET

Categories : Vb.Net

Loop - Extract text for record until the next record
Assuming the leading whitespace is absent from your real files, here's one way using awk: awk 'sub(/^>/,"") { print ++i, $0 } /Grades/ { print i, $NF } /year =/ { print i, "year = ", $NF }' file Results: 1 Tom 1 year = 16 1 10 1 9 2 Ann 2 year = 17 2 10 2 10 2 9

Categories : Perl

rescuing active record : Record Invalid
Couple things. You don't wrap your validates in begin/rescue blocks. So your model should only look like: class Product < ActiveRecord::Base attr_accessible :name, :price, :released_on validates :name, uniqueness: true end And its in the controller where you perform the validation and handle it appropriately. A sample controller might look like: class ProductsController < ApplicationController def create @product = Product.new(params[:product]) if @product.valid? @product.save flash[:notice] = "Product created!" redirect_to(@product) and return else render(:action => :new) end end end And then in your view you might render the actual errors back to the user: # app/views/products/new.html.erb <%= error_messages_for(@product

Categories : Ruby On Rails

select a record from each group if it has given value in column otherwise any one record
Try this one - SELECT VendorID , City FROM Vendor OUTER APPLY ( SELECT City = [text] FROM Mastervalues WHERE EXISTS( SELECT COUNT(*) FROM VendorDetail WHERE VendorID = Vendor.VendorID AND DetailCity = @GivenCityValue AND value = DetailCity ) OR Vendor.City = value ) t

Categories : SQL

Toggle cell editor after record programmatically added to grid in ExtJS
Your row is a model config object, not a model instance, therefore store.indexOf returns -1. Try: var inst = store.add(row)[0]; ... var index = store.indexOf(inst);

Categories : Extjs

Can I open a DataSet record by double-clicking a cell in an unbound DataGridView?
As Chris said in the comments below, in order for the SelectedRows property to be populated, you need to set dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect Otherwise, all you have inside DataGridViewCellEventArgs e is the ColumnIndex of the column which was double clicked. Once selection mode has been set, you may be able to do something such as: public void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { // sender is just dataGridView1 btw.. var selectedRow = dataGridView1.SelectedRows[0]; var primaryKey = selectedRow.Cells["primaryKeyColumnName"].Value; }

Categories : C#

How to update just 1 record in Ember.js with Ember-data? Currently save() and commit() on 1 record actually updates all records of model
You can create a new transaction just for managing that record, using transaction() method of the store. This transaction has the same api as the defaultTransaction. var transaction = this.get('store').transaction(); transaction.add(model) transaction.commit(); Committing this transaction won't affect other changes. See this blog post for further ideas.

Categories : Ember Js

How do I show only one record - the record with smallest value?
When a new user signs up for the course, you need to UPDATE table_name SET AvailableSeats = ... WHERE TrainingID=... AND CourseId=... rather than doing an INSERT. There should only be one row with a unique (DateId, LocationId, CourseId) set of values.

Categories : Asp Net

SQL Server : take 1 to many record set and make 1 record per id
I would first join all your data so that you get the relevant columns: claim_id, ac_name, plan_name, pending tally. Then I would add transform this to get plan name and plan tally on different rows, with a label tying them together. Then it should be easy to pivot. I would tie these together with common table expressions. Here's the query: with X as ( select cc.*, cp.plan_name, pa.pending_tally, rank() over (partition by cc.claim_id order by plan_name) as r from company_claims cc join claim_plans cp on cp.claim_id = cc.claim_id join pending_amounts pa on pa.claim_id = cp.claim_id and pa.plan_id = cp.plan_id ), P as ( select X.claim_id, x.ac_name, x.plan_name as value, 'plan_name_' + cast(r as varchar(max)) as label from x union all

Categories : SQL



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.