Convert LUA table/json to KEY=VAL - json

I need to convert a lua table to KEY=VAL
e.g:
local t1 = {
t0 = "valt0",
t1 = "valt1",
tN = {
t0key = "t0var",
t1key = "t1var",
}
}
to be
t0="valt0", t1="valt1", tN_t0key="t0var", tN_t1key="t1var"
somebody have suggestions?

Make a function that loops through the table, checking if the value is table, in which case feed that table back into the same function. for anything that isn't a table, write it out to your new flattened table. Depending on how likely it is to happen, you might want to check there are no cyclic reference by tracking tables you've already iterated through.

local t1 = {
t0 = "valt0",
t1 = "valt1",
t2 = 42,
tN = {t0key = "t0var",
t1key = "t1var"}
}
local function convert(t)
local arr = {}
local cyclic = {}
local function convert_subtable(t, prefix)
assert(not cyclic[t], 'Cannot convert: cyclic reference detected')
cyclic[t] = true
for k, v in pairs(t) do
k = prefix..tostring(k)
if type(v) == 'number' or type(v) == 'boolean' then
table.insert(arr, k..'='..tostring(v))
elseif type(v) == 'table' then
convert_subtable(v, prefix..k..'_')
else
table.insert(arr, k..'='..string.format('%q', tostring(v)))
end
end
cyclic[t] = nil
end
convert_subtable(t, '')
table.sort(arr)
return table.concat(arr, ', ')
end
print(convert(t1)) --> t0="valt0", t1="valt1", t2=42, tN_t0key="t0var", tN_t1key="t1var"

Related

Matlab-Index in position 1 is invalid. Array indices must be positive integers or logical values

i am pretty new to Matlab and i recently met this issues :-Index in position 1 is invalid. Array indices must be positive integers or logical values.
beta_1 = beta(WMT,RF,SP500)';
beta_2 = beta(SBUX,RF,SP500)';
beta_3 = beta(MSFT,RF,SP500)';
beta_4 = beta(JPM,RF,SP500)';
beta_5 = beta(IBM,RF,SP500)';
beta_6 = beta(HD,RF,SP500)';
beta_7 = beta(DIS,RF,SP500)';
beta_8 = beta(BP,RF,SP500)';
beta_9 = beta(BA,RF,SP500)';
beta_10= beta(NIKE,RF,SP500)';
my function:
function [beta_temp] = beta(stockdata,riskfree, marketdata)
beta_temp = zeros(60,0);
for i = 1:60
temp_stock = stockdata(i:i+59,1);
temp_rf = riskfree(i:i+59,1);
temp_mkt = marketdata(i:i+59,1);
rif = temp_stock - temp_rf;
rmf = temp_mkt - temp_rf;
model = regress(rif,rmf);
beta_temp(i)= model;
end
end

How toPerform a left join in linq pad -

How can I get linq pad to run my left join as show below?
var query =
from s in db.CDBLogsHeaders
.OrderByDescending(g => g.LogDateTime)
from sc in db.StyleColors
.Where(stylecolor => stylecolor.id == (int?)s.StyleColorID)
.DefaultIfEmpty()
from c in db.StyleHeaders
.Where(styleHeader => styleHeader.id == (int?)s.StyleHeaderID)
.DefaultIfEmpty()
select new
{
CDBLogsHeaderId = s.Id,
Merchandiser = c.Merchandiser,
Material = s.Material,
Season = s.Season,
LogsHeaderLogType = s.LogType,
PushFromTo = s.PushFromTo,
LinePlan = s.LinePlan,
QuikRefNumber = s.QuikRefNumber,
PLMOrigin = s.PLM_Origin,
SeasonOriginal = c.SeasonOriginal,
SeasonCurrent = c.SeasonCurrent,
StyleHeaderId = c.Id,
StyleCode = c.StyleCode,
StyleColorsColorCode = sc.ColorCode
};
query.Dump();
The sql that linq pad creates runs perfectly in Management Studio but linq-pad doesn't display any rows and gives this error
InvalidOperationException: The null value cannot be assigned to a
member with type System.Int32 which is a non-nullable value type.
How can I get linqpad to work so I can play with it?
In your anonymous type, make sure your ints are returning ints.
Change
StyleHeaderId = c.Id,
To
StyleHeaderId = (c.Id == null ? 0 : c.Id),

LINQ to SQL Query Where Clause

I would like to create a single query that "adjusts" it's where clause based on a tuple. The first item in the tuple contains a enum value indicating the field in which to filter. The second tuple item is the filter value.
Notice the query below does not work:
var query = from p in db.Categories
where ( QueryBy.Item1 == CategoryFields.Name && p.Name == (string)(QueryBy.Item2) ) ||
( QueryBy.Item1 == CategoryFields.Id && p.Id == (long)(QueryBy.Item2) ) ||
( QueryBy.Item1 == CategoryFields.Description && p.Description == (string)(QueryBy.Item2) ) ||
( QueryBy.Item1 == CategoryFields.SortOrder && p.SortOrder == (int)(QueryBy.Item2) )
select...
if (query.Count() == 1) // ERRORS HERE CONVERSION OF INT
A similar query with only this where clause change will works:
var query = from p in db.Categories
where ( QueryBy.Item1 == CategoryFields.Name && p.Name == (string)(QueryBy.Item2) )
select...
if (query.Count() == 1) // Works HERE
Any idea what could be wrong? Can it be that LINQ where clause perform a short-circuit evaluation and thus the cast of item2 fails? Is there a better way to accomplish my overall goal of adjusting where clause?
Thanks in advance for your help!
LINQ to SQL isn't smart enough to optimize your query and generate it dynamically based on the value of your QueryBy.Item1. It will simply generate a SQL query let SQL server decide this for itself.
When you know that, the error makes sense, since it's impossible for one single value to be castable to both int, long, and string.
In your case you would be better of dynamically generating the right where clause. You can do this with the PredicateBuilder:
IQueryable<Category> query = db.Categories;
var whereClause = PredicateBuilder.False<Category>();
switch (QueryBy.Item1)
{
case CategoryFields.Name:
long id = (string)QueryBy.Item2;
whereClause = whereClause.Or(p => p.Name == name);
break;
case CategoryFields.Id:
string name = (string)QueryBy.Item2;
whereClause = whereClause.Or(p => p.Id == id);
break;
case CategoryFields.Description:
string des = (string)QueryBy.Item2;
whereClause =
whereClause.Or(p => p.Description == des);
break;
case CategoryFields.Id:
string sort = (int)QueryBy.Item2;
whereClause =
whereClause.Or(p => p.SortOrder == sort);
break;
}
query = query.Where(whereClause);

How to write Linq-To-SQL statment which is equal to my following TSQL?

TSQL:-
Update table1
Set Name = 'John',
Address = null
where
ID = 1
LINQ-TO-SQL
var tab = db.Table1.Single(s => s.ID == 3);
tab.Name = DateTime.Now;
tab.Address = null;
db.SubmitChanges();
There isn't a single LINQ to SQL statement for updates. You have to retrieve the object, modify it, then save the changes (code assumes a single row since you have a specific Id):
var entity = context.Table1.Single(t => t.Id == 1);
entity.Name = "John";
entity.Address = "Toronto";
context.SubmitChanges();
using (var dataContext = new MyEntities())
{
var contact = Contacts.Single (c => c.ContactID == 1);
contact.FirstName = 'John';
contact.Address= 'Toronto';
dataContext.SaveChanges();
}

Help to build LINQ query

I have SQL database as follows
alt text http://img97.imageshack.us/img97/5774/dbimage.jpg
Now I want to filter the restaurant_detail table for the parameters:
1. cuisine 2. area
Can you help me to build LINQ query?
I presume you have a model generated either with LINQ to SQL or Entity Framework. Also, I'm assuming foreign key relationships have been set.
var details = db
.Cuisines
.Where(c => c.Cuisine=="something")
.SelectMany(c => c.RestaurantCuisines)
.Select(rc => rc.Restaurant.RestaurantDetails)
.Where(rd => rd.Area=="something")
;
Done with the linq query using following lines of code :
c = from q in dc.restaurant_cuisines
where q.cuisine.cuisine1.Contains(cuisine)
&& q.restaurant.price.ToString().Length == price.Length
select new NearBy { NearById = q.restaurant.id, NearByLongitude = (double)q.restaurant.longitude, NearByLatitude = (double)q.restaurant.latitude };
}
int[] ids = new int[c.Count()];
var lon = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.longtitude;
var lat = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.latitude;
foreach(NearBy n in c)
{
result = calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), n.NearByLatitude, n.NearByLongitude);
ids[i++] = n.NearById;
}
var r = from q in dc.restaurant_details
where 1 == 1 &&
(ids).Contains(q.restaurant_id)
select new Restaurant
{
Restora_id = q.restaurant_id.ToString(),
Name = q.restaurant.name,
Foodtype = q.restaurant.foodtype.foodtype1,
Avg_rating = q.restaurant.avg_rating.ToString(),
Featured = q.restaurant.featured.ToString(),
CuisineList = getCuisine(q.restaurant_id),
Restora_type = q.type,
Distance = Math.Round(calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), (double)q.restaurant.latitude, (double)q.restaurant.longitude), 2),
Newarrival = q.restaurant.newarrival.ToString(),
CountRecord = ids.Length.ToString()
};
var d = r.AsEnumerable().OrderBy(t => t.Distance);
var g = d.Take(recordSize + 10).Skip(recordSize);
return g.ToList();
Please note that above displayed code generated with some changes from the initial requirements.