I have a issue here for the connect mysql.
I have a vps that contain mysql server have a database name is 'tuyendungbg'. it's had table and data in there. But when i'm connect and query to select data, that have error for 'Table 'tuyendungbg.Careers' doesn't exist'.
here is my controller :
[HttpGet("/nganh-nghe/{slug?}")]
public IActionResult Index(string slug, [FromQuery(Name =
"p")] int currentPage, int
pageSize)
{
if (!string.IsNullOrEmpty(slug))
{
var career = _context.Careers.FirstOrDefault(x =>
x.Slug.Equals(slug));
if (career != null)
{
ViewBag.CareerName = career.CareerName;
//var qr = _context.Careers.ToList();
var qr = (from p in
_context.CompanyCareers.Where(x => x.CareerId ==
career.ID)
from b in _context.Companies.Where(x =>
x.Id == p.CompanyId)
from i in
_context.IndustrialAreas.Where(x => x.ID ==
b.IndustrialAreaId).DefaultIfEmpty()
select new CompanyModelView()
{
Id = b.Id,
CompanyName = b.CompanyName,
BasicSalary = b.BasicSalary,
Allowance = b.Allowance,
DateCreate = b.DateCreate,
JobTitle = b.JobTitle,
Src = b.Src,
_IndustrialArea = i,
Address = b.Address,
Slug = b.Slug,
WorkTypes = (from tc in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId == b.Id)
from type in
_context.WorkTypes.Where(x => x.Id
==
tc.TypeId)
select type)
}
).OrderByDescending(x => x.DateCreate).ToList();
// var worktype = (from w in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId
== qr.))
var totalCate = qr.Count();
if (pageSize <= 0) pageSize = 10;
int countPages =
(int)Math.Ceiling((double)totalCate / pageSize);
if (currentPage > countPages)
currentPage = countPages;
if (currentPage < 1)
currentPage = 1;
var pagingModel = new PagingModel()
{
countpages = countPages,
currentpage = currentPage,
generateUrl = (pageNumber) =>
Url.Action(nameof(Index), new
{
p = pageNumber,
pageSize = pageSize
})
};
ViewBag.pagingModel = pagingModel;
ViewBag.totalPost = totalCate;
ViewBag.cateIndex = (currentPage - 1) * pageSize;
var companies = qr.Skip((currentPage - 1) *
pageSize)
.Take(pageSize).ToList();
ViewBag.JobCount = companies.Count();
//Set slider menu
var leftSlider = new LeftSliderModel()
{
Areas = new SelectList(_context.Areas,
nameof(Area.ID),
nameof(Area.NameArea)),
Careers = new SelectList(_context.Careers,
nameof(Career.ID),
nameof(Career.CareerName)),
WorkTypes = _context.WorkTypes.ToList(),
Experiences = _context.Experiences.ToList()
};
ViewBag.LeftSlider = leftSlider;
return View(companies);
}
}
return NotFound();
}
Related
Currently I am trying to display a user's age but it appears as 0 in the page.
This is the View
<div class="col-xs-6 col-sm-4 overview-box">
<table class="table-responsive">
<tbody>
<tr>
<td class="overview-description-wrap">
<span class="overview-description">#translations["Player_Age"]</span>
</td>
<td class="overview-info hidden-xs" style="display:table-cell">
<span class="overview-info-lg">#Model.Age</span>
#if (Model.ShowDateOfBirth)
{
<span class="overview-info-sm">(#Model.BirthDate.ToString("dd.MM.yyyy"))</span>
}
</td>
<td class="overview-info hidden-lg hidden-sm hidden-md">
<span class="overview-info-lg">#Model.Age</span>
<br />
<span class="overview-info-sm">(#Model.BirthDate.ToString("dd.MM.yyyy"))</span>
</td>
</tr>
</tbody>
</table>
</div>
And this is the action that gets the values
public PlayerOverviewViewModel GetPlayerViewModel(int playerId, int sport, int country, int currentPlayerId = 0, int clubId = 0, string color = "")
{
PlayerOverviewViewModel result = new PlayerOverviewViewModel();
Nomenclatures.Sports currentsport = (Nomenclatures.Sports)sport;
Nomenclatures.Countries currentCountry = (Nomenclatures.Countries)country;
var state = LoadPlayerState(playerId, sport);
var finishedMatches = GetFinishedMatches(state, playerId, rankingId: 0).ToList();
var upcomingMatches = GetUpcomingMatches(state, playerId, currentPlayerId, 9).ToList();
var testMatches = ParseUpcomingChallenges(state, upcomingMatches);
var eventInvitations = new List<EventInvitationViewModel>();
var tournamentInvitations = GetTournamentInvitations(currentPlayerId);
var parsedInvitations = ParseTournamentInvitations(state, tournamentInvitations);
eventInvitations.AddRange(parsedInvitations);
var clubLeagueInvitations = GetClubLeagueInvitations(currentPlayerId);
parsedInvitations = ParseClubLeagueInvitations(state, clubLeagueInvitations);
eventInvitations.AddRange(parsedInvitations);
var playerRankings = state.PlayerRankings;
var rankingNames = _data.OrganisationRankings.GetRankingNames(playerRankings.Select(x => x.OrganisationRankingId.Value));
var player = state.CurrentPlayer;
int organizationId = state.CurrentPlayer.HomeClubId ?? 0;
var topRanking = GetPlayerRanking(state);
var playerCareerTopRanking = GetPlayerHighestStanding(state);
var playerCareerTopRankingDate = GetTopPlayerRankingDate(state);
var doubleCareerTopRanking = GetTopDoubleRanking(state, sport, country);
var doubleCareerTopRankingDate = GetTopDoubleRankingDate(state, sport, country);
var homeclub = player.Organisation ?? new Organisation();
var profileImg = _data.Images.PlayerImage(playerId);
var playerCareerWins = GetPlayerCareerWins(playerId, sport, state.Challenges);
var playerCurrentYearWins = GetPlayerCurrentYearWins(playerId, sport, state.Challenges);
var playerCareerLooses = GetPlayerCareerLooses(playerId, sport, state.Challenges);
var playerCurrentYearLosses = GetPlayerCurrentYearLooses(playerId, sport, state.Challenges);
var doublePlayerCurrentYearWins = GetDoublePlayerCurrentYearWins(playerId, sport);
var doublePlayerCareerLooses = GetDoublePlayerCareerLooses(state, sport);
var doubleCareerWins = GetDoubleCareerWins(state, sport);
var doublePlayerCurrentYearLooses = GetDoublePlayerCurrentYearLooses(state, sport);
var careerEventParticipations = GetAllEventsParticipations(playerId, sport, state.Challenges);
var currentYearEventParticipations = GetCurrentYearEventsParticipations(playerId, sport, state.Challenges);
var doubleCareerEventParticipations = GetDoubleCareerEventParticipations(state, sport);
var doubleCurrentYearEventParticipations = GetDoubleCurrentYearEventParticipations(state, sport);
var best3Wins = GetBest3Wins(state, playerId);
var singlePlayerHighestRankingCurrentYear = GetSinglePlayerHighestRankingForCurrentYear(state);
var doublePartnerInvitation = GetDoublePartnerInvitation(playerId);
//var playerUnavalability = this.GetPlayerSchedule(playerId);
string racquetName = player.GetRacket();
string shoesName = player.GetShoes();
result.Id = player.p_id;
result.Name = player.Name;
result.FirstName = player.FirstName;
result.MiddleName = player.MiddleName;
result.LastName = player.LastName;
result.Email = player.UserProfile.Email;
result.Address = player.PersonalInfo.pi_address;
result.BirthDate = player.PersonalInfo.pi_birth;
result.Age = DateHelper.GetAge(result.BirthDate);
result.Gender = player.PersonalInfo.pi_gender == 1 ? "Male" : "Female";
result.UserName = player.UserProfile.UserName;
result.Country = player.PersonalInfo.Country.Name;
result.CountryCode = player.PersonalInfo.Country.Short.ToLower();
result.RankingType = ((Nomenclatures.RankingTypes)topRanking.r_rankingtype).Description();
result.RankingClass = ((Nomenclatures.EventClasses)(topRanking.r_class ?? 1)).Description();
result.Points = topRanking.vPoints;
result.Level = topRanking.r_level ?? 1;
result.Standing = topRanking.vStanding;
result.HomeClub = string.IsNullOrEmpty(homeclub.Name) ? "No home club" : homeclub.Name;
result.ImageUrl = _manager.GetImageUrl(profileImg.img_id, Nomenclatures.ImageType.UserProfilePic);
result.ImageId = profileImg.img_id;
result.Racquet = racquetName;
result.Shoes = shoesName;
result.DominantHand = ((Nomenclatures.DominantHand)player.PersonalInfo.DominantHand).ToString();
result.BackHand = ((Nomenclatures.Backhand)player.PersonalInfo.Backhand).ToString();
result.Facebook = player.PersonalInfo.FacebookProfile;
result.Twitter = player.PersonalInfo.TwitterProfile;
result.WebSite = player.PersonalInfo.WebSite;
result.EmailVisible = player.PersonalInfo.pi_email_v;
result.ShowDateOfBirth = player.PersonalInfo.pi_birth_v || player.p_id == currentPlayerId;
//result.ScheduleDays = playerUnavalability.ScheduleDays;
//result.PlayerUnavalabilityVM = playerUnavalability;
result.PlayerCountryFlag = player.PersonalInfo.Country.Short.ToLower();
result.CareerWins = playerCareerWins;
result.GlobalEventsParticipatedSingles = careerEventParticipations;
result.EventsParticipatedSingles = currentYearEventParticipations;
result.CareerWinLossSingles = playerCareerWins + "-" + playerCareerLooses;
result.WinLossSingles = playerCurrentYearWins + "-" + playerCurrentYearLosses;
result.CareerWinLossDouble = doubleCareerWins + "-" + doublePlayerCareerLooses;
result.WinLossDoubles = doublePlayerCurrentYearWins + "-" + doublePlayerCurrentYearLooses;
result.GlobalEventsParticipatedDoubles = doubleCareerEventParticipations;
result.EventsParticipatedDoubles = doubleCurrentYearEventParticipations;
result.Best3Wins.Items = new List<ICarouselItem>(best3Wins);
result.CareerHighSingles = playerCareerTopRanking == 0 ? "-" : playerCareerTopRanking.ToString();
result.CareerHighDoubles = doubleCareerTopRanking == 0 ? "-" : doubleCareerTopRanking.ToString();
result.CareerHighDateSingles = playerCareerTopRankingDate;
result.CareerHighDateDoubles = doubleCareerTopRankingDate;
result.SinglesHighestRankingCurrentYear = singlePlayerHighestRankingCurrentYear == 0 ? "-" : singlePlayerHighestRankingCurrentYear.ToString();
result.DoublesHighestRankingCurrentYear = ""; //TODO: implement this
result.DoublePlayers = new List<DoublePartnersViewModel>();//TODO: implement this
result.PlayerRankings = playerRankings;
result.RankingNames = rankingNames;
result.CurrentSport = currentsport;
result.RankingCountry = currentCountry;
result.SportNumber = sport;
result.CountryNumber = country;
result.ParticipantType = (int)player.ParticipantType;
result.Class = player.p_class ?? 1;
result.DoubleInvitations = doublePartnerInvitation;
result.LastDonationDate = player.LastDonationDate;
int months;
int.TryParse(ConfigurationManager.AppSettings["donationPeriod"], out months);
result.IsDonated = player.LastDonationDate != null && player.LastDonationDate.Value.AddMonths(months) >= DateTime.UtcNow.Date;
var form = finishedMatches.OrderByDescending(x => x.Date).Take(5).Select(x => x.IsWon ? "W" : "L");
result.Form = form;
result.MatchesSection = new MatchesSectionVM
{
PlayerId = playerId,
CurrentPlayerId = currentPlayerId,
FinishedMatches = finishedMatches,
UpcomingMatches = testMatches,
UpcommingMatchesWatermark = !testMatches.Any(),
EventInvitations = eventInvitations,
FinishedMatchesWatermark = !finishedMatches.Any(),
LeftButtonName = "Confirm",
WatermarkMessage = "You dont have any matches to confirm. Create a challenge or join an event",
ShowButtons = currentPlayerId == playerId,
};
return result;
}
And this is the action that displays everything
[Authorize]
public ActionResult Index(int clubId = 0, string color = "")
{
if (mPlayerID == 0)
{
WebSecurity.Logout();
return RedirectToAction("login", "account", new { clubId, color });
}
var playerViewModel = _service.GetPlayerViewModel(mPlayerID, (int)mSport, (int)mCountry, mPlayerID, clubId, color);
playerViewModel.HasPhoto = _data.Images.PlayerHasPhoto(mPlayerID);
var profileCompletion = GetProfileCompletionPercents(playerViewModel);
playerViewModel.Id = mPlayerID;
playerViewModel.CurrentPlayerId = mPlayerID;
playerViewModel.DonationModel = new PayPalDonationModel(_data, mPlayerID);
playerViewModel.Languages = _cacheService.GetActiveLanguages();
ViewBag.ProfileCompletion = profileCompletion.Item1;
ViewBag.CompletionNext = profileCompletion.Item2;
return View(playerViewModel);
}
The only things that don't appear are the birth date and the user's age. Any suggestions ? Debugger shows that the properties have values in the View.
I have the following select
if ($result = $mysqli->query("SELECT
a.quoteID, a.quoteTitle , a.notes, c.web_path
FROM quotes a
INNER JOIN users_files b on b.user_id = a.quoteID
INNER JOIN files c on c.id = b.file_id ORDER BY quoteID ASC"))
{
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
which gets me information I need.
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/23.pdf"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/22.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/21.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/20.jpeg"},{"quoteID":"2","quoteTitle":"Kaitlin","notes":"Smith","web_path":"\/surplusAdmin3\/upload\/24.jpg"},{"quoteID":"8","quoteTitle":"Bryar2","notes":"Long","web_path":"\/surplusAdmin3\/upload\/17.png"},{"quoteID":"11","quoteTitle":"Avram","notes":"Allison","web_path":"\/surplusAdmin3\/upload\/4.jpg"}]
I now need to get my result as:
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path1":"\/surplusAdmin3\/upload\/23.pdf","web_path2":"\/surplusAdmin3\/upload\/22.jpeg","web_path3":"\/surplusAdmin3\/upload\/21.jpeg","web_path4":"\/surplusAdmin3\/upload\/20.jpeg"}]
I am not looking to re-do the MYSQL statement I just need to create a new array in the format I need.
I have the following code:
var currentQuoteID =0;
var dataChanged = [];
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
console.log(' current quote '+ currentQuoteID + ' = '+ e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
toPush = 'web_path'+fileCount+'"'+':'+'"'+ e["web_path"];
var field = 'web_path'+fileCount;
var data = e["web_path"];
var tempArray = [field,data];
dataChanged.push(toPush);
dataChanged.field = data;
//dataChanged = dataChanged.concat(tempArray);
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});
The result I am getting is :
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image"},"web_path1","/surplusAdmin3/upload/22.jpeg"]
What I need is
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image","web_path1","/surplusAdmin3/upload/22.jpeg"}]
But I cannot workout what I need to do here.
Got it working as follows:
// loop through and add field 'Type' can all be done in one loop.
dataReturned.forEach(function(e){
if (typeof e === "object" ){
e["Type"] = "other";
// console.log('stuff '+e['Type'][i] )
}
});
//loop through and workout the file type
dataReturned.forEach(function(e){
if (typeof e === "object" ){
var ext = e['web_path'].substr(e['web_path'].lastIndexOf('.') + 1);
if ( (ext === 'jpeg' ) || ( ext === 'jpg' )|| ( ext === 'png' )|| ( ext === 'gif' ) || ( ext === 'pdf' ))
{ e["Type"] = "image"; }
//console.log(e['web_path']);
// console.log('stuff '+ JSON.stringify(e))
}
});
// create a new array formated as needed
var currentQuoteID =0;
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
//console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
var field = 'web_path'+fileCount;
var data = webPath+e["web_path"];
var tempArray = [field,data];
dataChanged[arrayRow]['web_path'+fileCount] = data
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});
I've five fields- rate, qty. discount, cgst_percent, cgst_amount.
I want to calculate cgst_amount. The formula should be -
cgst_amount = ((rate*qty - (rate*qty*discount)/100)*cgst_percent)/100
To Start with simple steps, I tried cgst_amount = rate*qty
The javascript part is as below -
<?php
/* start getting the cgst */
$script = <<< JS
function getGst(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "rate") {
fetch1 = index.concat("-qty");
fetch2 = index.concat("-discount");
fetch3 = index.concat("-cgst_rate");
} else if (myString == "qty") {
fetch1 = index.concat("-rate");
fetch2 = index.concat("-discount");
fetch3 = index.concat("-cgst_rate");
} else if (myString == "discount"){
fetch1 = index.concat("-qty");
fetch2 = index.concat("-rate");
fetch3 = index.concat("-cgst_rate");
} else {
fetch1 = index.concat("-qty");
fetch2 = index.concat("-rate");
fetch3 = index.concat("-discount");
}
temp1 = $("#productsales-"+fetch1+"").val();
temp2 = $("#productsales-"+fetch2+"").val();
temp3 = $("#productsales-"+fetch3+"").val();
//alert (temp2);
if (!isNaN(temp1) && temp1.length != 0) {
ratevar = temp1;
}
if (isNaN(temp2) || temp2.length != 0) {
discvar = temp2;
}
if (isNaN(temp3) || temp3.length != 0) {
cgstpercentvar = temp3;
}
qtyvar = item.val();
if (isNaN(qtyvar) || qtyvar.length == 0) {
qtyvar = 0;
}
//alert (qtyvar);
if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
cgstvar = (parseFloat(qtyvar) * parseFloat(ratevar)).toFixed(2);
}
cgstField = "productsales-".concat(index).concat("-cgst_amount");
$("#"+cgstField+"").val(cgstvar);
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the cgst */
?>
Whn I key in rate and qty I get multiply of them as output in cgst_amount textbox. No problem so far. As soon as I key in anything in discount,the same texts are getting written in cgst_amount as output.
I'm not quite sure about the javascript part.
It is an extension of - Calculate from 3 inputfield in dynamic form yii2 and Calculate 3 fields and display the result in the 4th in yii2 dynamic form
If I work on the full formula, the javascript calculation part becomes - cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);
And the example is as below image -
The actual result should have been - 5.43. Instead I'm getting -0.00
You meshed up with fields and variables, i have updated a script a bit :
function getGst(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
quantity = index.concat("-qty");
rate = index.concat("-rate");
discount = index.concat("-discount");
cgstRate = index.concat("-cgst_rate");
temp1 = $("#productsales-"+quantity+"").val();
temp2 = $("#productsales-"+rate+"").val();
temp3 = $("#productsales-"+discount+"").val();
temp4 = $("#productsales-"+cgstRate+"").val();
if (isNaN(temp1) || temp1.length != 0) {
qtyvar = temp1;
}
if (!isNaN(temp2) && temp2.length != 0) {
ratevar = temp2;
}
if (isNaN(temp3) || temp3.length != 0) {
discvar = temp3;
}
if (isNaN(temp4) || temp4.length != 0) {
cgstpercentvar = temp4;
}
if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);
}
cgstField = "productsales-".concat(index).concat("-cgst_amount");
$("#"+cgstField+"").val(cgstvar);
}
I have written some code, and now I want to implement this on CUDA GPU but I'm new to synchronization. Below I'm presenting the code and I want to that LOOP1 to be executed by all threads (hence I want to this portion to take advantage of CUDA and the remaining portion (the portion other from the LOOP1) is to be executed by only a single thread.
do{
point_set = master_Q[(*num_mas) - 1].q;
List* temp = point_set;
List* pa = point_set;
if(master_Q[num_mas[0] - 1].max)
max_level = (int) (ceilf(il2 * log(master_Q[num_mas[0] - 1].max)));
*num_mas = (*num_mas) - 1;
while(point_set){
List* insert_ele = temp;
while(temp){
insert_ele = temp;
if((insert_ele->dist[insert_ele->dist_index-1] <= pow(2, max_level-1)) || (top_level == max_level)){
if(point_set == temp){
point_set = temp->next;
pa = temp->next;
}
else{
pa->next = temp->next;
}
temp = NULL;
List* new_point_set = point_set;
float maximum_dist = 0;
if(parent->p_index != insert_ele->point_index){
List* tmp = new_point_set;
float *b = &(data[(insert_ele->point_index)*point_len]);
**LOOP 1:** while(tmp){
float *c = &(data[(tmp->point_index)*point_len]);
float sum = 0.;
for(int j = 0; j < point_len; j+=2){
float d1 = b[j] - c[j];
float d2 = b[j+1] - c[j+1];
d1 *= d1;
d2 *= d2;
sum = sum + d1 + d2;
}
tmp->dist[tmp->dist_index] = sqrt(sum);
if(maximum_dist < tmp->dist[tmp->dist_index])
maximum_dist = tmp->dist[tmp->dist_index];
tmp->dist_index = tmp->dist_index+1;
tmp = tmp->next;
}
max_distance = maximum_dist;
}
while(new_point_set || insert_ele){
List* far, *par, *tmp, *tmp_new;
far = NULL;
tmp = new_point_set;
tmp_new = NULL;
float level_dist = pow(2, max_level-1);
float maxdist = 0, maxp = 0;
while(tmp){
if(tmp->dist[(tmp->dist_index)-1] > level_dist){
if(maxdist < tmp->dist[tmp->dist_index-1])
maxdist = tmp->dist[tmp->dist_index-1];
if(tmp == new_point_set){
new_point_set = tmp->next;
par = tmp->next;
}
else{
par->next = tmp->next;
}
if(far == NULL){
far = tmp;
tmp_new = far;
}
else{
tmp_new->next = tmp;
tmp_new = tmp;
}
if(parent->p_index != insert_ele->point_index)
tmp->dist_index = tmp->dist_index - 1;
tmp = tmp->next;
tmp_new->next = NULL;
}
else{
par = tmp;
if(maxp < tmp->dist[(tmp->dist_index)-1])
maxp = tmp->dist[(tmp->dist_index)-1];
tmp = tmp->next;
}
}
if(0 == maxp){
tmp = new_point_set;
aloc_mem[*tree_index].p_index = insert_ele->point_index;
aloc_mem[*tree_index].no_child = 0;
aloc_mem[*tree_index].level = max_level--;
parent->children_index[parent->no_child++] = *tree_index;
parent = &(aloc_mem[*tree_index]);
tree_index[0] = tree_index[0]+1;
while(tmp){
aloc_mem[*tree_index].p_index = tmp->point_index;
aloc_mem[(*tree_index)].no_child = 0;
aloc_mem[(*tree_index)].level = master_Q[(*cur_count_Q)-1].level;
parent->children_index[parent->no_child] = *tree_index;
parent->no_child = parent->no_child + 1;
(*tree_index)++;
tmp = tmp->next;
}
cur_count_Q[0] = cur_count_Q[0]-1;
new_point_set = NULL;
}
master_Q[*num_mas].q = far;
master_Q[*num_mas].parent = parent;
master_Q[*num_mas].valid = true;
master_Q[*num_mas].max = maxdist;
master_Q[*num_mas].level = max_level;
num_mas[0] = num_mas[0]+1;
if(0 != maxp){
aloc_mem[*tree_index].p_index = insert_ele->point_index;
aloc_mem[*tree_index].no_child = 0;
aloc_mem[*tree_index].level = max_level;
parent->children_index[parent->no_child++] = *tree_index;
parent = &(aloc_mem[*tree_index]);
tree_index[0] = tree_index[0]+1;
if(maxp){
int new_level = ((int) (ceilf(il2 * log(maxp)))) +1;
if (new_level < (max_level-1))
max_level = new_level;
else
max_level--;
}
else
max_level--;
}
if( 0 == maxp )
insert_ele = NULL;
}
}
else{
if(NULL == temp->next){
master_Q[*num_mas].q = point_set;
master_Q[*num_mas].parent = parent;
master_Q[*num_mas].valid = true;
master_Q[*num_mas].level = max_level;
num_mas[0] = num_mas[0]+1;
}
pa = temp;
temp = temp->next;
}
}
if((*num_mas) > 1){
List *temp2 = master_Q[(*num_mas)-1].q;
while(temp2){
List* temp3 = master_Q[(*num_mas)-2].q;
master_Q[(*num_mas)-2].q = temp2;
if((master_Q[(*num_mas)-1].parent)->p_index != (master_Q[(*num_mas)-2].parent)->p_index){
temp2->dist_index = temp2->dist_index - 1;
}
temp2 = temp2->next;
master_Q[(*num_mas)-2].q->next = temp3;
}
num_mas[0] = num_mas[0]-1;
}
point_set = master_Q[(*num_mas)-1].q;
temp = point_set;
pa = point_set;
parent = master_Q[(*num_mas)-1].parent;
max_level = master_Q[(*num_mas)-1].level;
if(master_Q[(*num_mas)-1].max)
if( max_level > ((int) (ceilf(il2 * log(master_Q[(*num_mas)-1].max)))) +1)
max_level = ((int) (ceilf(il2 * log(master_Q[(*num_mas)-1].max)))) +1;
num_mas[0] = num_mas[0]-1;
}
}while(*num_mas > 0);
If you want a single kernel to execute parts of its code on only a single thread within a block, use an if statement to execute a portion of code for only a single threadIdx and then barrier synchronize. Perhaps you should take a stab at writing a kernel and posting that for people to look at.
I am able to do this query just fine with the test repository which is In Memory
when I move to the sqlRepository I get this error
Unsupported overload used for query operator 'Intersect'.
I assume it is because sending the query to sql is too complicated for Linq to Sql to do when it is not dealing with the Model.Model.Talent Type. Is there some way around doing a search like this with Intersect?
thanks
public class TalentService : ITalentService
{
ITalentRepository _repository = null;
private IQueryable<Talent> BasicSearch(string searchExpression)
{
IQueryable<Talent> t;
string[] sa = searchExpression.Trim().ToLower().Replace(" ", " ").Split(' ');
t = _repository.GetTalents();
foreach (string s in sa)
{
t = t.Intersect(AddBasicSearch(s), new TalentComparer());
}
return t;
}
private IQueryable<Talent> AddBasicSearch(string s)
{
IQueryable<Talent> t2 = _repository.GetTalents()
.Where(tal => tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
return t2;
}
}
public class SqlTalentRepository:ITalentRepository
{
public IQueryable<Model.Model.Talent> GetTalents()
{
var tal = from t in _db.Talents
let tLanguage = GetTalentLanguages(t.TalentID)
where t.Active == true
select new Model.Model.Talent
{
Id = t.TalentID,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages())
};
return tal ;
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
public static class TalentExtensions
{
public static string ToLanguageNameString(this IEnumerable<TalentLanguage> source
, IEnumerable<Model.Model.Language> allLanguages)
{
StringBuilder sb = new StringBuilder();
const string del = ", ";
foreach (TalentLanguage te in source)
{
sb.AppendFormat("{0}{1}", allLanguages
.Where(x => x.LanguageId == te.LanguageID).SingleOrDefault().LanguageName, del);
}
string sReturn = sb.ToString();
if (sReturn.EndsWith(del))
sReturn = sReturn.Substring(0, sReturn.Length - del.Length);
return sReturn;
}
}
public class TestTalentRepository : ITalentRepository
{
IList<Talent> talentList;
public TestTalentRepository(ILanguageRepository _LanguageRepo )
{
this._LanguageRepository = _LanguageRepo;
talentList = new List<Talent>();
talentLanguageList = new List<TalentLanguage>();
for (int i = 0; i < 55; i++)
{
var t = new Talent();
t.Id = i;
t.FirstName = (i % 3 == 0) ? "Ryan" : "Joe";
t.LastName = (i % 2 == 0) ? "Simpson" : "Zimmerman";
AddLanguagesToTestTalent(i, t);
talentList.Add(t);
}
}
private void AddLanguagesToTestTalent(int i, Talent t)
{
IList<Language> Languages = _LanguageRepository.GetLanguages().ToList<Language>();
Random rLanguages = new Random();
int numLanguages = rLanguages.Next(Languages.Count - 1) + 1;
t.TalentLanguages = new LazyList<TalentLanguage>();
for (int j = 0; j < numLanguages; j++)
{
var x = new TalentLanguage();
x.TalentLanguageId = j;
x.TalentId = i;
Random random2 = new Random();
int rand = random2.Next(Languages.Count);
var y = Languages.ElementAtOrDefault(rand);
Languages.RemoveAt(rand);
x.Language = y;
x.LanguageId = y.LanguageId;
t.TalentLanguages.Add(x);
}
}
public IQueryable<Talent> GetTalents()
{
var ts = from t in this.talentList
let tLanguage = GetTalentLanguages(t.Id)
where t.Active == true
select new Model.Model.Talent
{
Id = t.Id,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages()),
City = t.City,
};
return ts.AsQueryable<Model.Model.Talent>();
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
If you're trying to find entries which match all of those criteria, you just need multiple where clauses:
private static readonly char[] SplitDelimiters = " ".ToCharArray();
private IQueryable<Talent> BasicSearch(string search)
{
// Just replacing " " with " " wouldn't help with "a b"
string[] terms = search.Trim()
.ToLower()
.Split(SplitDelimiters,
StringSplitOptions.RemoveEmptyEntries);
IQueryable<Talent> query = _repository.GetTalents();
foreach (string searchTerm in terms)
{
query = AddBasicSearch(query, searchTerm);
}
return query;
}
private IQueryable<Talent> AddBasicSearch(IQueryable<Talent> query, string s)
{
return query.Where(tal =>
tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
}