id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23530600
|
Controller
[HttpPost]
public JsonResult UploadExcel(FIRS firs, HttpPostedFileBase FileUpload)
{
List<string> data = new List<string>();
if (FileUpload != null)
{
// tdata.ExecuteCommand("truncate table OtherCompanyAssets");
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
string targetpath = Server.MapPath("~/FileUpload/");
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
var connectionString = "";
if (filename.EndsWith(".xls"))
{
connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
}
else if (filename.EndsWith(".xlsx"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
}
var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "ExcelTable");
DataTable dtable = ds.Tables["ExcelTable"];
string sheetName = "Sheet1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var firsRecords = from a in excelFile.Worksheet<FIRS>(sheetName) select a;
foreach (var a in firsRecords)
{
try
{
if (a.RC_NUMBER != "" && a.TIN_NUMBER != "" && a.COMPANY_NAME != "" && a.TCC_NUMBER != "")
{
FIRS TU = new FIRS();
var helper = new FirsServiceClient();
TU.RC_NUMBER = a.RC_NUMBER;
TU.TIN_NUMBER = a.TIN_NUMBER;
TU.COMPANY_NAME = a.COMPANY_NAME;
TU.TCC_NUMBER = a.TCC_NUMBER;
//db.FIRS.Add(TU);
//_firsService.AddFirs(TU);
//svc.SaveFirsImportData(TU);
//helper.SaveFirsImportData(TU);
TU.ACTION_STATUS = 1;
TU.CREATED_DATE = DateTime.Now;
_firsService.AddFirs(firs);
}
else
{
data.Add("<ul>");
if (a.RC_NUMBER == "" || a.RC_NUMBER == null) data.Add("<li> RC Number is required</li>");
if (a.TIN_NUMBER == "" || a.TIN_NUMBER == null) data.Add("<li>RC Number is required</li>");
if (a.COMPANY_NAME == "" || a.COMPANY_NAME == null) data.Add("<li>Company Name is required</li>");
if (a.TCC_NUMBER == "" || a.TCC_NUMBER == null) data.Add("<li> TCC Number is required</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
//deleting excel file from folder
if ((System.IO.File.Exists(pathToExcelFile)))
{
System.IO.File.Delete(pathToExcelFile);
}
return Json("success", JsonRequestBehavior.AllowGet);
}
else
{
//alert message for invalid file format
data.Add("<ul>");
data.Add("<li>Only Excel file format is allowed</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
data.Add("<ul>");
if (FileUpload == null) data.Add("<li>Please choose Excel file</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
Service.svc
public void AddFirs(FIRS firs)
{
_firsManager.AddFirs(firs);
}
When upload excel is click from view, it calls the controller public JsonResult UploadExcel(FIRS firs, HttpPostedFileBase FileUpload) Then, the controller reference the service AddFirs(FIRS firs) to save data to the database.
Why am I getting this error, and how can I resolve it.
Then, when I tried to debug by trapping the error I got this.:
I then used quickwatch. It tells me Some fields (PropertyName) like RC_NUMBER, tin_number, TCC_NUMBER are required.
I checked those fields in Excel that I tried to import, they are not empty. Please what do I do?
| |
doc_23530601
|
route.post('/dashboard/upload',ensureAuthenticated,(req,res) => {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
// console.log(files.file_thumbnail.type);
if(files.file_thumbnail.type !== 'image/jpeg' ){
console.log("File is not image");
res.render('upload');
} else {
var oldpath = files.file_thumbnail.path;
var newpath = '../uploads/' + files.file_thumbnail.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
// console.log(fields.file_name);
console.log('File uploaded successfully!');
res.render('upload');
var newfile = new file({
caption : fields.caption,
file_thumbnail : newpath
});
newfile.save()
.then(chllange => {
console.log("New File Added");
})
.catch(err => console.log(err));
});
}
});
});
here is my show image code
route.get('/dashboard/files',(req,res) => {
file.find({},['file_thumbline','caption'],{sort:{_id:-1}}, (err, data) => {
console.log(data);
res.render('files', {file: data});
});
});
and here is my image html code
<img src="<%= file.file_thumbnail %>" alt="Image">
<p><%= file.caption %></p>
error is after render code it shows alter text and in inspect element shows img src(unknown)
Edit
in show image code in
console.log(data);
it returnes all json data but when I get
console.log(data.caption);
it returns undefined
A:
Edit in show image code in
console.log(data);
it returnes all json data but when I get
console.log(data.caption);
it returns undefined
You are receiving an array from mongo. So if you want to access it you need to select an item ie. data[0].caption
A: Dont u have to close it in the image tag like that?
<img src="<%= file.file_thumbnail %>" alt="Image">
| |
doc_23530602
|
I have successfully run through the Apache tutorials and have now created my own collection and indexed my files.
Whilst the documentation is extensive I cannot find if there is a way to query all fields, but only return the fields that the search string/query was found in.
For example, if I have a file:
Filename: Weekly Report For Company X.pdf
Associated / indexed meta-data:
"id":"S:\\Weekly Reports\\JAN\\Weekly Report For Company X.PDF",
"date":["2017-11-02T19:14:07Z"],
"pdf_pdfversion":[1.6],
"company":["Microsoft"],
"access_permission_can_print_degraded":[true],
"subject":["weekly report; reports; weekly"],
"contenttypeid":["0x010100F29081EC69D67544A17D8172A093E42E"],
"dc_format":["application/pdf; version=1.6"],
If I query for "Weekly Report" I only want to return the 'id' and 'subject' fields as these are the only fields that contain the actual queried values. If other fields contained the string, I would want them returned too.
I'm leaning towards 'it cannot be done' (but hope I am wrong) as I liken it to a SQL query. It has to know what fields to return in the SQL statement and does not remove fields based on no matching string.
Since I don't know the matched fields before running the query I cannot use the filter list option at the point of executing the query.
Is this possible?
A: While this may be not precisely what you want, but you could mimic similar behaviour with highlighting.
All you need to do - is to create dismax query with qf being all fields that you have (e.g qf=id,subject,company)
Then you need to request highlighting, request all fields for it (hl.fl=id,subject,company) and enable hl.requireFieldMatch which would force Solr to return only fields which were matched for the query.
In this case you will have a highlighting section, that will contain ids of the matched documents and only highlighted contents of matched fields
| |
doc_23530603
|
1.'putText': identifier not found.
2.identifier "putText" is undefined.
My code:
putText(image1,"ff",cv::Point(25, 50), 30, CV_RGB(0, 0, 255));
Can someone explain me why?
A: Since you didn't shared any actual snippets I will just post you the snippet that should get you on top of things, given that you already have OpenCV matrix loaded and ready for writing the test.
#include <opencv/cv.h>
using namespace cv;
// ...
Mat img;
double scale = 0.45;
Point org = cvPoint(img.cols / 7, img.rows / 14);
putText(img, "sometext", org, FONT_HERSHEY_SIMPLEX, scale, CV_RGB(0, 255, 255), 1, CV_AA);
The declaration of function itself is located in "opencv2/core/core_c.h"
A: I'm guessing you're using OpenCV 3.x instead of OpenCV 2.x...
You need to add this:
#include "opencv2/opencv.hpp"
putText has been moved to the imgproc module in OpenCV 3.x
| |
doc_23530604
|
I would like to convert it into Posix timestamp (IE: seconds since the epoch)
Using this online converter (https://www.epochconverter.com/) I know the answer is 1512333480
But when I do the following code, the result is off by 1800 seconds -- 30 minutes:
>>> temp_time1 = datetime.datetime.strptime('2017-12-03T20:38:00.971261Z', '%Y-%m-%dT%H:%M:%S.%fZ')
>>> ctime = int(datetime.datetime(temp_time1.year,
temp_time1.month,
temp_time1.day,
temp_time1.hour,
temp_time1.minute,
temp_time1.second,
temp_time1.microsecond,
pytz.timezone('Europe/London')).strftime('%s'))
>>> print ctime
1512351480
Anyone know what I'm missing here??
A: You created a new timestamp and put it in the Europe/London timezone. That is not the same thing as UTC. The Europe/London timezone from the PyTZ database includes historical offsets, and those affect how datetime.datetime() interprets the timezone.
Just use the datetime.timestamp() method on the datetime object you already parsed from the string:
>>> import datetime
>>> temp_time1 = datetime.datetime.strptime('2017-12-03T20:38:00.971261Z', '%Y-%m-%dT%H:%M:%S.%fZ')
>>> temp_time1.timestamp()
1512333480.971261
Your original temp_time1 datetime object is timezone agnostic, so the timestamp() object already assumes no timezone conversion has to take place.
If you must apply the Europe/London timezone first for whatever reason, then at least use the timezone.localize() method to get the right offset applied:
>>> import pytz
>>> pytz.timezone('Europe/London').localize(temp_time1)
datetime.datetime(2017, 12, 3, 20, 38, 0, 971261, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)
>>> pytz.timezone('Europe/London').localize(temp_time1).timestamp()
1512333480.971261
See How to make an unaware datetime timezone aware in python
For Python 2 and Python 3.0, 3.1 or 3.2, where datetime.timestamp() is not available, subtract the epoch date:
>>> (temp_time1 - datetime.datetime(1970, 1, 1)).total_seconds()
1512333480.971261
Add in the UTC timezone when dealing with timezone-aware datetime instances:
>>> (pytz.timezone('Europe/London').localize(temp_time1) - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
1512333480.971261
Combined into a function:
def datetime_to_timestamp(dt, epoch=datetime.datetime(1970, 1, 1)):
if dt.tzinfo is not None:
epoch = pytz.utc.localize(epoch)
return (dt - epoch).total_seconds()
| |
doc_23530605
|
In next lines, if the user doesn't want to listen again to the music, I will add a list of music and make him choose, and, in the future, I want put some commands for skip to the next music and something about that.
P1 = str(input('wanna again? (Y/N)'))
def DEF1():
if P1 == ('Y'):
P2 = str(input('do you know what is it? (Y/N)'))
if P2 == ('Y'):
P3 = str(input('what is it?'))
print(P3)
if P2 == ('N'):
print('this is a game sound!')
if P1 == ('N'):
print('that is it')
def DEF2():
while:
playsound.playsound('', True) #a music link
if __name__ == '__main_':
Process(target=DEF1).start()
Process(target=DEF2).start()
The thing is: i want to start two process (DEF1 and DEF2) at the same time , it's a 'while' and a 'if' function, DEF1 it's some questions that i want to do for the user of the program, and DEF2 it's a music that repeat if the 'while
A: If I'm understanding correctly and you want your second method to play another sound or song based on the value of P3, you need to return a value from DEF1 based on user selection.
So in addition to 'print(P3)', you want to include 'return P3'.
Then you call DEF1 from within DEF2, assigning the return to a variable, for example:
song = DEF1()
The variable 'song' then holds the value of the answer to the question: 'what is it?'
What this does is allow DEF2 to call DEF1 with all of the questions and answers.
DEF2 then uses the return from DEF1 to determine which song to play. So instead of a while statement, you probably want an if statement (your while statement wouldn't have worked anyway since it doesn't have a condition for the loop).
Now when you call DEF2, DEF2 in turn, will call DEF1 for you.
| |
doc_23530606
|
What is the right way to store and update the order of such objects?
A: Use react state of the component that is a container of the cards, unless the order somehow affects other components in the app, in that case store the order in redux store as well.
On drop event if you need to sync the order with a database right away, use async action(thunk or saga) with the updated order.
For reference there is an advice from Dan Abramov for when to use react state vs redux store.
https://github.com/reactjs/redux/issues/1287#issuecomment-175351978
| |
doc_23530607
|
$connection = mysql_connect($hostname, $username, $password);
if (!$connection) {die('Could not connect: ' . mysql_error());}
mysql_select_db($database, $connection);
I know it's not a good idea to put them directly in the script that is querying the database. However, some say that you should put the connection details in a separate PHP script and include that script to connect.
Is there a more secure place to put the connection details?
A: The usual practice is to put them into a separate file, and put that outside the web root. See this answer for details.
A: You may want to put it in a directory that is not in the webapp hierarchy, to prevent a browser from having any chance to access it.
Depending on your level of paranoia, you could write a webservice that is behind a firewall, and call for the credentials, but that may be overkill.
It would help if we understood your architecture, is it just php script goes to database, then the first suggestion would be best, if you have firewalls, for example, then you will have more options.
A: If your OS has reasonable security features, it doesn't matter so much where, as long as the file belongs to a group with the minimum possible rights.
| |
doc_23530608
|
How can I split into these strings
s1 = A, s2 = B, s3 = C
I try
string str = "A|B|C";
string s3 = str.Substring(str.LastIndexOf("|") + 1); //get the s3
But how can I get the s1 and s2? I forgot I use C#
A: Almost all languages have the split functionality with this signature:
string.split(delimeter, optional_number_of_splits)
returns an array
For example in C#:
string myStr = "A|B|C";
string[] parts = myStr.Split('|');
A: The splitting can be done as follows.
string[] Parts
= str.Split(new string[]{"|"}, StringSplitOptions.RemoveEmptyEntries).ToArray();
| |
doc_23530609
|
So does intelliJ have some way of setting an alternative JAVA_HOME dir like eclipse does in its ini?
A: The other answers will not work for 64bit versions. Jetbrains have actually documented this quite well. From https://intellij-support.jetbrains.com/hc/en-us/articles/206544879-Selecting-the-JDK-version-the-IDE-will-run-under:
Java 8
Please be aware that Java 8 is required to run IntelliJ IDEA starting from version 16 on all the supported platforms. It also applies to the lightweight IDEs released from the same branch (144+).
Windows
JDK is bundled with all the product installers and it's recommended that you will use the provided JDK version unless there are any specific issues.
32-bit JDK is located in IDE_HOME\jre directory and is used by the 32-bit product executable.
To run the IDE in 64-bit mode you will need to download and install 64-bit JDK (not JRE) distribution and install it yourself. IDE will find and use it from the registry when you run the 64-bit .exe file (available only for IntelliJ IDEA right now, other products can use the .bat file to run in 64-bit mode).
<product>.exe uses this JDK search sequence:
*
*IDEA_JDK / PHPSTORM_JDK / WEBIDE_JDK / PYCHARM_JDK / RUBYMINE_JDK / CLION_JDK / DATAGRIP_JDK environment variable (depends on the
product, WEBIDE_JDK applies to both WebStorm and PhpStorm before
version 2016.1)
*..\jre directory
*system Registry
*JDK_HOME environment variable
*JAVA_HOME environment variable
idea64.exe uses this JDK search sequence:
*
*IDEA_JDK_64 environment variable
*..\jre64 directory
*system Registry
*JDK_HOME environment variable
*JAVA_HOME environment variable
It’s also possible to start the IDE with .bat file located in the bin directory, it uses the following JDK search sequence:
*
*IDEA_JDK / PHPSTORM_JDK / WEBIDE_JDK / PYCHARM_JDK / RUBYMINE_JDK / CLION_JDK / DATAGRIP_JDK environment variable (depends on the product)
*..\jre directory
*JDK_HOME environment variable
*JAVA_HOME environment variable
Environment variable must point to the JDK installation home directory, for example:
c:\Program Files (x86)\Java\jdk1.8.0_66
The actual JDK version used by the IDE can be verified in Help | About dialog (open any project to access the menu).
Define IDEA_JDK / PHPSTORM_JDK / WEBIDE_JDK / PYCHARM_JDK / RUBYMINE_JDK / CLION_JDK / DATAGRIP_JDK variable depending on the product to override the default version from IDE_HOME\jre.
Use Rapid Environment Editor to add/edit the variables, it will detect incorrect paths.
Linux
Starting from IntelliJ IDEA 16 and the most recent versions of the lightweight IDEs, we are bundling custom JRE with Linux distributions, just like we've been doing for Mac. Our custom JRE is based on OpenJDK and includes the most up to date fixes to provide better user experience on Linux (like font rendering improvements and HiDPI support).
Boot JDK path is stored in the .jdk file located in the config folder. It can be modified either via the Change IDE boot JDK action or by manually editing .jdk file (if you can't start the IDE to change it via an action).
It's recommended to use the bundled JRE (if available). In case you have any issues with the bundled version, you can switch to the latest version of Oracle JDK or OpenJDK available for your system (OpenJDK 1.6 is not supported, please use 1.7 or later versions, JDK 1.8 is recommended and older Java versions are not supported starting from IntelliJ IDEA 16).
Check bin/.sh file for the JDK search order, it's similar to Windows in terms of the environment variable names. It's a legacy way to adjust the boot jdk, use it for older product versions. Consider using .jdk file instead (see above), so that your modifications can survive IDE updates/re-installation.
Check this answer if you need to install the JDK manually on Linux.
If you have problems with ugly fonts, please see this thread comments for the tips.
Help | About will show the actual JDK version.
Mac OS X
Our latest IDE versions come with the bundled custom JDK 8 which contains the fixes for most known OpenJDK bugs. Should you need to use a different Java version, please refer to https://blog.jetbrains.com/idea/2015/05/intellij-idea-14-1-4-eap-141-1192-is-available/.
If you override IDE JDK version, its path is stored in .jdk file located in the config folder (idea.jdk for IntelliJ IDEA, pycharm.jdk for PyCharm, etc). Delete this file or change the path inside the file manually in case IDE no longer starts and you can't change it via the menu.
If IDE doesn't start and this file doesn't exist, create it manually and specify Java path to use (Java home location), for example:
/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk
A: In IntelliJ you can specify which SDK to use at project level. go to "File" --> "Project Structure" --> SDKs (list on the left) and you can add/remove paths to different SDKs
Other solution: If you use Windows then I think you can specify JAVA_HOME as system property just for IntelliJ. If you use Linux the solution is similar.
A: I use IDEA_JDK for this purpose (on linux).
I believe it is STUDIO_JDK for android studio.
For more information on this and other jetbrains IDE's, see https://intellij-support.jetbrains.com/hc/en-us/articles/206544879-Selecting-the-JDK-version-the-IDE-will-run-under
A: A reminder - once you set up a JAVA_HOME env variable in Windows, you need to close all your IntelliJ apps, and then start again. Otherwise, there might be troubles with accessing JAVA_HOME variable.
| |
doc_23530610
|
I have tried:
"properties": {
"userId": {"$ref": "#/definitions/userId"},
"beacons": {
"type": "array",
"items": { "$ref": "#/definitions/beaconSchema" }
}
}
The userId part is parsed with #/definitions/userId. The list items, however, ignore the #/definitions/beaconSchema and allow any old junk in it.
How can I use a JSON schema definition to parse all items in a JSON array?
A: The schema fragment you posted is correct. I suggest you look for typos in the $ref path and definitions property name. If you don't find the problem there, try posting more of the schema.
| |
doc_23530611
|
My session start:
<?php
session_start();
$hulplijn = $_SESSION['hulplijn'];
$_SESSION['hulplijn'] = $hulplijn;
?>
My button that disables the button once it is clicked:
<script>
function get_accept(input)
{
alert(input);
}
function changeText(el)
{
el.innerHTML = 'Al gebruikt!';
}
</script>
<button onclick="changeText(this); get_accept('<?php echo $hulplijn;?>'); this.disabled='disabled';">Hulplijn</button>
Anyone that can help me out here? Would be much appreciated!
A: So the thing I wanted to do isn't possible, too bad.. Instead I was better of just allowing users to use the button more than once.
| |
doc_23530612
|
<script type="text/javascript">
var offset = new Date().getTimezoneOffset(); //get client timezone differance with UTC
offset *= -1; // change sign
offset *= 60; // convert into second
console.log(offset);
</script>
<?php
echo "<br/><br/>";
$a = "<script>document.write(offset)</script>"; //getting value in string
echo $a; // this works and print : 19800
echo "<br/>";
settype($a, "integer");
echo $a; // print 0
?>
A: You set some HTML (with JavaScript) code in variable $a. This is not a valid number! So PHP can't convert the not numeric string into a number / integer:
$a = "<script></script>";
var_dump($a); //string(17) "<script></script>"
settype($a, "integer");
var_dump($a); //int(0)
The code is working if you set a numeric value as string (or integer) on the $a:
$a = "19800";
var_dump($a); //string(5) "19800"
settype($a, "integer");
var_dump($a); //int(19800)
Note: You can't directly assign the result from JavaScript to a PHP variable because the JavaScript code is executed on client side and PHP is executed on server side (before JavaScript). You can use AJAX to send values from JavaScript back to the server to use them on server side too.
| |
doc_23530613
|
SHELL=/bin/bash
LOGFILE=$HOME/procmail.log
VERBOSE=yes
:0
* ^Subject: envdump please$
{
LOG="`id`"
:0
/dev/null
}
/etc/group file contains (note the other usernames are vain attempts to make this work):
someuser:x:504:
s3:x:505:someuser,someotheruser,postfix,postdrop,mail,root
If I run as "someuser" the command id:
[someuser@lixyz-pqr ~]$ id
uid=504(someuser) gid=504(someuser) groups=504(someuser),505(s3)
However when I run procmail by sending an email with the subject "envdump please", the 505/s3 group disappears (this is in procmail.log):
procmail: [17618] Mon Dec 19 17:39:50 2011
procmail: Match on "^Subject: envdump please$"
procmail: Executing "id"
procmail: Assigning "LOG=uid=504(someuser) gid=504(someuser) groups=504(someuser)"
uid=504(someuser) gid=504(someuser) groups=504(someuser)procmail: Assigning "LASTFOLDER=/dev/null"
this server is running Fedora 14 with Postfix 2.7.5
A: Procmail wasn't installed setuid.
for background, it should look like:
[root@li321-238 postfix]# ls -l /usr/bin/procmail
-rwsr-sr-x. 1 root mail 92816 Jul 28 2009 /usr/bin/procmail
which you can set up via:
chmod ug+s /usr/bin/procmail
| |
doc_23530614
|
I have a page playing a HTML5 video, with a webvtt file for my subtitles. I'm trying to get one line to show up about a second after another line.....but keep the first line there.
Then make them disappear together.
Here's what I have:-
4
00:00:13.600 --> 00:00:16.400
Here is my first line....
5
00:00:14.600 --> 00:00:16.400
...and here is my second line.
For some reason, the first line is showing up at the bottom of the video....and the second line is then displayed above it.
That's not what I want.
I've also tried
4
00:00:13.600 --> 00:00:16.400
Here is my first line....
<00:00:14.600>...and here is my second line.
But both lines are being displayed together.
Any ideas?
A: If you want to achieve, you should not use overlapping cues. Instead stop your cue #4 right before cue #5 and add both texts inside of cue #5:
4
00:00:13.600 --> 00:00:14.600
Here is my first line....
5
00:00:14.600 --> 00:00:16.400
Here is my first line....
...and here is my second line.
| |
doc_23530615
|
Error: dyld: lazy symbol binding failed: Symbol not found: __kminitAdmob
Is there anybody has any idea ?
| |
doc_23530616
|
Given that seems to always be the case (unless you know of a way around this), is there any way to determine the file size of that .png before it is saved to disk? For example, maybe write it to a stream first and then get that stream size? How would I go about doing this?
A: You can write to a MemoryStream and calculate the size of it, then write it to the FileSystem.
Although: There might be a better way.
| |
doc_23530617
|
Do we need to buy a license? Why would someone buy a license?
A: You do not need to purchase a license to use the Eclipse IDE.
The terms of use are here: http://www.eclipse.org/legal/epl/notice.php
A: Eclipse is completely free, that is one of its main attractions. Generally speaking, most of what you will download from eclipse.org is free though you may want to read the license.
Some vendors, such as IBM, sell commercial versions of IDEs that are based on the Eclipse core but include a variety of proprietary plugins for things like collaboration, web development, etc. You don't need those if you want to use the standard facilities.
| |
doc_23530618
|
The closest thing I can find is here: https://github.com/JoshClose/CsvHelper/issues/956
My code currently looks like this:
protected override void Seed(pmg2_tracker_net.DAL.Pmg2TrackerContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceName = "pmg2_tracker_net.DAL.CustomCalJobTracker.csv";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
CsvReader csvReader = new CsvReader(reader);
csvReader.Configuration.HeaderValidated = null;
csvReader.Configuration.MissingFieldFound = null;
while (csvReader.Read())
{
var assignment = csvReader.GetRecord<Assignment>();
var status = csvReader.GetField<string>("Overall Job Status");
assignment.Status = context.Statuses.Local.Single(s => s.Designation == status);
context.Assignments.AddOrUpdate(a => a.Status, assignment);
}
}
}
}
And produces this error message:
CsvHelper.ReaderException: An unexpected error occurred. ---> System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles)
at CsvHelper.TypeConversion.DateTimeConverter.ConvertFromString(String text, IReaderRow row, MemberMapData memberMapData)
at lambda_method(Closure )
at CsvHelper.Expressions.RecordCreator.Create[T]()
at CsvHelper.Expressions.RecordManager.Create[T]()
at CsvHelper.CsvReader.GetRecord[T]()
--- End of inner exception stack trace ---
BadDataFound() doesn't seem to be doing anything for me. The date conversion seems to be happening at a level it can't deal with.
Also, I can't trap the GetRecord() section in a try/catch for some reason. It barfs, and then the loop moves on, and the thing blows up the load into the database with: System.InvalidOperationException: Sequence contains no matching element
I would think a library like this would be made to elegantly handle this sort of thing, so I keep thinking I'm missing something obvious.
As suggested, I'm trying to follow the pattern here: https://github.com/JoshClose/CsvHelper/issues/1205.
I added the Configuration line to my code:
csvReader.Configuration.RegisterClassMap<AssignmentMap>();
And my ClassMap file looks like this:
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.TypeConversion;
using pmg2_tracker_net.Models;
using System;
namespace pmg2_tracker_net.DAL
{
public class AssignmentMap : ClassMap<Assignment>
{
public AssignmentMap()
{
Map(m => m.Id);
<SNIP>
Map(m => m.OriginatorName);
Map(m => m.InitiatedDate).TypeConverter<CustomDateTimeConverter>();
Map(m => m.TechScreeningRequestDate).TypeConverter<CustomDateTimeConverter>();
Map(m => m.TechScreeningCompletionDate).TypeConverter<CustomDateTimeConverter>();
<SNIP>
Map(m => m.CommentsOnClosingTime);
}
}
}
public class CustomDateTimeConverter : DateTimeConverter
{
public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
{
try
{
return base.ConvertFromString(text, row, memberMapData);
}
catch (TypeConverterException)
{
Console.WriteLine(text);
return default(DateTime);
}
catch
{
throw;
}
}
}
The stack trace shows that it's using my CustomDatetimeConverter():
CsvHelper.ReaderException: An unexpected error occurred. ---> System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles)
at CsvHelper.TypeConversion.DateTimeConverter.ConvertFromString(String text, IReaderRow row, MemberMapData memberMapData)
at **CustomDateTimeConverter**.ConvertFromString(String text, IReaderRow row, MemberMapData memberMapData) in C:\Users\hq785\Projects\pmg2_tracker_net\pmg2_tracker_net\DAL\AssignmentMap.cs:line 72
at lambda_method(Closure )
at CsvHelper.Expressions.RecordCreator.Create[T]()
at CsvHelper.Expressions.RecordManager.Create[T]()
at CsvHelper.CsvReader.GetRecord[T]()
--- End of inner exception stack trace ---
I can't break in the Catch. I'm left with the impression that, because I'm calling this from the EntityFramework Seed() method from the Update-Database migration command, that it's been "wrapped" in a way that's preventing me from really interacting with the running code. (I've updated the title to reflect this complication.)
Coming from the Rails world, this all seems too clever by half. I guess all I can do is parse the fields "by hand" (re: https://joshclose.github.io/CsvHelper/examples/reading/reading-by-hand/).
Or make a separate PS script, so it's not running under the Seed() method. (The question that's kept me from trying this is how to run it "under" the EF layer, like rails runner.)
Or manipulate the CSV file into a series of SQL inserts, and clean then all up by hand. Sigh.
A: So I finally broke the fields out by hand, and wrapped them in DateTime.TryParse:
protected override void Seed(Pmg2TrackerContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
if (!System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Launch();
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceName = "pmg2_tracker_net.DAL.CustomCalJobTracker.csv";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
CsvReader csvReader = new CsvReader(reader);
csvReader.Configuration.HeaderValidated = null;
csvReader.Configuration.MissingFieldFound = null;
var records = new List<Assignment>();
csvReader.Read();
csvReader.ReadHeader();
while (csvReader.Read())
{
var assignment = new Assignment
{
Id = csvReader.GetField<int>("Id"),
Vpcr = csvReader.GetField("Vpcr"),
<SNIP>
InitiatedDate = ConvertBadDate(csvReader.GetField("InitiatedDate")),
TechScreeningRequestDate = ConvertBadDate(csvReader.GetField("TechScreeningRequestDate")),
TechScreeningCompletionDate = ConvertBadDate(csvReader.GetField("TechScreeningCompletionDate")),
<SNIP>
};
string status_string = csvReader.GetField<string>("Status");
assignment.Status = context.Statuses.First(s => s.Designation == status_string);
context.Assignments.AddOrUpdate(a => a.Vpcr, assignment);
}
}
}
base.Seed(context);
}
private DateTime ConvertBadDate(string PossibleDate)
{
DateTime val;
if (DateTime.TryParse(PossibleDate, out val))
{
Console.WriteLine("Converted '{0}' to {1}.", PossibleDate, val);
return val;
}
else
{
Console.WriteLine("Unable to convert '{0}' to a date.", PossibleDate);
return DateTime.Now;
}
}
As a bonus, I also found the trick to launch the process in another instance of Visual Studio, where I could set breakpoints, and find a bunch of little problems with the rest of my initial schema.
| |
doc_23530619
|
To clarify, I have a button <button onclick='load()'>load</button> that calls a load() function which gets an array, processes each element and displays it in a list <ul id='main'></ul>
function load(event) {
$("#main").empty(); //empty old elements
$.get("load.php", '', function (data) {
var arr = JSON.parse(data);
for (i = 0; i < arr.length; ++i) {
process(arr[I]); //process and append to #main
}
});
}
Problem is, that if I click the button again while its still putting the elements into the array, I get the new list plus the rest of the old list.
Is there a way to stop the first event while its still executing but still execute the second event?
A: As noted, you can stop the event by setting a flag and checking it, but a better approach would simply be to assign the new value directly. If your code works it means JSON.parse is returning an array already.
That means
"use strict";
(function () {
function load(event) {
$("#main").empty();
$.get("load.php", '', function (data) {
process = JSON.parse(data);
$("#main").whateverMethodFillsTheElement(process);
});
}());
Also, when writing asynchronous JavaScript code that makes HTTP requests, promises are preferred to callbacks. Since $.get returns a Promise you can write
"use strict";
(function () {
function load(event) {
$("#main").empty();
$.get("load.php")
.then(function (data) {
var items = JSON.parse(data);
$("#main").whateverMethodFillsTheElement(items);
});
}
}());
As discussed in comments, the aim is to use each item in another request which provides the actual value to add to 'main'. So loading data triggers an asynchronous call for each loaded item.
To accommodate this, we need to determine a key field that we can use to track each item so we do not append existing items to the list. We will call this field id for the sake of exposition.
"use strict";
(function () {
var allItems = [];
function load(event) {
$("#main").empty();
$.get("load.php")
.then(function (data) {
return JSON.parse(data);
})
.then(function (items) {
items.forEach(item => {
processItem(item)
.then(function (processed) {
var existingItem = allItems.filter(i => i.id === item.id)[0];
if(existingItem) {
var existingIndex = allItems.indexOf(existingItem);
allItems[existingIndex] = processed;
}
else {
allItems.push(processed);
}
});
});
});
}
}());
A: You should try this:
var xhr;
function load(ev){
if(ev.eventPhase === 2){
if(xhr)xhr.abort();
$('#main').empty();
xhr = $.get('load.php', function(data){
var a = JSON.parse(data);
for(var i=0,l=a.length; i<l; i++){
process(a[i]);
}
});
}
}
A: I can be wrong, but...
var req = $.ajax({
$("#main").addEventListener("click",()=>{req.abort()})
...
...
$("#main").removeEventListener("click",()=>{req.abort()})
});
A: Ok, seems like it's not possible to stop an Ajax success function after it began executing or to stop a past event without aborting the current one.
But the following solution worked for me so I figured I'll post it here:
var num = 0;
function load() {
var curNum = ++num;
$("#main").empty();
$.get("load.php", '', function (data) {
var arr = JSON.parse(data);
for (i = 0; i < arr.length; ++i) {
process(arr[i], curNum);
}
});
}
function process(item, curNum) {
if(curNum === num) { //don't process if a new request has been made
//get 'data' based on 'item'...
if(curNum === num) { //check again in case a new request was made in the meantime
$("#main").append(data);
}
}
}
I appreciate everyone's help.
| |
doc_23530620
|
(Idea presented here: http://tech.pro/blog/1639/using-rjs-to-optimize-your-requirejs-project)
I have an html file which has
<script>
require("common"), function() {
require(["some_app"], function(SomeApp) {
});
});
</script>
SomeApp.js depends on some library files
define(['jquery', 'backbone'], function($, Backbone) {
..
return SomeApp;
});
common.js include library files
define(['jquery', 'backbone'], function() {});
my build.js for r.js optimizer looks like
{
name: "SomeApp"
exclude: ['common'] // intent: do not include common library files
}
When I run the optimizer, 'common' is indeed excluded from the concatenated SomeApp.js!
The result is exactly what I want, but I'm perplexed because r.js seems to inspect the html which requires javascript files.
Is it true? What's going on here?
A:
The result is exactly what I want, but I'm perplexed because r.js seems to inspect the html which requires javascript files.
r.js does not inspect HTML files. The result you describe getting is consistent with r.js operating purely on the JavaScript files and the build configuration you describe in your question.
| |
doc_23530621
|
I mean, if i must have a login form and then when someone got logged I must change to another view, how could I must do that?
Must I put Login and the other view into a ViewPort? Do anyone has any example how I could manage this? What structure do you suggest?
A: Your Login should be an independent View. Here is an example how you can structure your MVC code:
Ext.application({
name: 'xxx',
models: [
// ...
],
views: [
// ...
],
stores: [
// ...
],
controllers: [
// ...
],
// ...
launch: function() {
// at the beginning show only the login form
this.showLoginView();
},
// when the login is successfull, show your main view
login: function(username, password) {
this.showMainView();
}
});
| |
doc_23530622
|
Html.Action("GetCartList", "Shared");
ShoppingCartViewModel scvm = (ShoppingCartViewModel)ViewData["ShoppingCartViewModel"];
My controller
[ChildActionOnly]
public ShoppingCartViewModel GetCartList()
{
var results = new ShoppingCartViewModel
{
Message = "",
SomeOtherProperty = "Other"
};
ViewData["ShoppingCartViewModel"] = results;
return results;
}
The question is why the scvm is always null?
When the controller "gets hit", the values are loaded successfully to the ViewData["ShoppingCartViewModel"]
I wish i could do something like ...
ShoppingCartViewModel scvm = Html.Action("GetCartList", "Shared");
A: In your child action, Set the ViewData to your ParentActionViewContext.
[ChildActionOnly]
public void GetCartList()
{
var results = new ShoppingCartViewModel
{
Message = "",
SomeOtherProperty = "Other"
};
ControllerContext.ParentActionViewContext.ViewData["ShoppingCartViewModel"]=results;
}
And in your Layout,
@Html.Action("GetCartList", "Home");
@{
var scvm = (ShoppingCartViewModel) ViewContext.ViewData["ShoppingCartViewModel"];
<div> @scvm.SomeOtherProperty </div>
}
| |
doc_23530623
|
I was thinking on starting with dive into python, but i'm worried most not about the python part, but the "she does not know anything about programming" problem.
How can I keep her interested? I'm worried because she will have to learn if/else - oop - functions and stuff as she learns the python syntax, and she might get bored.
Maybe a project we can work together? Some simple django app?
Any ideas will be appreciated.
Related? :https://stackoverflow.com/questions/111857/what-did-you-use-to-teach-yourself-python
A: Nothing is better for learning to program than a real project (by real I mean of use for somebody besides the author), internet connection and an expert friend. As long as she is willing to learn.
Screencasts are a great way to learn new stuff fast and not-so-boring. Try http://showmedo.com for example
A: Scott Hanselman recently podcasted about a book called "Hello World : Computer Programming for Kids and Other Beginners".
It's written using Python and sounds like a good introduction to programming for beginners of all ages - I'm thinking about getting it for my nephew's birthday.
Might be worth a look?
A: Try this: http://homepage.mac.com/s_lott/books/nonprogrammer.html#book-nonprogrammer
Non-programmers are my target market.
A: The only way to learn is to automate some everyday tasks for her, for example fetching her online news or something, or something like a basic password manager.
The possibilities are endless ! :P
A: Tom, my experience has not been positive about it. My wife "wanted" to learn python but never went beyond a few chapters of "Dive into Python". I vaguely infer that she had a few doubts on the way, and never got interested in solving them. I have little doubt that an adult seldom does something new unless he/she needs to do it.
I do not want to discourage you but I'd leave it up to her (my wife) to decide whether to learn programming or not -- I would not try to teach her if she does not ask for that. My wife is quite interested in photography instead.
On the positive side, we might have new ways of learning programming invented only recently like Scratch, which probably have a better chance of conversions.
A: A more "fun" approach to try is to give examples of everyday things that your wife will understand. Say if you are teaching her about if/else control flow, then give examples like "if time is 8am, wake up to go to work, else continue sleeping". In pseudocode,
if time == 8am:
do wake up
else:
do continue sleeping.
Other examples, learning about functions. So you can tell her, that functions let her do things over and over. eg
def go_toilet():
open door
close door
lift toilet seat
do stuff
flush
wash hands
exit door
A: I have heard good things about the book Learn to Program from the Pragmatic Programmers. It uses Ruby instead of Python, and is geared toward teaching basic programming concepts to complete beginners.
It seems to have examples and exercises geared toward stuff your average person can relate to.
| |
doc_23530624
|
Does somebody know how to do this?
A: Just type
cordova plugin ls
or
cordova plugin list
on command line in your project's root folder where you would normally install or remove your plugins, or build or run it.
A: The newer versions of Cordova also support the following:
cordova plugin
or
cordova plugins
A: for the capacitor cli npx cap ls
A: For ionic ionic cordova plugin list
| |
doc_23530625
|
It works fine. The problem is the state is not saved, so when I scroll, it call getView again, and the state change back to the previous state. And when change app then get back too
This is the getView function, where all the problem start :
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ContentViewHolder.CaptionTitleHolder captionHolder = null;
ContentViewHolder.PreCookingViewHolder preCookingHolder = null;
ContentViewHolder.CookingViewHolder cookingHolder = null;
int type = getItemViewType(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (type == CAPTION_TITLE){
if (convertView == null){
convertView = inflater.inflate(R.layout.caption_title_view, parent, false);
captionHolder = new ContentViewHolder.CaptionTitleHolder();
captionHolder.text = (TextView) convertView.findViewById(R.id.caption_title_textview);
convertView.setTag(captionHolder);
} else {
captionHolder = (ContentViewHolder.CaptionTitleHolder) convertView.getTag();
}
captionHolder.text.setText(((RecipeContentActivity2.CaptionTitle) allItems.get(position)).getContent());
} else if (type == COOKING){
if (convertView == null){
convertView = inflater.inflate(R.layout.cooking_steps_and_timer, parent, false);
cookingHolder = new ContentViewHolder.CookingViewHolder();
cookingHolder.text = (TextView) convertView.findViewById(R.id.cooking_step_content);
cookingHolder.time = (TextView) convertView.findViewById(R.id.cooking_timer);
cookingHolder.skipButton = (Button) convertView.findViewById(R.id.button_skip);
cookingHolder.startButton = (Button) convertView.findViewById(R.id.button_timer);
convertView.setTag(cookingHolder);
} else {
cookingHolder = (ContentViewHolder.CookingViewHolder) convertView.getTag();
}
CookingStep myStep = (CookingStep) allItems.get(position);
setUpCookingView(convertView, cookingHolder, myStep);
} else {
if (convertView == null){
convertView = inflater.inflate(R.layout.pre_cooking_view, parent, false);
preCookingHolder = new ContentViewHolder.PreCookingViewHolder();
preCookingHolder.text = (TextView) convertView.findViewById(R.id.pre_cooking_textview);
convertView.setTag(preCookingHolder);
} else {
preCookingHolder = (ContentViewHolder.PreCookingViewHolder) convertView.getTag();
}
preCookingHolder.text.setText((String) allItems.get(position));
}
return convertView;
}
private void setUpCookingView(final View c, final ContentViewHolder.CookingViewHolder view, final CookingStep step){
String stepOrder = context.getResources().getString(R.string.step_order) + " " + step.getOrder();
String content = "<b>" + stepOrder + ":</b> " + step.getContent() + "\n";
view.text.setText(Html.fromHtml(content));
if (step.getMinute() != null && step.getMinute() > 0){
if (step.getMyTimer() == null) {
CookingTimer2 timer = new CookingTimer2(step.getMinute()) {
@Override
public void upgradeUI() {
view.time.setText(toString());
}
};
step.setTimer(timer);
}
view.time.setVisibility(View.VISIBLE);
view.startButton.setVisibility(View.VISIBLE);
view.skipButton.setVisibility(View.VISIBLE);
view.startButton.setText(R.string.button_available);
view.skipButton.setText(R.string.skip_button_content);
view.startButton.setEnabled(step.isTurnEnable());
view.skipButton.setEnabled(step.isTurnEnable());
view.time.setText(step.getMyTimer().toString());
view.startButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (!view.startButton.isPressed()) {
view.startButton.setPressed(true);
view.startButton.setText(R.string.button_pressed);
step.getMyTimer().doStart();
//c.setTag(R.id.button_timer, true);
} else {
view.startButton.setPressed(false);
view.startButton.setText(R.string.button_available);
step.getMyTimer().doStop();
//c.setTag(R.id.button_timer, false);
}
}
return true;
}
});
view.skipButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
step.getMyTimer().doStop();
((RecipeContentActivity2) context).enableNextStep();
}
return true;
}
});
} else {
view.time.setVisibility(View.GONE);
view.startButton.setVisibility(View.GONE);
view.skipButton.setVisibility(View.GONE);
}
}
Somehow I managed to fix the problem in case when scrolling using this the timer's state. Thanks milosmns for reminding me that I still have my timer ticking
if (step.getMyTimer().isTicking()){
view.startButton.setPressed(true);
view.startButton.setText(R.string.button_pressed);
}
But I still have that problem when switch to another app, then get back. It seems that in this case, the getView didn't get called. So what should I do next ?
So yeah I've found a hackish way to do this. I don't really like it though
In my activity :
@Override
protected void onResume() {
super.onResume();
if (wasStoped)
((MyAdapter)listContent.getAdapter()).notifyDataSetChanged();
}
@Override
protected void onStop() {
wasStoped = true;
super.onStop();
}
I still want to know any other method
A: use holder class like:
public View getView(final int i, View view, final ViewGroup viewGroup) {
View vi = view;
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
vi = inflater.inflate(R.layout.listview_row_cart, null);
holder.yourbutton = (Button) vi.findViewById(R.id.btn);
vi.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.yourbutton.setText("Start");
}
class ViewHolder {
Button yourbutton
}
A: Your onCreate method is most likely being called again in order to rebuild the view and is refreshing the state of the button, you need to save the state of the button.
You can do this using the sharedPreferences.
You can view the documentation on how to implement this
Here
A: So I was able to resolve this, by implement for myself my Button, with custom state. Yeah I just realize that depend on button's state pressed is not the way, since there are too many interference that can change this state.
public class TimerButtonControl extends Button{
private static final int[] STATE_RUN = {R.attr.timer_run};
private boolean running = false;
public TimerButtonControl(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setRun(boolean r){
running = r;
refreshDrawableState();
}
public boolean isRunning() {return running; }
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (running) {
mergeDrawableStates(drawableState, STATE_RUN);
}
return drawableState;
}
}
and then define xml for this button :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:drawable="@drawable/clock_button_not_pressed"
app:timer_run="false" android:state_enabled="true" />
<item android:drawable="@drawable/clock_button_pressed"
app:timer_run="true" android:state_enabled="true" />
<item android:drawable="@drawable/button_unavailable"
android:state_enabled="false" />
</selector>
then use it inside my layout :
<com.username.mypackage.uiassistance.TimerButtonControl
android:id="@+id/button_timer"
android:padding="4dip"
android:layout_width="90dip"
android:layout_height="wrap_content"
android:layout_below="@id/cooking_step_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="@drawable/timer_button"
android:enabled="false"/>
and finally inside adapter :
if (step.getMyTimer().isTicking()){
view.startButton.setRun(true);
view.startButton.setText(R.string.button_pressed);
}
view.startButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (!view.startButton.isRunning()) {
view.startButton.setRun(true);
view.startButton.setText(R.string.button_pressed);
step.getMyTimer().doStart();
} else {
view.startButton.setRun(false);
view.startButton.setText(R.string.button_available);
step.getMyTimer().doStop();
}
}
return true;
}
});
Hope it could help anybody else that have the same problem as me.
| |
doc_23530626
|
sub is-happy( $n is copy ) {
my $seen-numbers = :{};
while $n > 1 {
return False if $n ∈ $seen-numbers;
$seen-numbers{$n} = True;
$n = $n.comb.map(*²).sum
}
return True;
}
say is-happy(7); # True
say is-happy(2018); # False
This code runs practically instantly. I tried say $seen-numbers.^name; and found that it was Hash[Mu,Any].
However, when I remove the colon, is-happy(7) returns True, but then is-happy(2018) tied up the CPU for several minutes (until I killed the process).
Also, in this case, say $seen-numbers.^name; prints Hash.
So, obviously, :{} results in creating a Hash[Mu,Any]. How does that work? Is this a work-around or is idiomatic? And what is a Hash[Mu,Any] and how does it compare to a normal Hash?
A: A Hash has Str keys. Any key that is not a Str will be coerced into one before storing the value under that string key. The {} constructs an empty Hash.
This behavior can be changed by giving Hash type arguments. A Hash[Int], for example, still has the auto-coercing string key, but can only store Int values (much like an Array[Int] can only store Int values). It is also possible to pass a second type argument to pick the type of the key. This creates what is often referred to as an "object hash", and it stores the exact keys that are provided in the indexer. So a Hash[Mu,Any] is a hash with unconstrained values and Any kind of key (nearly all types fall under Any, with the exception of Junction). The .WHICH of the key is used for hashing.
Most of the time, one doesn't create object hashes using Hash[TValue,TKey], but instead using a declaration syntax; for example, I might represent edges in a DAG using something like has Array %!edges-from{Mu}. There is also a way to create an anonymous object hash, :{}, which is what you observe in the example.
So, what difference does it make? Here:
$seen-numbers{$n} = True;
The $n will be stored as an Int, its .WHICH used for hashing to get the O(1) lookup. If we'd just used {} instead, we'd have had the Int being coerced into a Str for the key. That difference becomes important here:
return False if $n ∈ $seen-numbers;
Because the set membership operator looks for values to be identical. So when we have an object hash, :{}, storing the Ints, then $n might be identical to one of the keys in the hash; if it is, the algorithm terminates. However, with a normal hash, created with {}, the keys are Str, so never identical to the Int, and so the set membership check will always fail, causing non-termination of the algorithm.
The program is consistent with its own decisions. One could write:
return False if $seen-numbers{$n}:exists;
And then it will work with the {} (Hash) also. However, it will be coercing the numbers into Str for storage and lookup every single time, a cost avoided with :{}. So, we can say that the program has made a more efficient data structure choice by using :{}, and that in turn enabled the use of ∈, which could be considered more readable (especially if the target audience is folks used to reading such mathematical operators).
Another way to write the program that may have been clearer is:
my %seen-numbers is SetHash;
while $n > 1 {
return False if $n ∈ %seen-numbers;
%seen-numbers{$n} = True;
$n = $n.comb.map(*²).sum
}
return True;
Which makes clearer that we're thinking of %seen-numbers as a set, although in this case the name leaves relatively little question about its purpose.
| |
doc_23530627
|
I created a Label using following code. Before creating this Label I want to check if this Label is already exist then not to create it again.
label_service = client.GetService('LabelService', version='v201409')
###Code here to check if 'MyLabel' already exist - please suggest
operations = [{
'operator': 'ADD',
'operand': {'xsi_type': 'TextLabel',
'name' : 'MyLabel',
'status': 'ENABLED'}
}]
result = label_service.mutate(operations)
I can see with get operation of LabelService I can get Labels of specified criteria.
But I am not able to specify serviceSelector parameter correctly.
A: I have the same issue, if you run get instead of mutate like this:
label_service.get({'fields': ['LabelId', 'LabelName', 'LabelStatus', 'LabelAttribute']})
It will return an object which contains all the existing labels and their ids etc in an account.
In any case, I just tested it, it will not let you create a label which already exists so you don't need to worry.
| |
doc_23530628
|
Under Linux, I would use /dev/mem to acquire this data. Under Windows 8, I'm not sure what mechanism is available to do this.
My use case is inspecting a PCI Express device. The PCI Express device creates a ring buffer at a known address, that I can determine from the PCIe BAR. Once this address has been set, it won't change until the computer restarts.
Currently, I can use applications like RW Everything to see the data there, but I would like to be able to do this without user interaction (Without the GUI) so that I have fewer issues with the ring buffers wrapping before I can access the data.
Does anyone know if there is a privileged Windows system call I can make from userspace (to mmap a region for example) or do I need to use a custom kernel module to do this? I imagine that there is some way to do it without a custom kernel module, because I don't believe I installed one when I installed RW Everything.
A: Since Windows Server 2003 SP1, user-mode access to physical memory has not been possible. You will have to develop a driver to do it (or find a third-party tool that includes one).
From Technet:
In Windows Server 2003 SP1, user-mode access to the \Device\PhysicalMemory object is not permitted. All forms of access (read, write) are refused when the \Device\PhysicalMemory object is accessed from a user-mode application. Access to the \Device\PhysicalMemory object is refused regardless of the user context (Administrators, Users, Local System, etc.) the application is running in.
A: There are many windows software to access the physical memory, however, many of them cannot access the physical memory in windows vista or 7 because of physical memory protection feature in these OS's.
There are many windows tools similar to dev/mem unix's one, such as:
*
*Belkasoft Live RAM Caputer
*WindowsSCOPE Pro and Ultimate, available at http://www.windowsscope.com
*WindowsSCOPE Live
*winen.exe (Guidance Software - included with Encase 6.11 and higher)
*Mdd (Memory DD) (ManTech)
*MANDIANT Memoryze
*Kntdd
*Moonsols
*HBGary
*FTK Imager
*OSForensics
*WinPmem; and
*Windows Memory Reader
Check this wiki for more info:
http://www.forensicswiki.org/wiki/Tools:Memory_Imaging
| |
doc_23530629
|
My code: pointFormat = "{point.name}: <b>{point.percentage}</b><br/>"
Do we have any setting or any other way to do it?
A: How about using the formatter?
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares in January, 2018'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
//format: '<b>{point.name}</b>: {parseFloat(point.percentage)} %'
formatter: function() {
let pointName = this.point.name
let pointPercentage = parseFloat(this.point.percentage).toFixed(2).toLocaleString().replace(".", ",");
return `${pointName}: ${pointPercentage}%`
}
}
}
},
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: 'Chrome',
y: 61.41,
sliced: true,
selected: true
}, {
name: 'Internet Explorer',
y: 11.84
}, {
name: 'Firefox',
y: 10.85
}, {
name: 'Edge',
y: 4.67
}, {
name: 'Safari',
y: 4.18
}, {
name: 'Sogou Explorer',
y: 1.64
}, {
name: 'Opera',
y: 1.6
}, {
name: 'QQ',
y: 1.2
}, {
name: 'Other',
y: 2.61
}]
}]
});
.highcharts-figure, .highcharts-data-table table {
min-width: 320px;
max-width: 800px;
margin: 1em auto;
}
.highcharts-data-table table {
font-family: Verdana, sans-serif;
border-collapse: collapse;
border: 1px solid #EBEBEB;
margin: 10px auto;
text-align: center;
width: 100%;
max-width: 500px;
}
.highcharts-data-table caption {
padding: 1em 0;
font-size: 1.2em;
color: #555;
}
.highcharts-data-table th {
font-weight: 600;
padding: 0.5em;
}
.highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption {
padding: 0.5em;
}
.highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) {
background: #f8f8f8;
}
.highcharts-data-table tr:hover {
background: #f1f7ff;
}
input[type="number"] {
min-width: 50px;
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<figure class="highcharts-figure">
<div id="container"></div>
<p class="highcharts-description">
Pie charts are very popular for showing a compact overview of a
composition or comparison. While they can be harder to read than
column charts, they remain a popular choice for small datasets.
</p>
</figure>
| |
doc_23530630
|
SEVERE: Servlet.service() for servlet [springDispatcher] in context with path [/Events] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement] with root cause
java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: ATTENDANCE0_.EVENTID
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source)
at org.apache.commons.dbcp2.DelegatingConnection.prepareStatement(DelegatingConnection.java:293)
at org.apache.commons.dbcp2.DelegatingConnection.prepareStatement(DelegatingConnection.java:293)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1927)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1896)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1874)
at org.hibernate.loader.Loader.doQuery(Loader.java:919)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2610)
at org.hibernate.loader.Loader.doList(Loader.java:2593)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2422)
at org.hibernate.loader.Loader.list(Loader.java:2417)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1339)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
at calendar.DAL.AttendanceDAO.selectAttendancesByEventId(AttendanceDAO.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy25.selectAttendancesByEventId(Unknown Source)
at calendar.service.DefaultAttendanceService.getAttendeeNamesViaEventId(DefaultAttendanceService.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy32.getAttendeeNamesViaEventId(Unknown Source)
at calendar.controllers.EventController.showListings(EventController.java:110)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
This is the code under investigation:
public List<Attendance> selectAttendancesByEventId(int eventId) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
Query query = entityManager.createQuery("SELECT p FROM Attendance p WHERE p.eventId = :eventId");
query.setParameter("eventId",eventId);
//TODO
List<Attendance> attendances = query.getResultList();
return attendances;
}
public List<Attendance> selectAttendancesByAccountId(int accountId) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
Query query = entityManager.createQuery("SELECT p FROM Attendance p WHERE p.accountId = :accountId");
query.setParameter("accountId",accountId);
//TODO
List<Attendance> attendances = query.getResultList();
return attendances;
}
| |
doc_23530631
|
body: Column(children: [
SizedBox(height: height * 0.1),
Center(
child: Container(
height: height * 0.1,
width: width * 0.6,
child: Image.asset("assets/f.png", fit: BoxFit.contain),
)),
SizedBox(height: height * 0.05),
Center(
child: Container(
height: height * 0.4,
width: width * 0.8,
child: Form(
key: _formKey,
child: Column(children: [
TextFormField(
controller: name,
obscureText: false,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Name',
),
),
SizedBox(height: height * 0.01),
TextFormField(
validator: validateEmail,
controller: emailAddress,
obscureText: false,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email adress',
),
),
SizedBox(height: height * 0.01),
TextFormField(
validator: validatePassword,
controller: password,
obscureText: false,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
),
),
SizedBox(height: height * 0.01),
Center(
child: InkWell(
onTap: () {
_submit();
},
child: Container(
height: height * 0.05,
width: width * 0.4,
child: Center(
child: Text("Register",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white))),
decoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.circular(20.00)),
))),
InkWell(
onTap: () {
Navigator.of(context).pushNamed('/s');
},
child: Text("Already have an account?",
style: TextStyle(color: Colors.grey)))
]),
)),
)
])
| |
doc_23530632
|
id a b c d e
a 23_2_1 34_55_0 34_55_0 -1_-1_-1 34_55_0
b 3_55_0 34_55_0 34_55_0 34_55_0 34_55_0
c -1_-1_-1 34_55_0 34_55_0 34_55_0 -1_-1_-1
d 34_55_0 -1_-1_-1 34_55_0 34_55_0 34_55_0
e 34_55_0 34_55_0 34_55_0 34_55_0 34_55_0
f 34_55_0 34_55_0 34_55_0 34_55_0 34_55_0
I want to delete the rows that if there is value of columns is '-1_-1_-1' in the dataframe, and also extract the id that include the '-1_-1_-1'.
My trying:
lst_col = list(df.columns)[:-1]
df2 = df_bl[~df_bl[lst_col].isin(['-1_-1_-1'])]
A: First, find the values you care about:
match_cells = df == '-1_-1_-1'
That gives you a DataFrame with True wherever the indicated value is, and False elsewhere.
Now select the rows that have a match:
match_rows = match_cells.any(axis=1)
Then take the rows without matches:
df2 = df[~match_rows]
And get the row labels with matches:
match_ids = df.index[match_rows]
| |
doc_23530633
|
for (int i = 0; i<3; i++)
{
for (int j = 0; j<3; j++)
{
TileList[i][j] = Tiles[3];
//the goal is the overwrite the MapX and MapY fields of each element of the new Array
TileList[i][j].MapX = i;
TileList[i][j].MapY = j;
}
}
After printing out the values each element each MapX and MapY field of each element was expect to have their own separate value, however instead both MapX and MapY are set to 3 for each tile object reference in the 2d Array.
A: You're setting all the array members to the same object with this statement:
TileList[i][j] = Tiles[3];
That statement copies a reference to an object, not the object itself.
On the last pass through the loop, all the array members point to the same object, and these statements set its members to 3 and 3:
TileList[i][j].MapX = i;
TileList[i][j].MapY = j;
If you want all the array members to point to different objects, you can create a new object for each with a default constructor:
TileList[i][j] = new Tile();
Or a constructor which copies another object:
TileList[i][j] = new Tile( myDefaultTile );
Or the clone() method, if you support it:
TileList[i][j] = myDefaultTile.clone();
As an aside, note that it is customary in Java for the names of variables and class members to begin with a lowercase letter. For example:
tileList[i][j].mapX = i;
| |
doc_23530634
|
<div title="Have a nice<br />day">blah</div>
A: it seems that modern browsers will show tooltip on new line after carriage return symbol:
<!-- i've pressed Enter after word "line" -->
<div id="myDiv" title="first line
multiline">Hello world!</div>
Or you can try set value by javascript:
var myDiv=document.getElementById('myDiv');
myDiv.title = "first line \n multiline";
A: Short of replacing the entire thing with elements generated with JS (or ugly CSS hacks) and positioned with CSS, you can't, at least not reliably.
If I remember rightly, some browsers will render a new line if you have a literal new line in the element, while others will render the unprintable character symbol. It is possible that this might need the entity for a new line instead. Either way - avoid this as having the unprintable character symbol is more than a little suboptimal.
If you have that much content, it probably isn't suitable for a tooltip anyway.
A: You might want to look into some javascript tooltips.
| |
doc_23530635
|
Which one is better to do, in the long run? When I program it in C++, I have direct access to the raw requests where as in the case of using standard servers I need to use a scripting language to handle the requests. In any case, which one is the better option and why?
Also, when it comes to security for things like DDOS attacks etc., do the standard servers already have protection? If I would want to implement it in my socket server, what is the best way?
A: "Server side software" could mean lots of different things, for example this could be a trivial app which "echoes" everything back on a specific port, to a telnet/ftp server to a webserver running lots of "services".
So where in this gamut of possibilities does your particular application lie? Without further information, it's difficult to make any suggestions, but let's see..
*
*Web Services, i.e. your "server side" requirement is to handle individual requests and respond having done some set of business logic. Typically communication is via SOAP/XML, and this is ideal if you bave web based clients (though nothing prevents your from accessing these services via standalone clients). Typially you host these on web servers as you mentioned, and often they are easiest written in Java (I've yet to come across one that needed to be written in C++!)
*Simple web site - slightly different to the above, respods to HTML get/post requests and serves up static or dymanic content (I'm guessing this is not what you're after!)
*Standalone server which responds to something specific, here you'd have to implement your own "messaging"/protocols etc. and the server will carry out a specific function on incoming request and potentially send responses back. Key thing here is that the server does something specific, and is not a generic container (at which point 1 makes more sense!)
So where does your application lie? If 1/2 use Java or some scripting language (such as Perl/ASP/JSP etc.) If 3, you can certainly use C++, and if you do, use a suitable abstraction, such as boost::asio and Google Protocol buffers, save yourself a lot of headache...
With regards to security, ofcourse bugs and security holes are found all the time, however the good thing with some of these OS projects is that the community will tackle and fix them. Let's just say, you'll be safer using them than your own custom handrolled imlpementation, the likelyhood that you'll be able to address all the issues that they would have encountered in the years they've been around is very small (no disrespect to your abilities!)
EDIT: now that there's a little more info, here is one possible approach (this is what I've done in the past, and I've jused Java most of the way..)
*
*The client facing server should be something reliable, esp. if it's over the internet, here I would use a proven product, something like Apache is good or IIS (depends on which technologies you have available). IMHO, I would go for jBoss AS - really powerful and easily customisable piece of kit, and integrates really nicely with lots of different things (all Java ofcourse!) You could then have a simple bit of Java which can then delegate to your actual Server processes that do the work..
*For the Server procesess you can use C++ if that's what you are comfortable with
There is one key bit which I left out, and this is how 1 & 2 talk to each other. This is where you should look at an open source messaging product (even more higher level than asio or protocol buffers), and here I would look at something like Zero MQ, or Red Hat Messaging (both are MQ messaging protocols), the great advantage of this type of "messaging bus" is that there is no tight coupling between your servers, with your own handrolled implementation, you'll be doing lots of boilerplate to get the interaction to work just right, with something like MQ, you'll have multiplatform communication without having to get into the details... You wil save yourself a lot of time and bother if you elect to use something like that.. (btw. there are other messaging products out there, and some are easier to use - such as Tibco RV or EMS etc, however they are commercial products and licenses will cost a lot of money!)
With a messaging solution your servers become trivial as they simply handle incoming messagins and send messages back out again, and you can focus on the business logic...
my two pennies... :)
A: If you opt for 1st solution in Nim's list (web services) I would suggest you to have a look at WSO's web services framework for C++ , Axis CPP and Axis2/C web services framework (if you are not restricted to C++). Web Services might be the best solution for your requirement as you can quickly build them and use either as processing or proxy modules on the server side of your system.
| |
doc_23530636
|
I have the tail shape stored in a CGMutablePathRef and it's drawn as follows:
- (void) drawPaths
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddPath(context, self.mutablePath);
CGPathRelease(mutablePath);
CGColorRelease(fillColor);
CGColorRelease(strokeColor);
}
I am trying to make it so when I input some angle to this algorithm (say 45 degrees) that the tail rotates and curves much like the above photo. The rotation is obviously an easy transformation, but getting it to curve is what I'm struggling with. I realize that I probably need to use: CGPathAddQuadCurveToPoint however I'm having trouble understanding what to set as my control points and am getting unpredictable results. Even this brilliant post has left me clueless: Given a CGPath, how to make it curve?
Does anyone know how to do this?
A: I assume you have or can get the x and y coordinates for both the origin point of the paths - the end of the paths on the balloon - and for the end point - the tip of the triangle - that you want for each of the paths. Let's call the origin point (xorig, yorig) and the end point (xend, yend). To make the path curve, we need to calculate a reasonable quadratic curve coordination point, which we'll call (xc, yc). I believe the following coordinate calculation will produce a reasonable curve for you:
xc = (xorig * 3 + xend) / 4;
yc = (xorig + xend) / 2;
CGPathAddQuadCurveToPoint(mutablePath, NULL, xc, yc, xend, yend).
To make the path curve differently, you can vary the weights of xorig and xend in the calculation of xc.
A:
@interface
V : UIView
@end
@implementation
V
{ UIBezierPath* u1;
UIBezierPath* u2;
}
- (void)
awakeFromNib
{ u1 = UIBezierPath.bezierPath;
[ u1
moveToPoint:CGPointMake( 0, 0 )
];
[ u1
addQuadCurveToPoint:CGPointMake( 10, 100 )
controlPoint:CGPointMake( 10, 30 )
];
[ u1
addQuadCurveToPoint:CGPointMake( 20, 0 )
controlPoint:CGPointMake( 10, 30 )
];
u1.lineWidth = 3;
u1.lineJoinStyle = kCGLineJoinBevel;
u2 = UIBezierPath.bezierPath;
[ u2
moveToPoint:CGPointMake( 0, 0 )
];
[ u2
addQuadCurveToPoint:CGPointMake( 50, 60 )
controlPoint:CGPointMake( 10, 30 )
];
[ u2
addQuadCurveToPoint:CGPointMake( 20, 0 )
controlPoint:CGPointMake( 10, 30 )
];
u2.lineWidth = 3;
u2.lineJoinStyle = kCGLineJoinBevel;
}
- (void)
drawRect:(CGRect)p
{ CGContextTranslateCTM( UIGraphicsGetCurrentContext(), 100, 100 );
[ u1 stroke ];
CGContextTranslateCTM( UIGraphicsGetCurrentContext(), 100, 0 );
[ u2 stroke ];
}
@end
This program results image following. Maybe some hints.
A: I would first experiment with PaintCode to see what kind of code and variables I can come up with.
| |
doc_23530637
|
-- search field --
<div id="search_field" >
<%= search_form_for @search, :id => "search_form" do |f| %>
<div id="field">
<%= f.text_field :date_cont , :id => 'search_box' %>
</div>
<%= f.submit %>
<% end %>
-- result field -
<div id="image">
<%= render partial: 'image', format: 'js' %>
I have created a partial image with this code
<% @posts.each do |post| %>
<td><%= image_tag post.name %></td>
and my controller is
def index
if params[:q]
@search=Post.search(params[:q])
@posts = @search.result
else
@posts=Post.where(date: Date.today.strftime("%Y-%m-%d"))
end
everything is working fine now what I want is when I click on the date entire page is reloading I want only the partial "image" has to be reloaded and give the resultant Image . What should I do? how to call This partial via Ajax?
end
A: Add a parameter
remote: true
to your form tag.
I'm on a cell phone now, can't explain better. Google 'Rails form remote true', you'll find a tutorial to follow.
| |
doc_23530638
|
A: jquery does not add duplicates to the list.
var $test = $('.comment-copy')
$test.add($test)
does not duplicate the list
A: From the docs:
Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method.
So it's a union (removes duplicates), not a simple concatenation.
| |
doc_23530639
|
idx = (replaced['Result']==0)
replaced.loc[idx,['A1','A2']] = replaced.loc[idx,['A2','A1']].values
replaced.loc[idx,['B1','B2']] = replaced.loc[idx,['B2','B1']].values
replaced.loc[idx,['C1','C2']] = replaced.loc[idx,['C2','C1']].values
replaced.loc[idx,['D1','D2']] = replaced.loc[idx,['D2','D1']].values
Can I do this in a single line? Or is there any other way to shorten all these lines?
A: What's wrong with
replaced.loc[idx,['A1','A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']] = replaced.loc[idx,['A2','A1', 'B2', 'B1', 'C2', 'C1', 'D2', 'D1']].values
It almost looks like just renaming the columns could work, in which case you could use a list comprehension that just switches the numbers in the column names.
| |
doc_23530640
|
HOWEVER, what I need to do is find a way to pass on the primary key of the individual name they have selected. I have the primary key in the SQL statement, but am not clearly thinking of a way that I can bring it in to the javascript so that I can pass it on to the next page for post processing.
Any help would be appreciated. Let me know if more information is needed.
A: You should put the primary key in the value attribute of the option tag, and the display name of the team in the html attribute.
<select>
<option value='id' >Team 1</option>
</select>
Then just pass around the id, and look up the name before you send it back to the html.
| |
doc_23530641
|
Invalid remote: origin: Invalid remote: origin
According to this: http://youtrack.jetbrains.com/issue/IDEA-77239 writing .git at the end of address should solve the problem but actually it does not.
I have totally no idea how to resolve it further. Any ideas?
Edit: And I use Windows. It seems like an important piece of information to add.
A: Using Eclipse / Indigo, with the Maven plugin:
*
*Check out Maven Projects from SCM
*assuming that the git SCM plugin is installed, select "git" from the SCM URL: popup
*enter, e.g.:
https://<username>@github.com/<username>/<projectname>.git
having @ and ".git" is important
*assuming that the project is private, you will be prompted for the password
This should be good enough to move forward.
A: This error can occur when there is an underlying SSH authentication issue, like having the wrong public key on the git remote server or if the git remote server changed its SSH host key.
Eclipse will use the .ssh directory you specify in Preferences -> General -> Network Connections -> SSH2 for its ssh configuration. Set it "{your default user directory}.ssh\" .
To fix things, first you need to determine which ssh client you are using for Git. This is stored in the GIT_SSH environmental variable. Right-click on "Computer" (Windows 7), then choose Properties -> Advanced System Settings -> Environment Variables.
If GIT_SSH contains a path to plink.exe, you are using the PuTTY stack.
*
*To get your public key, open PuTTYgen.exe and then load your private key file (*.ppk). The listed public key should match the public key on the git remote server.
*To get the new host key, open a new PuTTY.exe session, and then connect to git@{git repo host}.
*Click OK and say yes to store the new key.
*Once you get a login prompt, you can close the PuTTY window. The new key has been stored.
*Restart Eclipse.
If GIT_SSH contains a path to "ssh.exe" in your "Git for Windows" tree, you are using Git for Windows's OpenSSH.
*
*Set %HOME% to your default user directory (as listed in Eclipse; see above).
*Set %HOMEDRIVE% to the drive letter of your default user directory.
*Set %HOMEPATH% to the path to your default user directory on %HOMEDRIVE%
*To get your public key, open the file %HOMEDRIVE%%HOMEPATH%/.ssh/id_rsa.pub (or id_dsa.pub) in a text editor. The listed public key should match the public key on the git remote server.
*To get the new host key, run: cmd.exe
*Run Git Bash
*Ctrl-C
*At the bash prompt, run /c/path/to/git/for/windows/bin/ssh.exe git@{git remote host}.
*Type yes to accept the new key.
*Once you have a login prompt, type: ctrl-c
*Close the cmd.exe window
*Restart Eclipse.
Finally, if you are still having trouble with your external ssh client, delete the GIT_SSH environmental variable and set the HOME environmental variable to your default user directory on Windows. Without the GIT_SSH variable, EGit will use its internal ssh client (java). It will use the .ssh directory you specified above as its SSH configuration directory.
Note: If you have Git for Windows, you can use its tools to create a SSH key pair your .ssh directory:
*
*Set %HOME% to your default user directory (as listed in Eclipse).
*Set %HOMEDRIVE% to the drive letter of your default user directory.
*Set %HOMEPATH% to the path to your default user directory on %HOMEDRIVE%
*Run Git Bash
*Ctrl -C
*Run: ssh-keygen.exe -t rsa -b 2048
*Save to the default filenames
*Choose a passphrase or save without one. If you save with a passphrase, Eclipse will prompt you for it each time you push or pull from your git remote server.
*Close Git Bash
You can also use the GUI in the SSH2 Preference pane in Eclipse to manage hosts and keys.
A: May be your git server has moved?
A: check out your .git/config this error can occur is your missing ".git" at the end of your origin url
[remote "origin"]
url = https://some.domain.com/repo/name
should be
[remote "origin"]
url = https://some.domain.com/repo/name.git
A: This Error may occur due to following reasons -
*
*Check the repository url, there should be a '.git' appended in the end.
*In case your network configurations have changed, make sure you have correct proxy configuration, and in case of secured git repository, make sure you provide correct credentials. (I got this error when my credentials were changed, and also when i had incorrect proxy configured.)
PS - To check network settings, go to Windows -> Preferences -> General -> Network Connections. Also if you're unsure of network settings or proxy config, you can try switching between Direct and Manual network settings.
| |
doc_23530642
|
In my program,
I want a message box to pop up either immediately a duplicate value is selected or when the OK button is pressed.
The code below is an if statement that only works when other combo boxes duplicate the selectedvalue in the first combo box.
Is there a shorter way than this long if statement? and I want to be able to validate every other combo box so they won't have a duplicate. P.S I want the pop up to keep coming up till a unique value is selected. cbosort1,2,3..are the combo boxes names respectively.
if (cboSort1.SelectedValue == cboSort2.SelectedValue || cboSort1.SelectedValue == cboSort3.SelectedValue || cboSort1.SelectedValue == cboSort4.SelectedValue || cboSort1.SelectedValue == cboSort5.SelectedValue)
{
MessageBox.Show("you cannot choose a duplicate column", "duplicate error");
return;
}
A: var comboboxes = new[] { cboSort1, cboSort2, ...... };
bool dup = comboboxes.GroupBy(c => (string)c.SelectedValue).Any(g => g.Count() > 1);
OR
bool dup = comboboxes.GroupBy(c => (string)c.SelectedValue).Count() < comboboxes.Length;
A: You can first detect the dupe values and then check if your cb1-5 is it:
using System;
using System.Data;
using System.Linq;
namespace SO
{
public class ComboBox { public string SelectedValue; }
public class Program
{
public static void Main(string[] args)
{
var cboSort1 = new ComboBox { SelectedValue = "not a dupe" };
var cboSort2 = new ComboBox { SelectedValue = "also not a dupe" };
var cboSort3 = new ComboBox { SelectedValue = "this is a dupe" };
var cboSort4 = new ComboBox { SelectedValue = "no dupe here" };
var cboSort5 = new ComboBox { SelectedValue = "this is a dupe" };
var boxes = new[] { cboSort1, cboSort2, cboSort3, cboSort4, cboSort5 };
var dupes = boxes
.GroupBy(cb => cb.SelectedValue) # groups by the value
.Where(grp => grp.ToList().Count > 1) # this value has more then 1
.Select(grp => grp.Key); # just select the SelectedValue
// now you just check if your CB has this selectedValue:
if (dupes.Any(d => d == cboSort1.SelectedValue))
Console.WriteLine("CB1 is a dupe");
if (dupes.Any(d => d == cboSort2.SelectedValue))
Console.WriteLine("CB2 is a dupe");
if (dupes.Any(d => d == cboSort3.SelectedValue))
Console.WriteLine("CB3 is a dupe");
if (dupes.Any(d => d == cboSort4.SelectedValue))
Console.WriteLine("CB4 is a dupe");
if (dupes.Any(d => d == cboSort5.SelectedValue))
Console.WriteLine("CB5 is a dupe");
}
}
}
Output:
CB3 is a dupe
CB5 is a dupe
| |
doc_23530643
|
Weird one, my client whom I have set up a WooCommerce website with wants to sell only products through their personal trainers, but allow any user to see them.
So I'm not sure of the best way to approach this. I was thinking of using the Coupon code input and doing some sort of check to see if the user added a specific code into it then show the shop purchase buttons, or else show a message like 'Your trainer needs to buy these!'
Thanks
GB
| |
doc_23530644
|
For Example
PK Col1 Col2
1 A B
2 A B
3 C C
4 C C
I want a return:
PK Col1 Col2
1 A B
3 C C
I tried following code but it didn't work:
DataTable dt = GetSampleDataTable(); //Get the table above.
dt = dt.Select("SELECT MIN(PK), Col1, Col2 GROUP BY Col1, Col2);
A: dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();
A: DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.
You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.
dt = dt.AsEnumerable()
.GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
.Select(g => g.OrderBy(r => r["PK"]).First())
.CopyToDataTable();
A: dt.AsEnumerable()
.GroupBy(r => new { Col1 = r["Col1"], Col2 = r["Col2"] })
.Select(g =>
{
var row = dt.NewRow();
row["PK"] = g.Min(r => r.Field<int>("PK"));
row["Col1"] = g.Key.Col1;
row["Col2"] = g.Key.Col2;
return row;
})
.CopyToDataTable();
A: This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.
var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);
A: Based on @Alfred Wallace's solution :
DataTable dt = new DataTable();
dt.Columns.Add("Col1");
dt.Columns.Add("Col2");
dt.Rows.Add("120", "34");
dt.Rows.Add("121", "34");
dt.Rows.Add("122", "34");
dt.Rows.Add("1", "345");
dt.Rows.Add("2", "345");
dt.Rows.Add("3", "345");
var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string xxx = "", yyy = "";
foreach (var k_group in grouped)
{
xxx += (string)(k_group.ElementAt(0)["Col1"]) + Environment.NewLine;
foreach (DataRow item_dr in k_group)
{
yyy += (string)(item_dr["Col1"]) + Environment.NewLine;
// or use WhatEverMethod(item_dr);
}
var zzz = k_group.Max(g => g["Col1"]);
var qqq = k_group.Key;
}
| |
doc_23530645
|
Any suggestion? Thanks
| |
doc_23530646
|
$headers = "From: " . strip_tags($mailfrom) . "\r\n";
$headers .= "Reply-To: ". strip_tags($mailfrom) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";`
without using the following lines mails are send successfully with html tags:
$headers = "From: " . strip_tags($mailfrom) . "\r\n";
$headers .= "Reply-To: ". strip_tags($mailfrom) . "\r\n";
How to resolve this?
A: Try like this
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .='From: '.$mailfrom . "\r\n";
$headers .='Reply-To: '.$mailfrom . "\r\n";
| |
doc_23530647
|
<a href="#workerPageForDetails" id="findAJobButton" data-role="button" data-inline="true" data-icon="search">Find a job</a>
I want the search icon to fill all the button if possible, resize it if not.
Can CSS or jQuery do that? How?
A: 32 x 32 pixel icons using CSS:
.ui-btn::after {
background-size: 32px !important;
width: 32px !important;
height: 32px !important;
}
A: You can replace the icon with your own custom icon and make it whatever size you want.
.ui-icon-search {
background-image: url('search.png');
width:24px;
height: 24px;
}
A: Try changing the background scale of the icon: background-size: 75%;
| |
doc_23530648
|
I was trying to find a way to do the same without the other array.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
void printAr(int[3][3]);
int main()
{
int A[3][3];
printf("Enter the numbers: \n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("\n-------------------------------\n");
printAr(A);
printf("Now transposing------------------\n");
for(int f=0;f<3;f++)
{
for(int h=0;h<3;h++)
{
int t=A[f][h];
A[f][h]=A[h][f];
A[h][f]=t;
}
}
printAr(A);
return 0;
}
void printAr(int B[3][3])
{
for(int k=0;k<3;k++)
{
for(int l=0;l<3;l++)
{
printf("%d ",B[k][l]);
}
printf("\n");
}
}
Here is the output:
Enter the numbers:
1
2
3
4
5
6
7
8
9
-------------------------------
1 2 3
4 5 6
7 8 9
Now transposing------------------
1 2 3
4 5 6
7 8 9
What am i doing wrong?
And why can't it transpose it?
A: In a transpose operation, every element of the upper-triangular submatrix gets swapped with one of the lower-triangular sub-matrix, and the diagonal elements don't move.
So a quick fix is
for(int f=0;f<3;f++)
{
for(int h=0;h<3;h++)
{
if (h<f)
{
int t=A[f][h];
A[f][h]=A[h][f];
A[h][f]=t;
}
}
}
But you can do that in a slightly better way...
A: Your transpose logic is wrong because your two loops will transpose the array twice resulting in the same array you have begin with. One of the solution is to copy the result in another array.
#include <stdio.h>
#include <stdlib.h>
void printAr(int[3][3]);
int main()
{
int A[3][3];
int B[3][3];
printf("Enter the numbers: \n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("\n-------------------------------\n");
printAr(A);
printf("Now transposing------------------\n");
for(int f=0;f<3;f++)
{
for(int h=0;h<3;h++)
{
int t=A[f][h];
B[f][h]=A[h][f];
}
}
printAr(B);
return 0;
}
void printAr(int B[3][3])
{
for(int k=0;k<3;k++)
{
for(int l=0;l<3;l++)
{
printf("%d ",B[k][l]);
}
printf("\n");
}
}
If you want to transpose without using second array try this.
#include <stdio.h>
#include <stdlib.h>
void printAr(int[3][3]);
int main()
{
int A[3][3];
printf("Enter the numbers: \n");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("\n-------------------------------\n");
printAr(A);
printf("Now transposing------------------\n");
for(int f=0;f<3;f++)
{
for(int h=f+1;h<3;h++)
{
int t=A[f][h];
A[f][h]=A[h][f];
A[h][f]=t;
}
}
printAr(A);
return 0;
}
void printAr(int B[3][3])
{
for(int k=0;k<3;k++)
{
for(int l=0;l<3;l++)
{
printf("%d ",B[k][l]);
}
printf("\n");
}
}
| |
doc_23530649
|
NOTE: I'm using NetworkImageView throughout the app. And I read somewhere that disk cache will be stored only when the image URL consists cache header. I want to know about that and also if no header in the URL like that then how to force the volley to store the disk cache of image ?
My code:
public class VolleySingletonPattern {
private static VolleySingletonPattern mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private VolleySingletonPattern(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(
LruBitmapCache.getCacheSize(mCtx)));
}
public static synchronized VolleySingletonPattern getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingletonPattern(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}}
My LruCache :
public class LruBitmapCache extends LruCache<String, Bitmap>
implements ImageCache {
public LruBitmapCache(int maxSize) {
super(maxSize);
}
public LruBitmapCache(Context ctx) {
this(getCacheSize(ctx));
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
@Override
public Bitmap getBitmap(String url) {
return get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
// Returns a cache size equal to approximately three screens worth of images.
public static int getCacheSize(Context ctx) {
final DisplayMetrics displayMetrics = ctx.getResources().
getDisplayMetrics();
final int screenWidth = displayMetrics.widthPixels;
final int screenHeight = displayMetrics.heightPixels;
// 4 bytes per pixel
final int screenBytes = screenWidth * screenHeight * 4;
return screenBytes * 3;
}}
A: I have used this this , and is working for me.
You need to add these permission.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
| |
doc_23530650
|
<asp:Button ID="Button1" runat="server" style="border:1px solid #456879;border-radius:5px;height: 22px;Width:150px" OnClick="Button1_Click" Text="Get Uploaded Data" Width="132px" />
and similarly after updating my gridview disappears but update happens so to again see the gridview i should again click the above button Get Uploaded Data,Finally in order to edit gridview data i need to click the button twice and in order to see the updated data again i need to click the button twice.How can i solve this
<asp:GridView ID="GridView2" runat="server" CellPadding="3" Font-Size="12px" Width="300px" Visible="false" OnRowEditing="GridView2_RowEditing" OnRowUpdating="GridView2_RowUpdating" OnRowCommand="GridView2_RowCommand" OnRowCancelingEdit="GridView2_RowCancelingEdit" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="Images/icon-edit.png" Height="32px" Width="32px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="Images/update1.jpg"/>
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="Images/cancel.jpg"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:templatefield headertext="sno">
<itemtemplate>
<asp:label id="lblid" runat="server" text='<%#DataBinder.Eval(Container.DataItem, "ID") %>'></asp:label>
</itemtemplate>
<edititemtemplate>
<asp:label id="lbleditid" runat="server" text='<%#DataBinder.Eval(Container.DataItem, "ID") %>'></asp:label>
</edititemtemplate>
</asp:templatefield>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary">
<ItemTemplate>
<asp:Label ID="lblSalary" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Salary") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditSalary" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Salary") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Designation") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Designation") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Location") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditLocation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Location") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.Cs Code
protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView2.EditIndex = e.NewEditIndex;
GridView2.DataBind();
GridView2.Visible = true;
}
protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblEditID = (Label)GridView2.Rows[e.RowIndex].FindControl("lblEditID");
TextBox txtEditName = (TextBox)GridView2.Rows[e.RowIndex].FindControl("txtEditName");
TextBox txtEditSalary = (TextBox)GridView2.Rows[e.RowIndex].FindControl("txtEditSalary");
TextBox txtEditDesignation = (TextBox)GridView2.Rows[e.RowIndex].FindControl("txtEditDesignation");
TextBox txtEditLocation = (TextBox)GridView2.Rows[e.RowIndex].FindControl("txtEditLocation");
con.Open();
string cmdstr = "update CodingLog1 set Name=@Name,Salary=@Salary,Designation=@Designation,Location=@Location where ID=@ID";
SqlCommand cmd = new SqlCommand(cmdstr, con);
cmd.Parameters.AddWithValue("@ID", lblEditID.Text);
cmd.Parameters.AddWithValue("@Name", txtEditName.Text);
cmd.Parameters.AddWithValue("@Salary", txtEditSalary.Text);
cmd.Parameters.AddWithValue("@Designation", txtEditDesignation.Text);
cmd.Parameters.AddWithValue("@Location", txtEditLocation.Text);
cmd.ExecuteNonQuery();
con.Close();
GridView2.EditIndex = -1;
GridView2.Visible = true;
GridView2.DataBind();
}
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView2.EditIndex = -1;
GridView2.Visible = true;
GridView2.DataBind();
}
Button code-
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = null; GridView1.DataBind();
string desi = Session["Role"].ToString();
string user = Session["Username"].ToString();
string selecteduser = ddlusers.SelectedItem.Text;
if (TextBox1.Text != "")
{
if (rdupldeddate.Checked == true)
{
DataTable dt = adm.GetRecordsByUploadedDate(user, TextBox1.Text, desi, selecteduser); //Uploaded date
if (dt.Rows.Count > 0)
{
if (desi == "Supervisor")
{
BtnExport.Visible = true;
GridView2.Visible = true;
GridView1.Visible = false;
GridView2.DataSource = dt;
GridView2.DataBind();
}
else
{
GridView2.Visible = false;
BtnExport.Visible = false;
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else { lblMsg.Visible = true; GridView1.Visible = false; GridView2.Visible = false; lblMsg.Text = "No Data Present!!!"; }
}
else
{
DataTable dt = adm.GetRecordsByCodedDate(user, TextBox1.Text, desi, selecteduser); //CodedDate
if (dt.Rows.Count > 0)
{
if (desi == "Supervisor")
{
BtnExport.Visible = true;
GridView2.Visible = true;
GridView1.Visible = false;
GridView2.DataSource = dt;
GridView2.DataBind();
}
else
{
GridView2.Visible = false;
BtnExport.Visible = false;
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else { lblMsg.Visible = true; GridView1.Visible = false; GridView2.Visible = false; lblMsg.Text = "No Data Present!!!"; }
}
}
else { lblMsg.Visible = true; lblMsg.Text = "Please Enter Date!!!"; }
}
I had tried all the possibilties by taking editindex=0 instead of -1, by calling my gridview2.databind in !ispostback moreover i had placed my gridview in update panel also but still its not working
A: Based on the code you pasted into the comments, the problem lies in your Page_Load event handler. The code that sets the initial visibility of the GridViews should be inside the if (!IsPostBack) block.
lblMsg.Text = "";
if (!IsPostBack)
{
BindUsers();
// Set the initial visibility of grids here
string desi = Session["Role"].ToString();
if (desi == "Supervisor")
{
GridView2.Visible = true;
GridView1.Visible = false;
ddlusers.Visible = true;
BtnExport.Visible = false;
}
else
{
GridView2.Visible = false;
GridView1.Visible = true;
ddlusers.Visible = false;
BtnExport.Visible = false;
}
}
Once you have set the visibility for those grids on the first page load, that setting will be maintained by the ViewState across postbacks. From that point on, it appears that your control events are managing the visibility of the grids (based on whether there are results to show, etc).
A: In your GridView2_RowUpdating, you are updating your data on the database and binding your GridView2 to nothing. That's why the GridView disappears. It has no data to show. While the button you click fetch the updated data and binds it to the GridView that's why it shows again. When you update the data, you should fetch the updated data and rebind it to your GridView again.
I suggest using DataSet and assign as Datasource before calling GridView2.DataBind();
SqlDataAdapter da = new SqlDataAdapter(cmdstr ,con);
da.SelectCommand.CommandType = CommandType.Text;
da.SelectCommand.Parameters.AddWithValue("@ID", lblEditID.Text);
da.SelectCommand.Parameters.AddWithValue("@Name", txtEditName.Text);
da.SelectCommand.Parameters.AddWithValue("@Salary", txtEditSalary.Text);
da.SelectCommand.Parameters.AddWithValue("@Designation", txtEditDesignation.Text);
da.SelectCommand.Parameters.AddWithValue("@Location", txtEditLocation.Text);
DataSet dsResult = new DataSet();
da.Fill(dsResult);
con.Close();
GridView2.DataSource = dsResult;
GridView.DataBind();
Or Call the codes in your button through a method after the update.
Try this if this works.
| |
doc_23530651
|
$sql=mysql_query("select * from updates ORDER BY update_time DESC LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['update_time'];
$message=$row['item_content'];
?>
<?php echo $message; ?>
<?php } ?>
has the same output as a variable, then do nothing. I'm only asking because i dont know how to put this amount of code into an if statement. If anyone knows please post, thanks :)
A: Instead of echoing $message in each iteration build a $messages string to use in your if:
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['update_time'];
$messages .= $row['item_content'];
}
if($messages != $old_messages) {
// do something
}
| |
doc_23530652
|
But today one of my clients discovered that in his opera browser the fonts are different. It's a computer font, I mean, you can't use that font by css, it's some custom font.
in CSS file, for that text fonts and as a default Body font I have sylfaen, calibri, georgia, helvetica, arial; and suddenly the fonts are not even closer to one of the fonts mentioned in my CSS.
one more thing is that, in some places we have sylfaen, and in some cases that stupid font.
What can be the problem?
body { background: url(../images/intro_bg.jpg) top center; background-attachment:fixed; margin:0; padding:0;
font:normal 12px Calibri, Sylfaen, Georgia, Tahoma, Arial; color:#898a8c; line-height: 140%; }
img { border: none; }
.wrapper { width:1001px; height:554px; position:absolute; top:0; bottom:0; left:0; right:0; margin:auto; }
#wrapper { width:1000px; margin:0px auto 0px auto; position: relative;}
.flash { background-color: #fff; width:343px; height:554px; float:left; }
.form { background:url(../images/intro.jpg); width:624px; height:554px; float:right; }
.date { margin-top:372px; padding-left:120px; }
.date input { background:url(../images/intro_form.png) top center no-repeat; width:92px; height:50px; border:none;
font:normal 40px/50px Calibri, Sylfaen, Georgia, Tahoma, Arial; color: #939598; text-align:center; margin-right:9px; }
.country { margin-top:38px; width:213px; margin-left:85px; }
.country select { height:18px; width:213px; font:normal 12px/18px Calibri, Sylfaen, Georgia, Tahoma, Arial; color: #939598; }
p.buttons { margin: 50px 0 0 0; padding-left: 2px;}
p.buttons input.geo { background:url(../images/geo.png) no-repeat; width:113px; height:24px; border:none; margin-left: 6px; text-indent:-9999px; }
p.buttons input.geo:hover { cursor: pointer; }
p.buttons input.eng { background:url(../images/eng.png) no-repeat; width:113px; height:24px; border:none; margin-left: 8px; text-indent:-9999px; }
p.buttons input.eng:hover { cursor: pointer; }
p.buttons input.rus { background:url(../images/rus.png) no-repeat; width:113px; height:24px; border:none; margin-left: 9px; text-indent:-9999px; }
p.buttons input.rus:hover { cursor: pointer; }
.shadow { background:url(../images/shadow.png) top center no-repeat; width:1034px; margin:0 auto; padding-top:0px; }
#header { width:1000px; height:305px; }
.header-top { background: url(../images/header-top.jpg) top center no-repeat; height:106px; width: 1000px; margin: 0 auto;}
.logo { width: 171px; height: 106px; margin:0 auto; }
.header-banner { width: 1000px; height: 159px; margin:0 auto; }
.menu-right { background:none; float: right; width:120px; height:40px; margin: 0 16px 0 0; }
#menu { background:#887b33; height:40px; width:1000px; margin:0; padding:0; }
.menu-main { list-style: none; margin: 0; padding: 0; height: 40px; width: 700px; float: left; }
.menu-main li { display:inline; border-right: solid 1px #a39961; }
.menu-main li:hover { display:inline; border-right: solid 1px #a39961; }
.menu-main li img { display:none; }
.menu-main ul
{
position:relative;
width:200px;
z-index:500;
display:none;
margin:0;
border:none;
}
.menu-main ul ul
{
top:0;
left:100%;
border:none;
}
div#menu li:hover ul ul,
div#menu li li:hover ul ul,
div#menu li li li:hover ul ul,
div#menu li li li li:hover ul ul
{display:none; border:none; }
div#menu li:hover ul,
div#menu li li:hover ul,
div#menu li li li:hover ul,
div#menu li li li li:hover ul
{display:block; border:none; }
div#menu li ul li { height: 20px; border:none; }
div#menu li ul li a{ background: #b1a676; color: #fff; height: 30px; font: normal 12px/30px Sylfaen, Calibri, Georgia, Arial, Verdana; text-decoration: none;
text-indent: 8px; border:none;
-webkit-box-shadow: 0 10px 15px rgba(0,0,0,.1);
-moz-box-shadow: 0 10px 15px rgba(0,0,0,.3);
box-shadow: 0 8px 12px rgba(0,0,0,.1); }
div#menu li ul li a:hover { background: #887b32; color: #fff; border:none; }
div#menu div.menu-right div#jflanguageselection ul.jflanguageselection { width:120px; margin:0; padding:0; margin-top: 11px; text-align: right;
margin-right: -5px; float:right; }
div#menu div.menu-right div#jflanguageselection ul.jflanguageselection li{ width:20px; margin:0; padding:0; display:inline; margin-right: 5px; }
div#menu div.menu-right div#jflanguageselection ul.jflanguageselection li a{ font: normal 14px calibri, georgia, sylfaen, verdana;
text-decoration: none; color:#fff; text-transform: uppercase; }
#content-holder { background:#fff url(../images/cont_shd.png) top center repeat-x; width:964px; padding:25px 18px 20px 18px; }
.left { width:111px; float:left; margin:0; padding:0; margin-right:17px;}
.left-menu { width:145px; float:left; margin:0; padding:0; background: #fff; margin-left:-18px; }
.left-menu2 { width:145px; float:left; margin:0; padding:0; background: #fff; margin-left:-18px; }
.right { width:111px; float:right; margin:0; padding:0; }
.right img { margin-bottom:20px;}
.content-main { width:677px; float:left; border-left:solid 1px #c5c7c8; border-right: solid 1px #c5c7c8;
padding: 0 14px; }
.content-main-wine { width:810px; float:left; border-left:solid 1px #b2b4b6; border-right: solid 0px #8a8d08;
padding: 0 0 0 14px; }
.content-search { width:677px; float:left; border-left:solid 1px #c5c7c8; border-right: solid 1px #c5c7c8;
padding: 0 14px; min-height:450px; }
#article { width:677px; border-bottom:solid 1px #c6c785; padding: 0 0 20px 0; margin: 0 0 20px 0; }
.article-image { width:148px; float:left;}
.article-cont { width:510px; float:right; }
.art-title { margin: -5px 0 5px 0; font:normal 20px Sylfaen, Calibri, Georgia, Tahoma, Arial; color:#8a8e06; }
.art-text { margin:0; }
.read-more { margin: 5px 0 0 0; }
.read-more a { font:normal 12px Calibri, Sylfaen, Georgia, Tahoma, Arial; color:#7c202b; text-decoration:none; }
#bot_cont { background: #35311c; width: 964px; height:150px; padding: 15px 18px 15px 18px; }
.holder { float: left; margin-right: 15px; }
.holder h3 { color: #8b8e09; font: bold 14px Calibri, Sylfaen, Georgia, Tahoma, Arial; border-right: solid 2px #887b32; margin: 0 0px 10px 0; width:140px }
.holder ul.lists { width:140px; float: left; margin:0; padding:0; margin-right:15px; }
.holder ul.menu-lists { width:140px; float: left; margin:0; padding:0; margin-right:15px; }
.holder ul.small { width: 80px; }
.holder ul.menu-lists li { list-style:none; margin-bottom:0px; }
.holder ul.menu-lists li { list-style:none; margin-bottom:0px; }
.holder ul.lists li { list-style:none; margin-bottom:0px; }
.holder ul.menu-lists li a { color: #fff; font: normal 13px Sylfaen, Calibri, Georgia, Tahoma, Arial; line-height: 130%; text-decoration:none; }
.holder ul.lists li a { color: #fff; font: normal 13px Sylfaen, Calibri, Georgia, Tahoma, Arial; line-height: 130%; text-decoration:none; }
.holder ul.icons { float:left; margin:0; padding:0; }
.holder ul.icons li { display:inline; list-style:none; margin-right:15px; }
.holder h3.last { border: none; }
.buyonline { margin-top: 15px; float: left; height:29px; width:111px; }
#footer { background: #887b32; width: 1000px; height: 24px; margin-bottom: 0px; padding-top:6px; }
.copyright { margin: 0 0 0 10px; color: #fff; float: left; }
.developed { margin: 0 10px 0 0; color: #fff; float: right; }
.developed a { color: #fff; text-decoration:none; }
.tree ul { margin:0; padding:0; width:145px; list-style:none; }
.tree ul li ul { margin:0; padding:0; width:145px; list-style:none; }
.tree ul li ul li a { font: normal 12px/20px sylfaen, calibri, Georgia, "Times New Roman", Times, serif; color:#7b212b; display:block;
text-decoration:none; text-indent: 10px; margin-bottom: 1px; }
.tree ul li ul li a:hover { background-color: #b57978; color:#fff; }
.tree ul li ul li a.sublevel_active { background-color: #7b212b; color:#fff; }
.tree ul li ul li a#active_menu { background-color: #7b212b; color:#fff; }
.tree ul li ul li ul { margin:0; padding:0; list-style:none; }
.tree ul li ul li ul li { text-indent: 20px; }
.tree ul li ul li ul li a { background-color: #fff; font: normal 12px/20px sylfaen, calibri, Georgia, "Times New Roman", Times, serif;
color:#808285; display:block; text-transform:uppercase; text-decoration:none; margin-bottom: 1px; }
.tree ul li ul li ul li a:hover { background-color: #ada05a; color:#fff; }
.tree ul li ul li ul li a.sublevel_active { background-color: #887b32; color:#fff; }
.tree ul li ul li ul li a#active_menu { background-color: #887b32; color:#fff; }
.tree ul li ul li ul li ul { margin:0; padding:0; list-style:none; }
.tree ul li ul li ul li ul li a { background-color: #fff; font: normal 12px/20px sylfaen, calibri, Georgia, "Times New Roman", Times, serif;
color:#cbbc9a; display:block; text-transform:capitalize; text-decoration:none; text-indent: 28px; margin-bottom: 1px; }
.tree ul li ul li ul li ul li a:hover { background-color: #d3ceb1; color:#fff; }
.tree ul li ul li ul li ul li a.sublevel_active{ background-color: #cbbc9a; color:#fff; }
.tree ul li ul li ul li ul li a#active_menu{ background-color: #cbbc9a; color:#fff; }
.tree ul li ul li ul li ul li ul { margin:0; padding:0; list-style:none; }
.tree ul li ul li ul li ul li ul li a { background-color: #fff; font: normal 12px/20px sylfaen, calibri, Georgia, "Times New Roman", Times, serif;
color:#887b32; display:block; text-transform:capitalize; text-decoration:none; text-indent: 33px; margin-bottom: 1px; }
.tree ul li ul li ul li ul li ul li a:hover { background-color: #e2dec9; color:#fff; list-style:none; }
.tree ul li ul li ul li ul li ul li a.sublevel_active { background-color: #e2dec9; color:#fff; list-style:none; }
.tree ul li ul li ul li ul li ul li a#active_menu { background-color: #e2dec9; color:#fff; list-style:none; }
div.content-main-wine { color: #808285; text-align: left; }
div.content-main-wine h2 { font: normal 18px sylfaen, georgia, verdana, aria, calibri; margin: 0 0 10px 0; color: #000; }
#wineholder { width: 680px; border-bottom: solid 1px #c5c7c8; padding-bottom: 10px; float:left; margin-bottom:20px; }
#wineholder-large { width: 690px; border-bottom: solid 0px #c5c7c8; padding-bottom: 10px; float:left; }
#wineholder-large p { margin-bottom: 20px; }
.winesimage-small { float: left; border:0; }
.winesimage { float: left; border:0; margin-right:10px; }
.wine-title { color: #7b212b; font: normal 18px Sylfaen, Georgia, Calibri, Verdana, Arial; float: left; width: 577px;
margin-bottom: 5px; margin-top: -5px; margin-left: 3px; }
table.contentpaneopen h3 { color: #7b212b; font: normal 18px Sylfaen, Calibri, Georgia, Verdana, Arial; margin-bottom: 0px; margin-top:10px; }
.wine-descript-short h3 { color: #7b212b; font: normal 18px Sylfaen, Calibri, Georgia, Verdana, Arial; margin-bottom: 0px; margin-bottom:5px; }
table.contentpaneopen h4 { color: #808285; font: normal 18px Sylfaen, Calibri, Georgia, Verdana, Arial; margin-bottom: 0px; margin-top:10px; }
table.contentpaneopen h6 { color: #887b32; font: normal 18px Sylfaen, Calibri, Georgia, Verdana, Arial; margin-bottom: 0px; margin-top:10px; }
table.contentpaneopen tr td table tr td p { margin-bottom: 25px; line-height:160%; }
table.contentpaneopen tr td div p { margin-bottom: 17px; line-height:160%; }
table.contentpaneopen { width:100% }
.wine-descript-short { width: 577px; float: left; margin-left: 3px; text-align: left; }
.wine-descript-short p { margin: 0; }
p.readmore { float:left; margin: 25px 0 0 3px; }
p.readmore a { color: #cbbc9a; text-decoration: none; font: normal 12px Calibri, Sylfaen, Georgia, Arial; }
.redtext { color: #7c212a; }
.readon { color: #cbbc9a; text-decoration: none; }
.contact { width:300px; border-right: dashed 1px #c5c7c8; margin:0; padding:0; padding-right:10px; float: left; }
.contact a { color: #887b32; font: normal 12px Sylfaen, Calibri, Georgia, Verdana, Arial; text-decoration:none; }
.contact span { color: #35321c; font: normal 12px Sylfaen, Calibri, Georgia, Verdana, Arial; text-decoration:none; }
div.left-menu2 div.moduletable h3 { color: #887b33; font: bold 12px Sylfaen, Calibri, Georgia, Verdana, Arial; text-decoration:none; text-indent:17px;}
.menu-left2 { margin:6px 0 0 0; padding:0; list-style:none; width:145px; }
.menu-left2 li { list-style:none; width:145px; margin-bottom:1px; }
.menu-left2 li a {
background: #fff;
display: block;
padding: 2px 5px 2px 25px;
text-decoration: none;
/* text-indent: 25px; */
font: normal 12px/20px calibri, sylfaen, georgia, verdana;
color: #808285;
}
.menu-left2 li a:hover { background: #ada05a; color: #fff; }
.menu-left2 li.active a {
background: #887b33;
color: #fff;
}
.contact-form { width:385px; float: left; margin-left: 30px; }
input.rapid_contact.inputbox, #user_name_formAcymailing1, #user_email_formAcymailing1 { border-top: solid 1px #6d6f71; border-left: solid 1px #6d6f71; border-right: solid 1px #918f90; border-bottom: solid 1px #c9c8c8;
width:145px; color:#808285; font:normal 12px sylfaen, georgia, calibri, arial; }
input.rapid_contact.button, .subbutton { width:64px; height:21px; background:url(../images/send_btn.png) no-repeat; border:none; margin-top:8px; margin-left: -2px;
color: #fff; font: normal 12px/21px Sylfaen, Calibri, Georgia, Verdana, Arial; }
textarea.rapid_contact.textarea { border-top: solid 1px #6d6f71; border-left: solid 1px #6d6f71; border-right: solid 1px #918f90; border-bottom: solid 1px #c9c8c8;
width:252px; height:100px; }
span.contact-label { padding: 0 10px 0 0; }
.telianiworld, .telianiworld-details { margin:0; padding:0; list-style:none; margin-left:10px; }
.telianiworld { float:left; margin-right:60px; margin-left:10px; }
.telianiworld li { list-style:none; margin-bottom:6px; }
.telianiworld li a, .telianiworld-title { color: #7b212b; font: normal 13px Sylfaen, Georgia, Calibri, Verdana, Arial; text-decoration:none; text-transform: uppercase; margin:0; }
.telianiworld-link a { color: #887b33; font: normal 14px Sylfaen, Calibri, Georgia, Verdana, Arial; text-decoration:none; }
.telianiworld-details p { margin-bottom:0; }
.telianiworld-details p a { color: #887b33; font: normal 14px Sylfaen, Calibri, Georgia, Verdana, Arial; text-decoration:none; }
.menu-addition, .menu-addition li ul, .menu-addition li ul li ul { margin:0; padding:0; list-style:none; font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important; }
.menu-addition li { list-style:none; /* margin-bottom: 1px; */ font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important; }
.menu-addition li a {
background: #fff;
display: block;
padding: 2px 0 5px 18px;
text-decoration: none;
/* text-indent: 25px; */
font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important;
color: #7c222b;
margin-bottom:1px;
}
.menu-addition li a:hover { font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important;
background: #b57978;
color: #fff;
}
.menu-addition li.active a { font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important;
background: #7c222b;
color: #fff;
}
.menu-addition li ul li { margin-top:1px; margin-bottom:0; font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important; }
.menu-addition li ul li a, .menu-addition li ul li.item23 a, .menu-addition li ul li.item24 a,
.menu-addition li ul li.item25 a, .menu-addition li ul li.item26 a {
background: #fff;
display: block;
padding: 2px 5px 5px 25px;
text-decoration: none;
/* text-indent: 25px; */
font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important;
color: #808285;
}
.menu-addition li ul li.item23.active a, .menu-addition li ul li.item24.active a,
.menu-addition li ul li.item25.active a, .menu-addition li ul li.item26.active a { background: #887b32; color: #fff; font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif; }
.menu-addition li ul li.item23 a:hover, .menu-addition li ul li.item24 a:hover,
.menu-addition li ul li.item25 a:hover, .menu-addition li ul li.item26 a:hover { background: #ada05a; color: #fff; font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif; }
.menu-addition li ul li li { font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important; }
.menu-addition li ul li ul li.item27 a, .menu-addition li ul li ul li.item28 a, .menu-addition li ul li ul li.item29 a {
background: #ffffff !important;
display: block;
color: #bab186 !important;
padding: 2px 0 3px 40px;
text-decoration: none;
font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important;
}
.menu-addition li ul li ul li.item27 a:hover,
.menu-addition li ul li ul li.item28 a:hover,
.menu-addition li ul li ul li.item29 a:hover {
background: #d3ceb1!important;
display: block;
color: #fff !important;
padding: 2px 0 3px 40px;
text-decoration: none;
font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important;
}
.menu-addition li ul li ul li.item27.active a,
.menu-addition li ul li ul li.item28.active a,
.menu-addition li ul li ul li.item29.active a {
background: #bab186 !important;
display: block;
color: #fff !important;
padding: 2px 0 3px 40px;
text-decoration: none;
font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important;
}
.menu-addition li ul li ul li.item29 a, .menu-addition li ul li ul li.item29 a:hover, .menu-addition li ul li ul li.item29.active a { width: 102px; padding: 2px 4px 3px 40px; font: normal 10px sylfaen, calibri, Georgia, "Times New Roman", Times, serif !important; }
span.green { color:#887b32; }
span.pale { color:#cbbc9a; margin-top:20px; }
span.pale p { padding-left:0px; margin:0; }
.trading-left { float: left; width:543px; margin-top:0px; }
.trading-right { float: right; width:207px; margin-top:10px; margin-left:0px; }
.trading-right p { font: normal 12px sylfaen, georgia, arial, calibri; margin-bottom:20px; margin-top:0; }
.trading-right a { font: normal 12px sylfaen, georgia, arial, calibri; color:#7b212b; text-decoration:none; margin-top:0px; }
table.trading-cell { margin-top:0px; border-collapse: collapse; margin-bottom:20px; }
table.trading-cell tr { border-bottom: dashed 1px #c5c6c8; }
table.trading-cell tr td img { margin-left:25px; }
div.trad-title { width:145px; height:23px; font: normal 12px/23px sylfaen, georgia, arial, sylfaen;
color: #fff; text-align: right; float: left; background: #bbb187; padding-right: 5px; }
p.indent a { text-decoration:none; color:#887b32; margin-top:0; }
div.front-article { margin-top:-15px; margin-bottom:0; border-bottom: solid 1px #c5c7c8; padding-bottom:8px;}
div.archive-title { width:105px; }
div.archive-title a { color:#7b212b; font:normal 18px sylfaen, georgia, arial, calibri; float:left; text-decoration:none; }
div.archive-desc { color:#808285; font:normal 12px sylfaen, georgia, arial, calibri; float:right; width:705px; padding-right: 0px;}
#archive-list li { margin-bottom:20px; }
button.archive-btn { width:51px; height:21px; background:url(../images/select.jpg) no-repeat; border:none; margin-left: 10px;
color: #fff; font: normal 12px/21px Sylfaen, Calibri, Georgia, Verdana, Arial;}
.newsletter { width:300px; float:left; }
ul.menu-lists.siaxleebi { width:90px }
ul.menu-lists.galerchika { width:75px }
ul.menu-lists.investorebi { width:120px }
dl.system-message { display:none; }
.content-video { width:750px; padding: 0 0 0 0px; margin:0 auto; }
.gallery { width: 690px; padding: 0 10px 20px 0px; border-right: dashed 0px #c5c7c8; float: left; }
.content-photos { width:690px; padding: 0 0 0 0px; margin:0 auto; }
.moduletablegallery h3 { margin: 10px 0 10px 0; font: normal 12px Sylfaen, Georgia, Arial, Verdana, Calibri; color:#898a8c; }
.video-holder { float: left; width: 210px; margin:0 20px; }
.viewmorevids { margin: 0 0 0 10px; width: 500px; }
.viewmorevids a { font: normal 12px Sylfaen, Georgia, Arial, Verdana, Calibri; color:#7b212b; }
a.ytb img { vertical-align:bottom; margin-left:10px; }
.list-awards { width:110px; border-left: dashed 1px #b2b4b6; float: right; padding-left: 10px; }
.list-awards-wide { width:100px; border-left: dashed 1px #b2b4b6; float: right; padding-left: 10px; height:400px; }
.content-main-wine .jcb_fieldValue { line-height: 150%; }
.red-filter { display:block; width:60px; height:17px; background:#7c212a; margin-right: 4px;
font: normal 10px/17px sylfaen, georgia, arial, calibri; text-align: center; color:#fff; text-decoration:none; float:left; }
.white-filter { display:block; width:60px; height:17px; background:#887b32; margin-right: 4px;
font: normal 10px/17px sylfaen, georgia, arial, calibri; text-align: center; color:#fff; text-decoration:none; float:left; }
.rose-filter { display:block; width:75px; height:17px; background:#bc5168; margin-right: 4px;
font: normal 10px/17px sylfaen, georgia, arial, calibri; text-align: center; color:#fff; text-decoration:none; float:left; }
.icons a.pdf { display:block; background: url(../images/pdf_button.png) no-repeat; width:19px; height:21px; text-indent:-9999px; float:left; margin-right:3px; }
.icons a.print { display:block; background: url(../images/print_button.png) no-repeat; width:19px; height:21px; text-indent:-9999px; float:left; margin-right:3px; }
.icons a.email { display:block; background: url(../images/email_button.png) no-repeat; width:18px; height:15px;
text-indent:-9999px; float:left; vertical-align:bottom; margin-top:5px; margin-right:3px; }
.content-sitemap div.xmap { width:600px; margin:0 0 0 220px; }
.content-sitemap div.xmap ul li a { color:#454545; text-decoration:none; font:normal 12px Calibri, Sylfaen, Georgia, Tahoma, Arial; color:#898a8c; }
.content-sitemap div.xmap ul li a:hover { color:#62551a; text-decoration:none; }
.content-sitemap div.xmap ul.level_2 { display:none; }
div.search { width:140px; margin-top:55px; }
.search input.inputbox { border:none; background: url(../images/search_bg.png) no-repeat; width:85px; height:20px; padding-left:8px;
font: normal 12px/20px Calibri, Sylfaen, Georgia, Arial, Verdana; color:#454545; margin:0; vertical-align: top; }
.search input.button, button.searchbtn-search { border:none; background: url(../images/search_btn.png) no-repeat; width:24px; height:20px; text-indent:-9999px;
margin:0 0 0 -1px; vertical-align: top; }
input.searchbox-search { border:none; background: url(../images/search_bg-big.png) no-repeat; width:242px; height:20px; padding-left:8px;
font: normal 12px/20px Calibri, Sylfaen, Georgia, Arial, Verdana; color:#454545; margin:0; vertical-align: top; margin-right:-3px; margin-left:20px;}
span.awardlist-title { font: normal 18px/24px Sylfaen, Calibri, Georgia, Arial, Verdana; color:#7b212b; }
span.awardlist-desc { font: normal 18px/24px Sylfaen, Calibri, Georgia, Arial, Verdana; color:#808285;}
span.awardlist-mosavali { font: normal 18px/18px Sylfaen, Calibri, Georgia, Arial, Verdana; color:#887b32; }
div.awardlist-list { width:661px; border-bottom: solid 1px #b2b4b6; padding: 10px 0; height: 44px; margin-left: 42px; }
img.awardlist-image { float: right; }
span.awardlist-awardtitle { font: normal 12px Sylfaen, Calibri, Georgia, Arial, Verdana; color:#808285; float: left;
margin-top: 18px;}
.search-title { color:#62551a; font: normal 12px Sylfaen, Calibri, Georgia, Arial, Verdana; line-height:150%; }
.search-title:hover { text-decoration: underline }
p.search-options { margin-left:-6px; margin-bottom:0; }
p.results-search { margin-left:3px; }
#searchphraseall, #searchphraseany, #searchphraseexact {
background-color: #fff;
border: 0px dotted #9900FF; color: #ccc; }
.map-tabs { margin:-3px 0 0 0; padding:0; }
.map-tabs div.moduletable { margin:0; padding:0; }
.map-tabs p { margin:0; padding:0; }
.kaxeti-btn { background-color:#887b32; padding: 3px 10px; color:#fff; margin-right: 10px; }
.imereti-btn { background-color:#b79f72; padding: 3px 10px; color:#fff; margin-right: 10px; }
.racha-btn { background-color:#7c222b; padding: 3px 10px; color:#fff; margin-right: 10px; }
.shavi-btn { background-color:#008570; padding: 3px 10px; color:#fff; margin-right: 10px; }
.kartli-btn { background-color:#ca6419; padding: 3px 10px; color:#fff; margin-right: 10px; }
.tab-desc { color: #808285; font: normal 12px Sylfaen, Calibri, Georgia, Arial, Verdana; }
p.kaxeti { color: #887b32; font: normal 18px Sylfaen, Calibri, Georgia, Verdana, Arial; margin:0; margin-bottom: 0px; margin-top:10px; }
p.imereti { color: #b79f72; font: normal 18px Sylfaen, Calibri, Georgia, Verdana, Arial; margin:0; margin-bottom: 0px; margin-top:10px; }
p.racha { color: #7c222b; font: normal 18px Sylfaen, Calibri, Georgia, Verdana, Arial; margin:0; margin-bottom: 0px; margin-top:10px; }
p.shavi { color: #008570; font: normal 18px Sylfaen, Calibri, Georgia, Verdana, Arial; margin:0; margin-bottom: 0px; margin-top:10px; }
p.kartli { color: #ca6419; font: normal 18px Sylfaen, Calibri, Georgia, Verdana, Arial;margin:0; margin-bottom: 0px; margin-top:10px; }
Here's the code :)
A: Perhaps the user has set a default text for his browser? (Not sure if this is possible to overwrite all text, but i've heard of it, and otherwise they do it when they do not recognize the font)
Have you tested it yourself on Opera?
A: Are you using @font-face? if not - it is entirely possible that your client doesn't have the font installed in his system
A: Its worth pointing out that Calibri and Sylfaen were only added to Windows in Windows Vista. Users with older versions (XP, etc) may not have these fonts. In this case, it'll fall back to Georgia, which may give quite a different look.
Further, all of the fonts you specified are owned by Microsoft, so users of other operating systems may not have any of them.
In our site, we found that in order to support Calibri as the default font, we actually needed to make it available for download using the CSS @font-face declaration.
The basic syntax looks like this:
@font-face {
font-family: "CalibriForMac";
src: url("../fonts/calibri.ttf");
}
but you may want to read some of the many examples on the web, as there are a number of cross-browser and cross-operating-system issues with using @font-face.
Here's one page which discusses it: http://nicewebtype.com/notes/2009/10/30/how-to-use-css-font-face/
| |
doc_23530653
|
@Getter
@Setter
@ConfigurationProperties("kafka")
public class KafkaConnectionSettings {
private String bootstrapAddress = "dataflow-kafka:9092";
{
And trying to autowire it in other configuration-class. For example:
@Configuration
@AllArgsConstructor
public class KafkaProducerConfig {
private KafkaConnectionSettings kafkaSettings;
@Bean
public ProducerFactory<String, String> producerFactory() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(
ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,kafkaSettings.getBootstrapAddress());
}
}
But I receive the following exeption:
No qualifying bean of type 'com.app.config.kafka.KafkaConnectionSettings' available: expected single matching bean but found 2: kafkaConnectionSettings,kafka-com.app.config.kafka.KafkaConnectionSettings
Its a "little" strange, considering that in "com.app.config"-package I have a similar config:
@Getter
@Setter
@ConfigurationProperties("app")
public class FileSettings {
}
and this last authowired successfully in classes, annotated with @Service
What am I doing wrong?
A: The problem is solved. I forgot to add KafkaConnectionSettings.class in @EnableConfigurationProperties at my testclass
@ActiveProfiles("test")
@EnableConfigurationProperties({FileSettings.class, KafkaConnectionSettings.class})
@RunWith(SpringRunner.class)
@SpringBootTest
public class AppTest {
Sorry for not quite clear question.
| |
doc_23530654
|
Now the problem is the my client is building a few promo pages which basically allows the user to purchase an upgrade. This is fine but my client only wants one unique subscription by customer (with its associated membership).
So the agreed solution is that, on a purchase of any new subscription product, all other subscriptions should be cancelled. All associated membership deleted/cancelled and only the latest subscription should remain active with its accompanying membership.
So I have tried to build this solution but it is just not working, so any advise/direction would be most welcome.
What I have tried:
function wp56908_new_order_housekeeping ($order_id)
{
$args = array(
'subscriptions_per_page' => -1,
'customer_id' => get_current_user_id(),
);
$subscriptions = wcs_get_subscriptions($args);
foreach ($subscriptions as $subscription) {
$s_order_id = method_exists( $subscription, 'get_parent_id' ) ? $subscription->get_parent_id() : $subscription->order->id;
if ($s_order_id != $order_id) {
$cancel_note = 'Customer purchased new subscription in order #' . $order_id;
$subscription->update_status( 'cancelled', $cancel_note );
}
}
}
add_action( 'woocommerce_thankyou', 'wp56908_new_order_housekeeping', 10, 1 );
A: This is the support email I got from WooCommerce regarding the issue with the function wcs_get_subscriptions().
Thanks for contacting support and report us this issue!
I've tried it in a local install and I confirm that this seems to be a
bug! I've already reported it to our development team and a patch
should be included in next updates. By now, if you're in a real hurry
and want to get it working, you could search for this code (in
wcs-functions.php line 483):
// We need to restrict subscriptions to those which contain a certain
product/variation if ( ( 0 != $args['product_id'] && is_numeric(
$args['product_id'] ) ) || ( 0 != $args['variation_id'] && is_numeric(
$args['variation_id'] ) ) ) { $query_args['post__in'] =
wcs_get_subscriptions_for_product( array( $args['product_id'],
$args['variation_id'] ) ); }
And replace it with something like:
// We need to restrict subscriptions to those which contain a certain
product/variation if ( ( 0 != $args['product_id'] && is_numeric(
$args['product_id'] ) ) || ( 0 != $args['variation_id'] && is_numeric(
$args['variation_id'] ) ) ) { $prod_args = array( $args['product_id'],
$args['variation_id'] ); $prod_args = array_filter($prod_args,
function($prod_args) { return ($prod_args !== 0); });
$query_args['post__in'] = wcs_get_subscriptions_for_product(
$prod_args ); }
Please take in mind that this is not the ideal solution because you'll
be modifying our plugin's code directly and these changes can be lost
after updating, but if you feel comfortable with code and want to take
the risk as a temporary workaround until we add the proper patch in
our plugin, you can do it. ;)
Let me know if you need any help with this!
Thanks, Bernat
A: There's a new setting in the WC Subscriptions plugin which lets you limit to one active subscription. You can find more information here: https://woocommerce.com/document/subscriptions/store-manager-guide/#:~:text=Limit%20subscriptions,the%20subscription%20from%20the%20dropdown.
The end user will get the message:
“You have a subscription to this product. Choosing a new subscription will replace your existing subscription.”
| |
doc_23530655
|
import numpy as np
arr = np.array([1, 2, 3])
scale = lambda x: x * 3
scale(arr) # Gives array([3, 6, 9])
Contrast this with normal Python lists:
arr = [1, 2, 3]
scale = lambda x: x * 3
scale(arr) # Gives [1, 2, 3, 1, 2, 3, 1, 2, 3]
I'm curious as to how this is possible. Does a numpy array override the multiplication operator or something?
A: numpy.ndarray overloads the * operator by defining its own __mul__ method. Likewise for +, -, etc. This allows for vector arithmetic.
A: Its all about Overriding operators in numpy
You can learn numpy.arry here
Let us focus on your lamda function for each;
1. numpy array :
arr = numpy.array([1, 2, 3])
type(arr)
scale = lambda x: x * 3
scale(arr)
this takes each element from array
2. normal list:
a =[1,2,3]
type(a)
scale = lambda x: x * 3
scale(a)
this takes full list as x and multiplies the list here itself
A: These are two different objects which behaves differently when you use * operator on them.
*
*In the first case you generate a numpy array. In this case, * operator was overloaded for performing multiplication. i.e. every element will be multiplied by 3.
*In the second case you generate a list. In this case the * operator is treated as a repetition operator, and the entire list is repeated 3 times.
code example:
type(np.array([1,2,3]))
type([1, 2, 3])
result:
numpy.ndarray
list
| |
doc_23530656
|
Here is the code I'm working with:
const long b500mb = 65536000;
const long b1gb = 134217728;
public Main()
{
InitializeComponent();
}
//https://unitconverter.io/gigabits/bytes/1
private void Main_Load(object sender, EventArgs e)
{
var cDriveDirectories = new DirectoryInfo(@"C:\").GetDirectories()
.Where(f => !f.Attributes.HasFlag(FileAttributes.System))
.Where(w => w.FullName != @"C:\Windows")
.Select(f => f.FullName)
.ToList();
var filesOver1Gb = new List<FileInfo>();
foreach (var item in cDriveDirectories)
{
DirectoryInfo d = new DirectoryInfo(item);
var files = d.GetFiles("*", SearchOption.AllDirectories).Where(w => w.Attributes.HasFlag(FileAttributes.Normal)
&& w.Length > b1gb).ToList();
foreach (FileInfo file in files)
{
filesOver1Gb.Add(file);
}
}
}
How can I get around this error?
System.UnauthorizedAccessException: 'Access to the path 'C:\inetpub\history' is denied.'
A: After @zee's help:
I VS as an admin and then put a try/catch around the line of code that was failing and continued.
This code will obtain the information I need!
const long b500mb = 65536000;
const long b1gb = 134217728;
public Main()
{
InitializeComponent();
}
//https://unitconverter.io/gigabits/bytes/1
private void Main_Load(object sender, EventArgs e)
{
var cDriveDirectories = new DirectoryInfo(@"C:\").GetDirectories()
.Where(f => !f.Attributes.HasFlag(FileAttributes.System))
.Where(w => w.FullName != @"C:\Windows")
.Select(f => f.FullName)
.ToList();
var filesOver1Gb = new List<FileInfo>();
IList<string> unauthorizedFiles = new List<string>();
foreach (var item in cDriveDirectories)
{
DirectoryInfo d = new DirectoryInfo(item);
var files = new List<FileInfo>();
try
{
files = d.GetFiles("*", SearchOption.AllDirectories).Where(w => !w.Attributes.HasFlag(FileAttributes.System)
&& w.Length > b1gb).ToList();
}
catch (UnauthorizedAccessException)
{
// ignore error and continue to process files over 1gb.
}
foreach (FileInfo file in files)
{
filesOver1Gb.Add(file);
}
}
// get the total count in bytes to find out how many gbs we have etc.
long totalOver1Gb = 0;
foreach (var file in filesOver1Gb)
{
totalOver1Gb = totalOver1Gb + file.Length;
}
}
| |
doc_23530657
|
the method is not starting, it also does not display that no result was found
Table
<table id="table-anexo" class="table table-striped table-hover display" style="width:100%">
<thead>
<tr>
<th data-field="id"><span>DOCUMENTO</span></th>
<th data-field="tipo"><span>TIPO</span></th>
<th data-field="dt_anexo"><span>DATA ANEXO</span></th>
<!--<th data-field="acao" data-formatter="" data-events="" ><span>AÇÃO</span></th>-->
</tr>
</thead>
</table>
Function AJAX
function get_anexo_ajax(metodo, editando_id) {
var ticket_id = editando_id;
$.ajax({
type: 'POST',
data: {ticket_id : ticket_id},
url: 'ticket/get_anexo_all',
success: (function (data) {
console.log(data.anexo);
//$('#table-anexo').bootstrapTable({ data: data.anexo });
//$('#table-anexo').bootstrapTable('refresh')
$('#table-anexo').bootstrapTable('load', data.anexo);
}),
});
}
Data JSON
{"anexo":[{"id":"1","tipo":"jpg","dt_anexo":"2018-08-01 11:09:28","mensagem_id":"2","ticket_id":"1"}]}
A: I think data is the invalid format. And Set data-toggle="table" on a normal table. I tested, it run Ok. You can try:
<table id="table-anexo" data-toggle="table" class="table table-striped table-hover display" style="width:100%">
var obj = JSON.parse(data);
$('#table-anexo').bootstrapTable('load', obj.anexo);
| |
doc_23530658
|
A: Try using gotoxy(short int, short int) in the header file.
And use some coding relating to (up,down,left,arrow) key, just find out the ASCII values of that key. So, when user click up arrow once, the highlighted part should move upwards using textbackground(WHITE) and the scroll page should appear using if statement.
Remember to use input=getche(); that's the most important part. Don't use getch();
| |
doc_23530659
|
In the OLD solution, I have a soon-to-be deprecated console app that accesses my Azure-hosted DB to do some work. We had some new DB migrations in the new repository and had some work that required the console app, so I moved the app project over into a throwaway branch in the new repo just so I could build it with the latest migrations.
It compiles fine. However, when I try to run it, I ALWAYS get the The model backing the 'DataContext' context has changed error.
What's weird about this is that my code and my DB are on the same migration. I can even run the update-database command on that DB and it tells me that I have "no pending migrations". I did compares on the stored procedures in my visual studio and the DB and they are all equal. Same results when trying Add-Migration "SyncTest", it creates a migration with no changes.
I cannot delete the __MigrationHistory table because I need to run this console app on production servers and cannot afford to lose that data/have any downtime.
So if I am on the same migration step between my console app and my DB, then why is it still throwing this error? I dunno where else to check!
A: I don't know why it is happening in your particular case, but I did stumble across a way to turn off the error, put this line in your DbContext instance ctor:
Database.SetInitializer<YourDbContextClass>(null);
| |
doc_23530660
| ||
doc_23530661
|
import numpy as np
import pandas as pd
df = pd.DataFrame({
'Key1': ['one', 'one', 'two', 'three'] * 3,
'Key2': ['A', 'B', 'C'] * 4,
'Value1': np.random.randn(12),
'Value2': np.random.randn(12)
})
print df
Key1 Key2 Value1 Value2
0 one A 1.405817 1.307511
1 one B -0.037627 -0.215800
2 two C -0.116591 -1.195066
3 three A 2.044775 -1.207433
4 one B -1.109636 0.031521
5 one C -1.529597 1.761366
6 two A -1.349865 0.321454
7 three B 0.814374 2.285579
8 one C 0.178702 0.479210
9 one A 0.718921 0.504311
10 two B -0.375898 -0.379315
11 three C -0.822250 0.703811
I can pivot it so that I get the first key as rows and the second key as columns
pt = df.pivot_table(
index=['Key1'],
columns=['Key2'],
values=['Value1','Value2']
)
print pt
Value1 Value2
Key2 A B C A B C
Key1
one -0.076303 -0.899175 0.631831 -1.196249 0.339583 0.583173
three 0.105773 0.460911 -0.387941 0.697660 1.091828 1.447365
two 1.391854 0.499841 -0.422887 -0.366169 -0.230001 2.417211
How can flip it such that the values and columns are stacked by the column first and then the values, e.g.
A B C
Value1 Value2 Value1 Value2 Value1 Value2
one -0.0763 -1.19625 -0.89918 0.339583 0.631831 0.583173
three 0.105773 0.69766 0.460911 1.091828 -0.38794 1.447365
two 1.391854 -0.36617 0.499841 -0.23 -0.42289 2.417211
I've looked at MultiIndexes but I can't see how that would affect the layout in this way.
A: You can use MultiIndex.swaplevel and sort_index:
pt.columns = pt.columns.swaplevel(0,1)
pt = pt.sort_index(axis=1)
#pt = pt.sort_index(axis=1, level=0)
print (pt)
Key2 A B C
Value1 Value2 Value1 Value2 Value1 Value2
Key1
one 0.439076 -0.492287 -0.841044 0.435300 -0.490016 0.045178
three -0.975650 0.276097 0.617394 -0.553229 0.213254 -0.044848
two 0.291563 2.730831 -2.405110 -0.878826 -0.801219 0.908600
Another solution with DataFrame.swaplevel:
pt = pt.swaplevel(0,1, axis=1).sort_index(axis=1)
print (pt)
Key2 A B C
Value1 Value2 Value1 Value2 Value1 Value2
Key1
one 0.439076 -0.492287 -0.841044 0.435300 -0.490016 0.045178
three -0.975650 0.276097 0.617394 -0.553229 0.213254 -0.044848
two 0.291563 2.730831 -2.405110 -0.878826 -0.801219 0.908600
| |
doc_23530662
|
File hook.h:
class Hook : public Object {
public:
enum class Type {
…
};
…
}
File object.h:
class Hook;
class Object {
…
void notifyHooks(Hook::Type type, const std::string &arg);
…
}
An obvious attempt of a forward declaration would be enum class Hook::Type;. However, it doesn't work. Would Hook be a namespace, one could write:
namespace Hook {
enum class Type;
}
However, this notation fails for the class case. Here, it would not be seen as a forward declaration anymore but rather as a (quite empty) full declaration of Hook.
How to properly resolve this problem?
| |
doc_23530663
|
I enable draggable and droppable this way:
$(".draggable").draggable();
$(".droppable").droppable();
The problem is that with this the user can drag the div anywhere on the screen, including out of the droppable area.
How can I limit the boundary area for the draggable object?
A: $(function() { $( "#draggable" ).draggable({ containment: "window" }); });
of this code does not display.
Full code and Demo:
http://www.limitsizbilgi.com/div-tasima-surukle-birak-div-drag-and-drop-jquery.html
In order to limit the element inside its parent:
$( "#draggable" ).draggable({ containment: "window" });
A: Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV
buildDraggable = function() {
$( "#handle" ).draggable({
containment: '#thumbnail',
drag: function(event) {
var top = $(this).position().top;
var left = $(this).position().left;
ICZoom.panImage(top, left);
},
});
A: Use the "containment" option:
jQuery UI API - Draggable Widget - containment
The documentation says it only accepts the values: 'parent', 'document', 'window', [x1, y1, x2, y2] but I seem to remember it will accept a selector such as '#container' too.
A: See excerpt from official documentation for containment option:
containment
Default: false
Constrains dragging to within the bounds of the specified
element or region.
Multiple types supported:
*
*Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
*Element: The draggable element will be contained to the bounding box of this element.
*String: Possible values: "parent", "document", "window".
*Array: An array defining a bounding box in the form [ x1, y1, x2, y2 ].
Code examples:
Initialize the draggable with the containment option specified:
$( ".selector" ).draggable({
containment: "parent"
});
Get or set the containment option, after initialization:
// Getter
var containment = $( ".selector" ).draggable( "option", "containment" );
// Setter
$( ".selector" ).draggable( "option", "containment", "parent" );
A: $(function () {
$( ".droppable-area" ).sortable({
connectWith: ".connected-sortable",
containment: ".droppable-area", //(parent div)
stack: '.connected-sortable div'
}).disableSelection();
});
| |
doc_23530664
|
from Final_For_DB
Group by Account_Name
order by Indemnity_Cost desc;
I have three columns in my FINALFOR_DB, which are:
*account_name
*indemnity_paid
*claim_count
I want to write a query that will give me the top 10 values that are grouped by account_name. Indemnity cost is calculated by dividing indemnity_paid by claim_count to get the exact cost.
Can anyone help me with this?
Edit:
Now I have this:
SELECT TOP 10 [FINAL_FOR_DB].[Indemnity_Paid]/[FINAL_FOR_DB].[Claim_Count] AS Indemnity_Cost, final_for_db.Claimant_Name, final_for_db.Account_Name, final_for_db.Claim_ID, final_for_db.File_Date, final_for_db.Resolution_Date, final_for_db.Claim_Status, final_for_db.State_Filed, final_for_db.Expense_Amount
FROM final_for_db
GROUP BY [FINAL_FOR_DB].[Indemnity_Paid]/[FINAL_FOR_DB].[Claim_Count], final_for_db.Claimant_Name, final_for_db.Account_Name, final_for_db.Claim_ID, final_for_db.File_Date, final_for_db.Resolution_Date, final_for_db.Claim_Status, final_for_db.State_Filed, final_for_db.Expense_Amount
HAVING (((final_for_db.Account_Name)="Exxon"))
ORDER BY [FINAL_FOR_DB].[Indemnity_Paid]/[FINAL_FOR_DB].[Claim_Count] DESC;
I would like to know if it's possible to have top 10 claims for each account in one query. In this one I had to use a condition that had Exxon as Account name.
A: You didn't explicitly state it, but I assume the above query did not do what you wanted.
This would probably be because calculations from the select cannot be reused in clauses such as order by, where, etc.
You would need to explicitly perform the calculation again in those subsequent clauses, wherever it is needed.
A: I'm not sure if its faster in terms of performance(tbh never tested): I would use:
select T1.* from
(Select Top 10 Account_Name, Indemnity_Paid/Claim_Count as Indemnity_Cost
From Final_For_DB
WHERE account_name = "account_name"
) AS T1
Order By T1.Indemnity_Cost DESC;
ALSO: Access SQL requires aggregation function for all fields involved in a Group function. I would write your SQL something like this:
select T1.* from
(Select Top 10 Account_Name, sum(Indemnity_Paid)/sum(Claim_Count) as Indemnity_Cost
From Final_For_DB
WHERE account_name = "condition"
Group By Account_Name) AS T1
Order By T1.Indemnity_Cost DESC;
Since you are groping by account_name you should also sum the "indemnity_paid" & claim_count field across all matched rows unless that field are already a calculated field in your table/query. in that case you can simply use the first method but also sort by account_name
| |
doc_23530665
|
sock=CFSocketCreate(NULL, PF_INET, SOCK_DGRAM, IPPROTO_UDP, kCFSocketDataCallBack|kCFSocketWriteCallBack|kCFSocketConnectCallBack, sockCallback, &sock_ctx);
then am setting up a loop
sockref=CFSocketCreateRunLoopSource(NULL, sock, 0);
CFRunLoopAddSource(CFRunLoopGetMain(), sockref, kCFRunLoopCommonModes);
and connecting to the address
CFDataRef adrref=CFDataCreate(NULL, (const UInt8 *)&adr, sizeof(adr));
CFSocketError err=CFSocketConnectToAddress(sock, adrref,-1);
if i have callback kCFSocketWriteCallBack i send the required data
CFDataRef bufref=CFDataCreate(NULL, buffer, scl->NTP_PACKET_SIZE);
CFSocketError error = CFSocketSendData(scl->sock, NULL, bufref,3);
everything until here works perfect.My actual problem is at
else if(callbackType==kCFSocketDataCallBack)
9/10 times is working ok. server sending the response and my process continues. the problem is that am waiting for data to come to actual continue my app logic. if no data come kCFSocketDataCallBack is not triggered and app waiting for ever. Is there a way for me to put a timeout at waiting to receive data?( without having by myself a NSTimer to reconnect to the pool)
A: I think the important thing to know here is that UDP is inherently unreliable.
It is therefore absolutely possible and normal behaviour that packets get lost and that you sometimes do not get a response. You mention 9 out of 10 times it works, that sounds pretty good for a UDP based protocol.
So I think you really need to make your code a little smarter. I also think there is no way around using a timer to find out if you actually received a response within a certain amount f time.
Fortunately it is very easy to schedule a CFRunLoopTimer on your loop. What you need to do is this:
*
*When you call CFSocketSendData for the first time you also add a CFRunLoopTimer.
*When you receive a kCFSocketDataCallBack callback you cancel the timer
*If you never receive a response, or if the response comes in really late, your timer will fire. So you can simply send the packet again from time timer callback and schedule it again with CFRunLoopTimerSetNextFireDate
You can keep a counter around that you increment every time you send a packet. Then you can give up after a certain amount of tries.
This is a little more code but it will make your UDP based app much more reliable.
| |
doc_23530666
|
Upon clicking the third button, I am fetching the value of that resource, changing it(200, all edges) and applying it statically for first button and dynamically for second but still it's picking up the old value(10) for the button which is using it dynamically. For Buttton using it statically it was supposed to fetch the old value (10) but I thought just because the second button is fetching it dynamically, it will reflect the change(200).
<Window x:Class="WpfApplicationUnleashed.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace:WpfApplicationUnleashed"
Title="Window1" >
<Window.Resources>
<Thickness x:Key="BadiThickness">10</Thickness>
</Window.Resources>
<StackPanel>
<Button x:Name="cmdStatic" HorizontalAlignment="Center" >
I am Static
</Button
<Button x:Name="cmdDynamic" HorizontalAlignment="Center" >
I am Dynamic
</Button>
<Button x:Name="cmdChanger" HorizontalAlignment="Center" Click="cmdChanger_Click">
I am Changer
</Button>
</StackPanel>
</Window>
Code:
private void cmdChanger_Click(object sender, RoutedEventArgs e)
{
Thickness th = (Thickness)this.FindResource("BadiThickness");
th.Bottom = 200;
th.Top = 200;
th.Left = 200;
th.Right = 200;
cmdDynamic.SetResourceReference(Button.MarginProperty, "BadiThickness");
cmdStatic.Margin = (Thickness)this.FindResource("BadiThickness");
}
A: You do realize that Thickness is a value type and that is why when you change it's value, it won't be affected in the resource.
What you can do to set that resource's value is following:
this.Resource["BadiThickness"] = new Thickness(200);
On a side note, please avoid using Hindi in a resource's name. That may mislead.
| |
doc_23530667
|
table 1 has G_Id, G_y
table 2 has S_ID, G_ID(FK), S_Date
Table 3 has N_ID, S_ID(FK), N_Date
I wanted to create the trigger after an update on Table 3
for any new N_date (table3) update Table 1 G_y(not a date) by calculating (N_date - S_date) * 11
I can't figure it out.
A: Assuming that you're using MySQL you can do it like this
CREATE TRIGGER n_date_insert_trigger
AFTER INSERT ON table3
FOR EACH ROW
UPDATE table1 t1 JOIN
(
SELECT g_id, DATEDIFF(NEW.n_date, s_date) * 11 g_y
FROM table2 t2
WHERE s_id = NEW.s_id
) q ON t1.g_id = q.g_id
SET t1.g_y = q.g_y;
CREATE TRIGGER n_date_update_trigger
AFTER UPDATE ON table3
FOR EACH ROW
UPDATE table1 t1 JOIN
(
SELECT g_id, DATEDIFF(NEW.n_date, s_date) * 11 g_y
FROM table2 t2
WHERE s_id = NEW.s_id
) q ON t1.g_id = q.g_id
SET t1.g_y = q.g_y;
Here is SQLFiddle demo
| |
doc_23530668
|
"columnOptionsSection": {
"additionalColumns": [
{
"ColumnName": "MachineName",
"DataType": "nvarchar",
"DataLength": 100
}
]
}
and I have "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ] further down (and it works fine with File sink).
The log is written but MachineName column is NULL. @AlexRiabov states that the current version of the sink doesn't have doesn't have Microsoft.Extensions.Configuration support. This is contradicted by the documentation which has an entire section devoted to it. He also states that updating to the latest dev version resolves the issue - however, that version throws exceptions so I can't use it.
So my questions...
*
*Is it possible to define custom columns to use with the MSSqlServer sink from appsettings.json? If so, how?
*Is Serilog.Sinks.MSSqlServer sink still being worked on? Last major release appears to have been over a year ago.
A: 5.1.3-dev-00236 worked for me
make sure you have the Environment enrichers library added
my appSettings json:
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"WriteTo": [{
"Name": "MSSqlServer",
"Args": {
"connectionString": --removed--,
"schemaName": "dbo",
"tableName": "Logs",
"autoCreateSqlTable": false,
"restrictedToMinimumLevel": "Debug",
"batchPostingLimit": 5,
"period": "0.00:00:02",
"columnOptionsSection": {
"addStandardColumns": [ "LogEvent" ],
"removeStandardColumns": [ "MessageTemplate", "Properties" ],
"additionalColumns": [
{
"ColumnName": "UtcTimeStamp",
"DataType": "datetimeoffset",
"AllowNull": false
},
{
"ColumnName": "MachineName",
"DataType": "nvarchar",
"DataLength": 128,
"AllowNull": false
}
]
}
}
}]
| |
doc_23530669
|
I couldn't find any callback that fits my purpose. It seems that after_initialize excluding after_find would have work.
How should I deal with this situation? Am I doing something smelly that Rails wasn't prepared for?
A: In the after_initialize callback you could check to see if the record is new or not via secret.new_record? Then, only generate your token for new records.
| |
doc_23530670
|
A: Imagick is a native php extension to create and modify images using the ImageMagick API. So doesn't retry any PDF's info but image's info:
Imagick::getNumberImages — Returns the number of images in the
object.
$pdf->getNumberOfPages(); //returns number of images that are equal to number of PDF's pages. This is a method from pdf-to-image package.
A PDF describes the content and appearance of one or more pages. It also contains a definition of the physical size of those pages. That page size definition is not as straightforward as you might think. There can in fact be up to 5 different definitions in a PDF that relate to the size of its pages. These are called the boundary boxes or page boxes.
The MediaBox is used to specify the width and height of the page. For the average user, this probably equals the actual page size.
Each page in a PDF can have different sizes for the various page boxes.
A PDF always has a MediaBox definition. All the other page boxes do not necessarily have to be present in regular PDF files.
The MediaBox is the largest page box in a PDF. The other page boxes can equal the size of the MediaBox but they are not expected to be larger (The latter is explicitly required in the PDF/X-4 requirements). If they are larger, the PDF viewer will use the values of the MediaBox.
You should be able to retrieve the exact "HiResBoundingBox" value (which is the MediaBox value in PDF).
A test document is A4 (210mm x 297mm) which is 595.28pt x 841.89pt and has four(4) pages.
The unit of these values is PostScript points (where 72 pt == 1 inch).
$pdf = "1.pdf";
$output = shell_exec("identify -format \"%[pdf:HiResBoundingBox]\" $pdf");
echo $output;
prints this String:
595.28x841.89+0+0595.28x841.89+0+0595.28x841.89+0+0595.28x841.89+0+0
with some REGEX you could get width:595.28pt and height:841.89pt for each page and convert them to millimeters.
A: How about this approach?
By Imagick I can easily get image from pdf file
$RESOLUTION = 300;
$myurl = 'filename.pdf['.$pagenumber.'];'
$image = new Imagick($myurl);
$image->setResolution( $RESOLUTION , $RESOLUTION );
$image->setImageFormat( "png" );
$image->writeImage('newfilename.png');
Now I have image from page of PDF file. I know resolution (number pixels per inch) and I can get width and height of image in pixels. So don't need to have deep knowledge in math to calculate width and height of page of PDF in inch:
$pdfPageWidth = $imageWidth / $RESOLUTION;
$pdfPageHeight = $imageHeght/ $RESOLUTION;
| |
doc_23530671
|
Note: This happens only when running app on my test device. When my it's ran while my test device is connected to Xcode, it never crashes.
This is the only code in my final view controller, other than viewDidLoad of course.
Code:
@IBAction func closeBtnPressed(sender: AnyObject) {
//dismissViewControllerAnimated(true, completion: nil)
self.navigationController?.popToRootViewControllerAnimated(true)
}
Any ideas? Thanks!
| |
doc_23530672
|
I installed the latest version of the Release plugin (2.0.2).
I get this error:
| Loading Grails 2.0.4
| Configuring classpath.
| Environment set to development.....
| Packaging Grails application.....
| Compiling 33 GSP files for package [myPackage].....
| Plugin packaged grails-plugin-myPlugin.jar
| Skipping POM generation because 'pom.xml' exists in the root of the project..
| Error Error executing script MavenDeploy: : Error downloading wagon provider from the remote repository: Missing:
----------
1) org.apache.maven.wagon:wagon-http:jar:1.0-beta-2
Try downloading the file manually from the project website.
Then, install it using the command:
mvn install:install-file -DgroupId=org.apache.maven.wagon -DartifactId=wagon-http -Dversion=1.0-beta-2 -Dpackaging=jar -Dfile=/path/to/file
Alternatively, if you host your own repository you can deploy the file there:
mvn deploy:deploy-file -DgroupId=org.apache.maven.wagon -DartifactId=wagon-http -Dversion=1.0-beta-2 -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]
Path to dependency:
1) unspecified:unspecified:jar:0.0
2) org.apache.maven.wagon:wagon-http:jar:1.0-beta-2
----------
1 required artifact is missing.
for artifact:
unspecified:unspecified:jar:0.0
from the specified remote repositories:
central (http://repo1.maven.org/maven2)
(Use --stacktrace to see the full trace)
Thanks for your help
A: I had the same problem and could handle it this way:
*
*Install Maven2
*Configure proxy as described here
This is enough to solve your problem.
If your maven server requires authentication you can proceed as described here or here
~/.m2/settings.xml:
<settings>
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>proxyserver.mydomain.com</host>
<port>8080</port>
<username>user</username>
<password>pass</password>
<nonProxyHosts>*.bla.com.br|*.blabla.biz</nonProxyHosts>
</proxy>
</proxies>
<servers>
<server>
<id>myrepo</id>
<username>user</username>
<password>pass</password>
</server>
</servers>
</settings>
A: I found a workaround for this issue. Since something tries to retrieve wagon-http dependency using deprecated http maven repository url, we can manually preinstall this dependency in our local repository:
mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get -Dartifact=org.apache.maven.wagon:wagon-http:1.0-beta-2 -Dpackaging=jar -DrepoUrl=https://repo1.maven.org/maven2
After that publish-plugin command should work.
Possible fix for that issue would be upgrade grails-release plugin to v3.1.3(didn't work for me): link
A: This looks like a Maven issue:
Maven fails to download a required dependency
org.apache.maven.wagon:wagon-http:jar:1.0-beta-2 from
http://repo1.maven.org/maven2
Since the required artifact can be found in Maven central this may be a result of a networking issue
| |
doc_23530673
|
Basically in the footer of the masterpage I want to create a link and the value of that I want to be editable per site collection. I read about resuable content list and I wonder if I can use it here, If not what other options I have?
A: I would suggest use a DVWP on master page that would solve your purpose as you can update the links in list and they would be updated in masterpage
| |
doc_23530674
|
it really is making me crazy for finding what did i do wrong in this code
what could be myy mistake here?
<?php
include("../mysql_connect.php");
if (isset($_POST['search_form'])) {
$page1 = $_GET['page'];
if ($page1 == "" || $page1 == 1) {
$page1 = 0;
}
else {
$page1 = ($page1 * 5) - 5;
}
$query = "select * from tbl_news where news_title like '$_POST[search]' || news_author like '$_POST[search]' ";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
?>
<table class="table table-hover" border="2">
<col width="50%"></col>
<col width="40%"></col>
<col width="20%"></col>
<tr>
<td rowspan="3">
a href="news_view.php?id=<?php echo $row['news_id']; ?>">
<img src="<?php echo $row['news_image_location'] . $row['news_image']; ?>" height="300" width="500">
</a>
</td>
<td>Title: <?php echo $row['news_title']; ?></td>
</tr>
<tr>
<td>Author: <?php echo $row['news_author']; ?></td>
</tr>
<tr>
<td>Date: <?php echo $row['news_date_filed']; ?></td>
</tr>
</thead>
</table>
<?php
}
$query1 = "select * from tbl_news where news_title like '$_POST[search]' || news_author like '$_POST[search]'";
$result1 = mysql_query($query1);
$row1 = mysql_num_rows($result1);
$pagecount = $row1 / 5;
$pagecount = ceil($pagecount);
for ($count = 1; $count <= $pagecount; $count++) {
?>
<a href="news.php?page=<?php echo $count; ?>"><?php echo $count ?></a>
<?php
}
}
else{
$page1 = $_GET['page'];
if ($page1 == "" || $page1 == 1) {
$page1 = 0;
}
else {
$page1 = ($page1 * 5) - 5;
}
$query = "select * from tbl_news where news_status='Active' limit $page1,5";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
?>
<table class="table table-hover" border="2">
<col width="50%"></col>
<col width="40%"></col>
<col width="20%"></col>
<tr>
<td rowspan="3">
<a href="news_view.php?id=<?php echo $row['news_id']; ?>">
<img src="<?php echo $row['news_image_location'] . $row['news_image']; ?>" height="300"
width="500">
</a>
</td>
<td>Title: <?php echo $row['news_title']; ?></td>
</tr>
<tr>
<td>Author: <?php echo $row['news_author']; ?></td>
</tr>
<tr>
<td>Date: <?php echo $row['news_date_filed']; ?></td>
</tr>
</thead>
</table>
<?php
}
?>
<?php
$query1 = "select * from tbl_news where news_status='Active'";
$result1 = mysql_query($query1);
$row1 = mysql_num_rows($result1);
$pagecount = $row1 / 5;
$pagecount = ceil($pagecount);
for ($count = 1; $count <= $pagecount; $count++) {
?>
<a href="news.php?page=<?php echo $count; ?>"><?php echo $count ?></a>
<?php # code...
}
}
?>
here is the full code, of what errror gives me, please help me guys it takes me a a lot of time having this kind of problem i already tried everything i could but maybe you guys could me solve my problem hahahaha it really drained my mind here , im already mindblown on what is the my currently facing problem
A: You are missing < at the a tag inside the first while loop (exactly on line 21 when I copy/paste your code). That might be the reason it doesn't recognize the else statement, because it can't get to it properly.
A: try this code. may be it resolve your problem.
I have corrected some syntax mistake in your code.
<?php
include("../mysql_connect.php");
if (isset($_POST['search_form'])) {
$page1=$_GET['page'];
if ($page1=="" || $page1==1) {
$page1=0;
}
else{
$page1=($page1*5)-5;
}
$query="select * from tbl_news where news_title like '$_POST[search]' || news_author like '$_POST[search]' ";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
?>
<table class="table table-hover" border="2">
<col width="50%"></col>
<col width="40%"></col>
<col width="20%"></col>
<tr>
<td rowspan="3">
<a href="news_view.php?id=<?php echo $row['news_id'];?>">
<img src="<?php echo $row['news_image_location'].$row['news_image'];?>" height="300" width="500">
</a>
</td>
<td>Title: <?php echo $row['news_title'];?></td>
</tr>
<tr>
<td>Author: <?php echo $row['news_author'];?></td>
</tr>
<tr>
<td>Date: <?php echo $row['news_date_filed'];?></td>
</tr>
</thead>
</table>
<?php
}
$query1="select * from tbl_news where news_title like '$_POST[search]' || news_author like '$_POST[search]'";
$result1=mysql_query($query1);
$row1=mysql_num_rows($result1);
$pagecount=$row1/5;
$pagecount=ceil($pagecount);
for ($count=1; $count <= $pagecount ; $count++) {
?>
<a href="news.php?page=<?php echo $count;?>"><?php echo $count?></a>
<?php
}
}else{
$page1=$_GET['page'];
if ($page1=="" || $page1==1) {
$page1=0;
}
else{
$page1=($page1*5)-5;
}
$query="select * from tbl_news where news_status='Active' limit $page1,5";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
?>
<table class="table table-hover" border="2">
<col width="50%"></col>
<col width="40%"></col>
<col width="20%"></col>
<tr>
<td rowspan="3">
<a href="news_view.php?id=<?php echo $row['news_id'];?>">
<img src="<?php echo $row['news_image_location'].$row['news_image'];?>" height="300" width="500">
</a>
</td>
<td>Title: <?php echo $row['news_title'];?></td>
</tr>
<tr>
<td>Author: <?php echo $row['news_author'];?></td>
</tr>
<tr>
<td>Date: <?php echo $row['news_date_filed'];?></td>
</tr>
</thead>
</table>
<?php
}
$query1="select * from tbl_news where news_status='Active'";
$result1=mysql_query($query1);
$row1=mysql_num_rows($result1);
$pagecount=$row1/5;
$pagecount=ceil($pagecount);
for ($count=1; $count <= $pagecount ; $count++) {
?>
<a href="news.php?page=<?php echo $count;?>"><?php echo $count?></a>
<?php # code...
}
}
?>
| |
doc_23530675
|
I have a Spring Boot Test.
The annotations are:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@TestPropertySource(locations { "myproperties.properties" })
I've got a test that I'd love to use @RunWith(Theories.class). The test is testing basically the same thing over several different places in my code.
Of course, @RunWith must be singular.
So is there a way to have the theories started up as a rule? Or SpringRunner.class? Or something so that they can co-exist?
A: There should be two ways to solve that:
*
*SpringClassRule and SpringMethodRule <-- I use this approach
just use
@RunWith(Theories.class)
public class YourTest {
@ClassRule
public static final SpringClassRule scr = new SpringClassRule();
@Rule
public final SpringMethodRule smr = new SpringMethodRule()
*Initializing the TestContextManager Manually according to Baeldung it works for Parameterized, but I wouldn't know why it shouldn't work for Theories also ;)
Generally, it is not recommended to initialize the TestContextManager manually. Instead, Spring recommends using SpringClassRule and SpringMethodRule.
@RunWith(Parameterized.class)
public class YourTest {
private TestContextManager testContextManager;
@Before
public void setup() throws Exception {
this.testContextManager = new TestContextManager(getClass());
this.testContextManager.prepareTestInstance(this);
}
| |
doc_23530676
|
Catchable fatal error: Object of class PDOStatement could not be converted to string on line 10
class User {
var $name = "";
var $email = "";
var $user_id;
function __construct($user_id) {
global $pdo;
$this->user_id = $user_id;
$user_info = $pdo->prepare("SELECT * FROM users WHERE user_id = :id");
$user_info->execute(array(":id" => $user_id));
$result = $user_info->fetch(PDO::FETCH_ASSOC);
$this->email = $result["email"];
$this->name = $result["name"];
}
public static function createUser($email,$password,$name) {
global $pdo;
$check = $pdo->prepare("SELECT user_id FROM users WHERE email = ?");
$check->execute(array($email));
$stmt = $check->fetch();
if(isset($stmt["user_id"])) {
return false;
}
$password_hash = hash('sha256', $password);
$user_id = $pdo->prepare("INSERT INTO users
(email, password, name)
VALUES (?,?,?)");
$user_id->execute(array(
$email, $password_hash, $name));
return new User($user_id);
}
}
Can anyone help me?
| |
doc_23530677
|
react-native-cli: 1.0.0
react-native: 0.30.0
npm: 3.10.3
node: v6.5.0
"react": "~15.2.1"
When running react-native run-ios I am getting:
** BUILD FAILED **
The following build commands failed:
CompileC /Users/*/f8app/ios/build/Build/Intermediates/Pods.build/Debug-iphonesimulator/React.build/Objects-normal/x86_64/RCTRootShadowView.o /Users/*/f8app/node_modules/react-native/React/Views/RCTRootShadowView.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)
/Users/*/f8app/node_modules/react-native/node_modules/promise/lib/done.js:10
throw err;
^
Error: xcodebuild process exited with code 65
at ChildProcess.<anonymous> (/Users/*/f8app/node_modules/react-native/local-cli/runIOS/runIOS.js:93:14)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
Michaels-MacBook-Pro-2:f8app *$
A: You can try this command npm dedupe. In my case, it works like a charm without error 65 any more. It happens after xcode 10.01
command line
cd "to path of your project"
npm dedupe
| |
doc_23530678
|
A: 7-zip comes with bzip2 support (and many many more formats) and a C# wrapper.
A: SharpZipLib is what you're looking for.
#ziplib (SharpZipLib, formerly NZipLib) is a Zip, GZip, Tar and BZip2 library written entirely in C# for the .NET platform.
| |
doc_23530679
|
A picture of what I'm trying to archive is here
Can this be done, I am a little lost ?
I have found some css code on the internet to make an accordeon menu that works nicely (as shown below), but I don't know how to change it to display the sublist inside the parent menu square.
This is probably easy stuff for someone with lots of experience and a stupid question, but I'm kinda stuck :-(. I think the "on hover" also needs to trigger the resizing of the parent item, but how ? Or am I overlooking a very simple solution ?
Thanks alot and sorry for my bad English.
n.
.menu {
margin: 0 auto;
padding: 0;
width: 150px;
}
.menu li {
list-style: none;
}
.menu li a {
display: table;
margin-top: 1px;
height: 90px;
padding: 14px 10px;
width: 90px;
background: #5DB26E;
text-decoration: none;
text-align: left;
vertical-align: middle;
color: #fff;
overflow: hidden;
-webkit-transition-property: background;
-webkit-transition-duration: 0.4s;
-webkit-transition-timing-function: ease-out;
transition-property: background;
transition-duration: 0.4s;
transition-timing-function: ease-out;
}
.menu > li:first-child a {
margin-top: 0;
}
.menu li a:hover {
background: #4AADBB;
-webkit-transition-property: background;
-webkit-transition-duration: 0.2s;
-webkit-transition-timing-function: ease-out;
transition-property: background;
transition-duration: 0.2s;
transition-timing-function: ease-out;
}
.menu li ul {
margin: 0;
padding: 0;
}
.menu li li a {
display: block;
margin-top: 0;
padding: 0 10px;
height: 0;
background: #C6DDD9;
color: #1F3D39;
-webkit-transition-property: all;
-webkit-transition-duration: 0.5s;
-webkit-transition-timing-function: ease-out;
transition-property: all;
transition-duration: 0.5s;
transition-timing-function: ease-out;
}
.menu > li:hover li a {
display: table;
margin-top: 1px;
padding: 10px;
width: 100%;
height: 1em;
-webkit-transition-property: all;
-webkit-transition-duration: 0.3s;
-webkit-transition-timing-function: ease-out;
transition-property: all;
transition-duration: 0.3s;
transition-timing-function: ease-out;
}
.menu > li:hover li a:hover {
background: #A4CAC8;
-webkit-transition-property: background;
-webkit-transition-duration: 0.2s;
-webkit-transition-timing-function: ease-out;
transition-property: background;
transition-duration: 0.2s;
transition-timing-function: ease-out;
}
A: How about something like this?
You'd probably want to replace the headers with anchor tags for wherever your nav links link to.
ul {
padding:0;
margin:0;
}
li {
box-sizing:border-box;
padding:0;
margin:0;
list-style:none;
}
ul.menu > li {
overflow:hidden;
width:47px;
max-height:47px;
padding:10px;
margin-bottom:10px;
background:blue;
color:white;
cursor:pointer;
transition:all 1s ease;
}
ul.menu > li:hover {
width:100px;
max-height:120px;
}
h2 {
margin:0 0 10px 0;
}
h3 {
margin:0;
}
<ul class="menu">
<li>
<h2>A</h2>
<ul>
<li>
<h3>A.a</h3>
<h3>A.b</h3>
<h3>A.c</h3>
</li>
</ul>
</li>
<li>
<h2>B</h2>
<ul>
<li>
<h3>B.a</h3>
<h3>B.b</h3>
<h3>B.c</h3>
</li>
</ul>
</li>
<li>
<h2>C</h2>
<ul>
<li>
<h3>C.a</h3>
<h3>C.b</h3>
<h3>C.c</h3>
</li>
</ul>
</li>
<li>
<h2>D</h2>
<ul>
<li>
<h3>D.a</h3>
<h3>D.b</h3>
<h3>D.c</h3>
</li>
</ul>
</li>
</ul>
A: my solution is as seen below (for everyone who is faced with the same problem)
#hideme{display:none;}
.menu ul {
padding:0;
margin:0;
color:white;
text-decoration:none;
}
.menu li {
box-sizing:border-box;
padding:0;
margin:0;
list-style:none;
color:white;
text-decoration: none;
text-align: bottom; vertical-align: bottom;
}
.menu > li ul li{
box-sizing:border-box;
margin-left:20px;
margin-top:5px;
list-style:none;
text-decoration: none;
text-align: bottom; vertical-align: bottom;
}
ul.menu > li {
overflow:hidden;
width:90px;
min-height:90px;
max-height:90px;
padding:10px;
margin-bottom:10px;
background:#5DB26E;
color:#5DB26E;
cursor:pointer;
transition:all 0s ease;
}
ul.menu > li:hover {
width:180px;
min-height:180px;
color: white;
border: 3px solid white;
box-shadow: 0px 0px 0px 3px #5DB26E;
position: relative;
}
ul.menu> li:hover #hideme{display:block; position: absolute;
bottom: 10;}
ul.menu> li:hover .fa-arrow-right{content: "\f023";}
.hoverme:hover .fa-arrow-right,
.hoverme .fa-check {
display: none;
}
.hoverme:hover .fa-check {
display: inline;
}
.menu a {
margin:0;
text-decoration:none;
color:white;
}
<ul class="menu">
<li> <a href="news.html"><b>news</b></a>
<ul> <span id ="hideme">
<li><a href="aaaaa.html" class="hoverme"><i class="fa fa-arrow-right"></i><i class="fa fa-check"></i> aaaaa</a></li>
<li><a href="bbbbb.html" class="hoverme"><i class="fa fa-arrow-right"></i><i class="fa fa-check"></i> bbbbb</a></li></span>
</ul>
</li>
</ul>
| |
doc_23530680
|
Now if I want to use axios, I can get the return data by calling the path directly
But I hope I can set up files to centrally manage apiUrl and apiName and import them
index.html
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/http-vue-loader"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="module" src="/api/server.js"></script>
</head>
<body>
<div id="app">
<p>
<router-link to="/contact">Go to contact</router-link>
</p>
<p>
<router-link to="/about">Go to about</router-link>
</p>
<p>
<router-view></router-view>
</p>
</div>
<head>
<script>
const contact = httpVueLoader('./view/contact.vue')
const about = httpVueLoader('./view/about.vue')
const routes = [
{ path: '/contact', component: contact },
{ path: '/about', component: about }
]
const router = new VueRouter({
routes
})
var app = new Vue({
router,
}).$mount('#app')
</script>
</head>
</body>
</html>
contact.vue
<template>
<p>{{ hello }}</p>
</template>
<script>
module.exports = {
data: function () {
return {
hello: "contact",
};
},
mounted() {
axios
.get('apiUrl/apiName')
.then(response => (console.log(response.data))
.catch(function (error) {
console.log(error);
});
},
};
</script>
<style>
</style>
Currently, data can be obtained through directly defined paths. I am not using Node.js. Is it possible to modularize apiUrl?
A: You could set axios's default baseURL so that all requests share the same URL prefixed to their paths:
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com/'
I would do this in index.html before loading any components that would make axios requests.
| |
doc_23530681
|
The data in organic column is something like this:
I can run my package successfully in Visual Studio, but after I deploy the package to SQL Server and run it with the same input parameters, I get this error:
The conversion returned status value 2 and status text. The value could not be converted because of potential loss of data
Why I can run the package in Visual Studio but not on SQL Server?
| |
doc_23530682
|
Event source functions locally on localhost but once deployed, I cannot detect the event triggers. However, the logs on the firebase functions logger show the function being carried out. However, when tested, the function does not provide any feedback to the event
const EventEmitter = require('events');
const Stream = new EventEmitter();
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
exports.eventEmitter = (req, res) => {
console.log(req.body);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive'
})
Stream.on('push', function(event, data) {
console.log('send0');
res.write('event: ' + String(event) + '\n' + 'data:' + JSON.stringify(data) + '\n\n');
});
setInterval(() => {
console.log('send1');
Stream.emit('push', 'message', { msg: 'it works! hurraaay' });
}, 5000);
}
When I test this code locally for event emission, using the following Angular code, The event is detected and logged on the console. However, once I deploy the function to firebase functions, I get a pending request on the network tab of the browser that doesn't have any log and seems to not complete at all and my angular code does inevitably detects nothing
getStream() {
return Observable.create(observer => {
let url = 'link to emitter';
let eventSource = new EventSource(url);
eventSource.addEventListener('message', function(e) {
console.log(e.data);
}, false);
eventSource.addEventListener('open', function(e) {
// Connection was opened.
console.log("open");
}, false);
eventSource.addEventListener('error', function(e) {
if (eventSource.readyState == EventSource.CLOSED) {
// Connection was closed.
console.log("closed");
}
}, false);
eventSource.addEventListener('message', message => { console.log(message.data); });
eventSource.onmessage = (event) => {
let json = JSON.parse(event.data);
if (json !== undefined && json !== '') {
this.zone.run(() => observer.next(json));
}
};
eventSource.onerror = (error) => {
if (eventSource.readyState === 0) {
console.log('The stream has been closed by the server.');
eventSource.close();
observer.complete();
} else {
observer.error('EventSource error: ' + error);
}
}
});
}
A: Cloud Functions HTTP endpoints do not support streaming data to clients like a websocket. It can only receive an entire payload up front, then send an entire payload back to the client. There are no chunked responses. The limit for the payload is 10MB. The default timeout for a function invocation is 60s and can only be increased to 9m max. If you need streaming, then Cloud Functions is not the right product for your use case.
| |
doc_23530683
|
Through my Windows Forms Application I am sending the path which needs to be monitored by the FileSystemWatcher Service. My question is, without stopping the service and then sending another path that I want to monitor, is it possible to send the new path and and to start monitoring that file?
Here's quick insight of how my program works:
*
*Send path to FileSystemWatcher Service;
*Start service;
//Let's say I now want to monitor another folder
*Stop service;
*Give new path;
*Start service;
A: There's a few solutions to inter-process communication but a great option is named pipes.
There's a really nice step by step example which uses a Windows Service to send data to a system tray icon. In this example, the Window Service is also the named pipe server.
In your case, your windows service will be a client, listening to data from your Windows Forms application.
| |
doc_23530684
|
*
*I removed XFrame package from the middleware in settings.py.
*I putted X_FRAME_OPTIONS='SAMEORIGIN' to settings.py
*I added 'X-Frame-Options' to response object with the same value in my view in which I wanted to use the <iframe>
*I tried to add @xframe_options_sameorigin decorator to my view.
*I also changed /etc/apache2/apache2.conf, putted Header always set X-Frame-Options "SAMEORIGIN" into it.
Then I tried to restart apache2 service after all my actions but the result always the same:
X-Frame-Options setted as 'DENY'
My Django version is 2.2.4.
A: Sorry, some of this methods have worked. Update of browser page has not worked at first time, but after few minutes, it has worked. All done, thank you.
| |
doc_23530685
|
df = pd.DataFrame()
df['Obs']=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
df['Marker']=[0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]
df['Mean']=(df.Obs.rolling(5).mean())
How can I create a Desired column like this:
df['Desired']=[0,0,0,0,3.0,0,0,0,0,8.0,0,0,0,0,13.0]
print(df)
Obs Marker Mean Desired
0 1 0 NaN 0.0
1 2 0 NaN 0.0
2 3 0 NaN 0.0
3 4 0 NaN 0.0
4 5 1 3.0 3.0
5 6 0 4.0 0.0
6 7 0 5.0 0.0
7 8 0 6.0 0.0
8 9 0 7.0 0.0
9 10 1 8.0 8.0
10 11 0 9.0 0.0
11 12 0 10.0 0.0
12 13 0 11.0 0.0
13 14 0 12.0 0.0
14 15 1 13.0 13.0
A: You are close, just need a where:
df['Mean']= df.Obs.rolling(5).mean().where(df['Marker']==1, 0)
Output:
Obs Marker Mean
0 1 0 0.0
1 2 0 0.0
2 3 0 0.0
3 4 0 0.0
4 5 1 3.0
5 6 0 0.0
6 7 0 0.0
7 8 0 0.0
8 9 0 0.0
9 10 1 8.0
10 11 0 0.0
11 12 0 0.0
12 13 0 0.0
13 14 0 0.0
14 15 1 13.0
| |
doc_23530686
|
Let's say I have the dictionary
d1= {570.44: 2, 305.21: 1, 271.94: 0, 463.20: 3, 556.60: 4, 596.27: 5}
I want to get an ordered list of the keys but ordered according to the values not the keys
In this case I would like to get
[271.94, 305.21, 570.44, 463.20, 556.60, 596.27]
(since you can see that their values are: 0,1,2,3,4,5
A: Try this:
d1= {570.44: 2, 305.21: 1, 271.94: 0, 463.20: 3, 556.60: 4, 596.27: 5}
sorted(d1, key=d1.get)
Output:
[271.94, 305.21, 570.44, 463.2, 556.6, 596.27]
| |
doc_23530687
|
<form id='login' action='login.php' method='POST' accept-charset='UTF-8'>
<input type='text' name="username" id='username' />
<input type='password' name='password' id='password' />
<input type="text" name="store" />
<input type='submit' name='Submit' value='Submit' />
</form>
The form works perfectly on Firefox and Chrome. All variables appear in the $_POST variable with no issues.
On IE9, however, the form is submitted properly, but $_POST is the empty array. I.e., in login.php:
print_r($_POST);
prints the empty array. I'm trying to figure out what could be different about IE9 that's making it behave differently from Firefox and Chrome and I can't figure it out.
I found mention of some module under Apache that's causing people problems, but I'm running IIS7, not Apache, so that's not it. Someone on a Ruby forum mentioned setting a DisableNTLMPreAuth to 1 in the registry, but that hasn't fixed it either.
Any help is appreciated.
A: accept-charset is not support in Internet Explorer. Remove it and see if that solves you're problem.
A: I think this is to do with a double hit - i.e. that IE is re-reloading the page somehow. Have you got some client side stuff (jQuery?) that re-reloads the page by accident as a bug? Try posting to a completely new page and writing <?PHP die ('<pre>'.print_r($_REQUEST,true).'</pre>');?> on the top line and seeing what happens.
A: plz enter "name" attribute for form.
<form id='login' name='login' action='login.php' method='POST' accept-charset='UTF-8'>
<input type='text' name="username" id='username' />
<input type='password' name='password' id='password' />
<input type="text" name="store" />
<input type='submit' name='Submit' value='Submit' />
</form>
A: The reason is you are not maintaining the session. In Firefox and Chrome are much smart and they maintain the session irrespective of the Development of the Code, which gives users a good things. But in IE6-9, IE Can't maintain session, developer has to check it and if the session is not maintained every page loaded is a new session and thus there is no post.
| |
doc_23530688
|
top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'
Then I call this command from the java code, but I do not get any output. Normal linux commands such as ls works for me.
My code is:
public class HelloWorld{
public static void main(String []args){
String s;
Process p;
try {
p = Runtime.getRuntime().exec("top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
}
A: To use pipes, you need run your command from within a shell:
ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c",
"top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'");
p = b.start();
Also, please be aware that your command fails on a different locale. And the output of top may vary too.
| |
doc_23530689
|
I need the Microsoft graph api name and also the code to read my own emails using node js oauth 2.0
| |
doc_23530690
|
I have seen some really S. L. O. W. SAS code where my coworkers running a series of proc sql commands. These programs typically include 3 - 5 proc sql steps. Each proc sql command creates a local SAS table. They are not using passthrough sql. The data sets are large (1 million rows +) and these proc sql steps run slowly. Most of the data lives on the server. There is usually a small table that defines the population that we want to look at and it is in a SAS data file, but everything else lives on the server.
I have demonstrated dramatic improvements in speed by simply running all of the queries directly on the server. (Oracle in this case, but I don't think that is important.) Usually, I have to first upload a table to my personal schema that defines the population of clients we want to examine. Everything else is on the server. Sometimes I collapse their queries together because they can be done in a single step, but I do not believe that is why my version of their program is so much faster.
I think proc sql uploads the initial data set and then runs the first query on the server. It then downloads the output to the local computer, creating the local SAS data set. For the second proc sql step, it uploads the table created in step one back to the server and then runs the query on the server. To make this all even worse, the "local" SAS data sets are actually stored on a remote server, not the actual local machine. This is invisible to SAS, but it does mean we are copying data across the network yet again. I believe SAS is running slowly because of a large amount of unnecessary network traffic.
Question #1 - Is my understanding of what proc sql is doing correct? Are we really wasting as much time as I think we are uploading and downloading large tables / data sets across our network?
Qeustion #2 - Is there some way to control when proc sql runs against a server versus when it runs against the local database? In some cases, if we could prevent the upload / download step, the query would run more efficiently.
A: Short answer
Your understanding is not exactly correct, but it's in the right ballpark. SQL is probably not sending the SAS dataset to the server, it is more likely downloading the server data to SAS - but it's probably downloading the entire table, not limited by the join criteria. Your solution is exactly what I would suggest doing - hopefully your colleagues will get on board.
Long answer
In terms of how the processing works, it depends on your code. PROC SQL will execute code locally (as in, on the SAS server/desktop), unless it decides to pass the query up to the server and hasn't been told it's not allowed to. That's called implicit passthrough. You can't really control it except to turn it entirely off (with noipassthru on the PROC SQL statement). You can look at it sometimes using options msglevel=i; (a system option), and _METHOD or _TREE to see what SQL decided to do (similar to explain plan).
I've had cases where it caused harm: SQL Server runs character comparisons case-insensitively while SAS does not, and I had a particular query that sometimes was sent up to the server and sometimes not depending on details of the data. I wasn't careful enough with checking case, and so it appeared to work when it really wasn't correct (comparing Propcase to UPCASE).
The general rule is that SAS will try to send the query to the server if:
*
*The data in the query entirely already resides on the server
*The query is sufficiently simple that SAS can easily figure out how to tell the server to do it, in its native language
If you're running a query with local SAS dataset (say, joining a server table to a SAS dataset locally), it won't (at least as far as I know) go to the server. It should always run it locally, which would mean downloading from the server all data in the contributing tables (possibly filtered if there is a logical filter in the query). IE (these examples aren't necessarily good SQL code, just examples of concept):
libname oralib oracle [connection info];
proc sql;
*Will pass through likely;
select tableA.*, tableB.cost
from oralib.tableA inner join oralib.tableB
on tableA.id=tableB.id;
*Will probably not pass through;
select tableA.*, tableB.cost
from oralib.tableA inner join work.tableB
on tableA.id=tableB.id;
*Might pass through, might not;
select tableA.*, tableB.cost, tableC.productID
from oralib.tableA inner join oralib.tableB
on tableA.id=tableB.id
left join oralib.tableC
on tableA.id=tableC.id;
*This downloads the data but probably applies the where statement server side;
select tableA.*, tableB.cost
from oralib.tableA inner join work.tableB
on tableA.id=tableB.id
where tableA.date < '01JAN2010'd;
quit;
In the case of the second query, it probably pulls all of tableA down. In the fourth query, it likely will pass the where clause to the server (assuming the date doesn't cause a problem, but it shouldn't, SAS knows how to convert dates to oracle type dates).
Note that SAS procs can also generate passthrough. PROC MEANS, etc., will send the instructions to Oracle to do the means/sums/etc. if it can easily do so.
Your best bet is to:
*
*Try to do everything in pass through that you can (and that makes sense). Only way to be sure it goes to the server is to use passthrough.
*If you have a large table on the server and a small table in SAS, upload the table in SAS to the server. A passthrough session and a libname session can't see each others session-specific temporary tables, so you'd have to use a GTT or similar (something all users can see). Similarly, if you have a large table in SAS and a small table (or small query result) in SQL, bring it down locally (through passthrough if necessary).
*When you do have to bring things down, limit as much as possible. When I worked in that kind of environment, I made huge time savings simply by joining to tables on the server to limit my result set before bringing them down.
At the end of the day, you will be constrained by network traffic no matter what you do; just try to optimize it as best you can. It sounds like you understand how to do that already, so just do what you normally would do in non-SAS environments.
| |
doc_23530691
|
A: A google search with the terms big integer library gave me the C++ Big Integer Library . From the website:
This library emphasizes ease of use and clarity of implementation over
speed; some users will prefer GMP, which is faster.
Edit:
To create a random number with 125 bits there are plenty of options.
A simple and quick solution (but obviously not available in the library I posted above - I don't whether it's possible with GMP) would be to do a rand() * 0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF in the correct notation.
A method in the scope of the above library, which unfortunately is rather slow, would be to draw 125 single bits ("0" or "1" at random) and add increasing powers of 2 if you drew a "1". Here is some (untested) code:
BigInteger summand, number125bit;
summand = 1;
srand(systemtime_or_any_other_number);
for (int i=0; i<125; i++)
{
if (rand() && 1)
{
number125bit += summand;
}
summand = summand << 1;
}
| |
doc_23530692
|
URLS.py File of the Project:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('tabs_app.urls')),
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls'))
]
VIEWS.py file of the app in the project where index.html file is located:
from django.shortcuts import render
# Create your views here.
def login(request):
return render(request, 'login.html')
URLS.py file of the app in the project where index.html file is located:
from django.urls import path
from . import views
urlpatterns = [
path('', views.login, name='login')
]
VIEWS.py file of the app in which LOGIN code is written:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User, auth
# Create your views here.
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'login.html')
URLS.py file of the app where LOGIN code is written:
from django.urls import path
from . import views
urlpatterns = [
path('login', views.login, name='login')
]
ERROR MESSAGE which is coming on the local server:
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/login
Using the URLconf defined in tabs_pilot.urls, Django tried these URL patterns, in this order:
1. [name='login']
2. admin/
3. accounts/
^media/(?P<path>.*)$
The current path, login, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
A: Are you trying to use Django's build in login functionality? In this case your endpoint is http://127.0.0.1:8000/accounts/login and your template should be found within the registration directory in your templates directory.
Mozilla does a pretty good job of outlining how this all works in their Django Tutorial. Check it out here.
| |
doc_23530693
|
I am using the cleditor jQuery plugin for its Rich Text/HTML editing capabilities. For the most part, it works fine. However, there's a weird problem if I do the following in IE9:
*
*Click the "Show Source" button at the top right of the toolbar to switch to HTML Mode
*Paste the following snippet:
<p>Note the double-quotes</p>
<div onclick='alert("hi")'>click me</div>
*Switch back to Rich Text Mode and make a trivial change (for e.g., add a space)
*Switch again to HTML Mode
Note how the double-quotes are now incorrectly escaped like this:
<div onclick="alert(\"hi\")">click me</div>
What the heck is going on here? Other browsers escape the double-quotes properly like this:
<div onclick="alert("hi")">click me</div>
I've tried to using the entity, ", myself but it doesn't matter - IE9 still messes it up. Does anyone know how to overcome this issue?
A: Nevermind, I figured it out. If anyone else is struggling with this issue, I think it's the combination of using cleditor, the XHTML plugin and Internet Explorer.
You can fix it by adding this JavaScript Snippet before your cleditor code:
(function ($) {
var oldCallback = $.cleditor.defaultOptions.updateTextArea;
$.cleditor.defaultOptions.updateTextArea = function (html) {
if (oldCallback) {
html = oldCallback(html);
}
var isIE = /*@cc_on!@*/false;
if (isIE) {
return html.replace(/\\\"/g, """);
} else {
return html;
}
};
})(jQuery);
Alternatively, you can do the conditional replacement in jquery.cleditor.js (line 1126 for cleditor v1.3.0).
| |
doc_23530694
|
I have tried this following method to split up the column data but the select substring method is not able to split the column properly.
SELECT SUBSTRING_INDEX(btrim,'|',2) AS devicename,
SUBSTRING_INDEX(btrim,'|',1) AS brand
FROM fts_inventory
the following is the data from my table
btrim
----------------------------
Samsung|Galaxy-J1|Sam-GalJ1
Samsung|Galaxy-J1|Sam-GalJ1
Samsung|Galaxy-J1|Sam-GalJ1
Samsung|Galaxy-J1|Sam-GalJ1
Samsung|Galaxy-J1|Sam-GalJ1
Samsung|Galaxy-J1|Sam-GalJ1
BBC|Brought-by-client|BROUGHT001
Motorola|G4|Moto-G4L|on CDMA / LTE
LTE-Sim|LTE-Sim|LTE-Sim pack
LTE-Sim|LTE-Sim|LTE-Sim pack
I want results like this in 2 separate columns:
devicename brand
-------------------------------------
Galaxy-J1 Samsung
Galaxy-J1 Samsung
Galaxy-J1 Samsung
Galaxy-J1 Samsung
Galaxy-J1 Samsung
Galaxy-J1 Samsung
Brought-by-client BBC
G4 Motorola
LTE-Sim LTE-Sim
LTE-Sim LTE-Sim
but getting this :
devicename brand
---------------------------------------------
Samsung|Galaxy-J1 Samsung
Samsung|Galaxy-J1 Samsung
Samsung|Galaxy-J1 Samsung
Samsung|Galaxy-J1 Samsung
Samsung|Galaxy-J1 Samsung
Samsung|Galaxy-J1 Samsung
BBC|Brought-by-client BBC
A: Try below
Standard Query
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(btrim, '|', 1), '|', -1) as first,
SUBSTRING_INDEX(SUBSTRING_INDEX(btrim, '|', 2), '|', -1) as second
.....
SUBSTRING_INDEX(SUBSTRING_INDEX(btrim, '|', n), '|', -1) as nth
FROM fts_inventory;
Exact Query
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(btrim, '|', 2), '|', -1) as devicename,
SUBSTRING_INDEX(SUBSTRING_INDEX(btrim, '|', 1), '|', -1) as brand
FROM fts_inventory;
A: In the syntax is SUBSTRING_INDEX(str, delim, count), using -2 in the count will return your expected result.
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(btrim, '|', -2), '|', 1) AS devicename,
SUBSTRING_INDEX(btrim,'|', 1) AS brand
FROM fts_inventory
A: An option:
SELECT
SUBSTRING_INDEX(`der`.`btrim`, '|', -1) `devicename`,
SUBSTRING_INDEX(`der`.`btrim`, '|', 1) `brand`
FROM (
SELECT SUBSTRING_INDEX(`btrim`, '|', 2) `btrim`
FROM `fts_inventory`
) `der`;
See dbfiddle.
| |
doc_23530695
|
public function index($id_cliente)
{
if (!isset($this->session->id_usuario)) {
return redirect()->to(base_url());
}
$mascotas = $this->mascota->getList($id_cliente);
$clientes = $this->mascota->getListaC($id_cliente);
$data = [
'titulo' => 'Mascotas', 'datos' => $mascotas, 'cliente' => $clientes,
'idcliente' => $id_cliente,
];
$this->clienta = $id_cliente;
echo view('header');
echo view('nav');
echo view('mascotas/mascotas', $data);
echo view('footer');
}
public function info()
{
$r = $this->clienta;
var_dump($r);
exit;
}
A: As I understand you want to pass $id_cliente value to info() because you are assigning $this->clienta = $id_cliente; here.
You will have to call the info($id_cliente) function inside your index($id_cliente) function and pass the value as a parameter.
A: send it to view then get it as get variable
public function index($id_cliente)
{
if (!isset($this->session->id_usuario)) {
return redirect()->to(base_url());
}
$mascotas = $this->mascota->getList($id_cliente);
$clientes = $this->mascota->getListaC($id_cliente);
$data = [
'titulo' => 'Mascotas', 'datos' => $mascotas, 'cliente' => $clientes,
'idcliente' => $id_cliente,
];
$data['clienta'] = $id_cliente;
echo view('header');
echo view('nav');
echo view('mascotas/mascotas', $data);
echo view('footer');
}
public function info()
{
echo $this->request->get('id');
exit;
}
this is the only way
| |
doc_23530696
|
The reason I need my PWA to access Chrome device APIs is to get a unique identifier per device to decide which content to display.
A: As per chromeos.dev: "Previously, Chrome Apps had extra functionality available to them in kiosk mode that is not currently supported by web apps alone. You can continue to use some of this functionality by deploying an extension with your kiosk web application."
Source: https://chromeos.dev/en/education/connecting-an-extension-from-a-kiosk-pwa
It only talks about sending a message from PWA to extension in order to execute a chrome API (like restart) but doesn't talk about how to send information back from extension to PWA. We are also stuck in the same boat- looking for a unique identifier so as to throw content on the chromebox running the PWA. Currently we use chrome.enterprise.deviceAttributes to get serial number and directory device ID in kiosk mode and would need the same once we migrate to PWA. Any luck on this?
| |
doc_23530697
|
A: From the same oracle FAQ,
To list the active instances from PL/SQL, use
DBMS_UTILITY.ACTIVE_INSTANCES().
and yes are "subject to change without notification": someone can draw out the power cable of one machine "without notification"
| |
doc_23530698
|
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LettersDropControl.ascx.cs" Inherits="MSAJAX1.LettersDropControl" %>
public partial class LettersDropControl : System.Web.UI.UserControl
{
private string selectedLetter;
public string SelectedLetter
{
get { return selectedLetter; }
set { selectedLetter = value; }
}
// Delegate
public delegate void OnButtonClick(string strValue);
// Event
public event OnButtonClick btnHandler;
protected void ddlLetters_SelectedIndexChanged(object sender, EventArgs e)
{
throw new Exception("TEST");
SelectedLetter = ddlLetters.SelectedItem.Value;
// Raise event if there is a subscription
if (btnHandler != null)
{
btnHandler(string.Empty);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ddlLetters.Items.Add("A");
ddlLetters.Items.Add("B");
}
}
}
The aspx page is
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MSAJAX1.Default" %>
<%@ Register TagPrefix="CP" TagName="LetterCtrl" Src="LettersDropControl.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<CP:LetterCtrl id="LetterCtrl1" runat="server" />
</div>
</form>
</body>
</html>
A: Check in case you have added the AutoPostBack property for the concerned dropdown. something like this
<asp:DropDownList 1" runat="server" AutoPostBack="True">
| |
doc_23530699
|
Thanks!
A: You added C:\FFmpeg\bin\ffmpeg.exe to your path, instead, you need to add only the directory:
C:\FFmpeg\bin\
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.