How can I enable Assembly binding logging?
A good place to start your investigation into any failed binding is to use the "fuslogvw.exe" utility. This may give you the information you need related to the binding failure so that you don't have to go messing around with any registry values to turn binding logging on.
Fuslogvw MSDN page
The utility should be in your Microsoft SDKs folder, which would be something like this, depending on your operating system:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v{SDK version}A\Bin\FUSLOGVW.exe"
Run this utility as Administrator, from Developer Command Prompt (as Admin) type FUSLOGVW
a new screen appears
Go to Settings to and select Enable all binds to disk also select Enable custom log path and select the path of the folder of your choice to store the binding log.
Restart IIS.
From the FUSLOGVW window click Delete all to clear the list of any previous bind failures
Reproduce the binding failure in your application
In the utility, click Refresh. You should then see the bind failure logged in the list.
You can view information about the bind failure by selecting it in the list and clicking View Log
The first thing I look for is the path in which the application is looking for the assembly. You should also make sure the version number of the assembly in question is what you expect.
How does the compilation/linking process work?
On the standard front:
a translation unit is the combination of a source files, included headers and source files less any source lines skipped by conditional inclusion preprocessor directive.
the standard defines 9 phases in the translation. The first four correspond to preprocessing, the next three are the compilation, the next one is the instantiation of templates (producing instantiation units) and the last one is the linking.
In practice the eighth phase (the instantiation of templates) is often done during the compilation process but some compilers delay it to the linking phase and some spread it in the two.
Convert hex color value ( #ffffff ) to integer value
I have the same problem that I found some color in form of #AAAAAA
and I want to conver that into a form that android could make use of.
I found that you can just use 0xFFAAAAAA
so that android could automatically tell the color. Notice the first FF
is telling alpha
value.
Hope it helps
post ajax data to PHP and return data
$.ajax({
type: "POST",
data: {data:the_id},
url: "http://localhost/test/index.php/data/count_votes",
success: function(data){
//data will contain the vote count echoed by the controller i.e.
"yourVoteCount"
//then append the result where ever you want like
$("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller
}
});
in the controller
$data = $_POST['data']; //$data will contain the_id
//do some processing
echo "yourVoteCount";
Clarification
i think you are confusing
{data:the_id}
with
success:function(data){
both the data
are different for your own clarity sake you can modify it as
success:function(vote_count){
$(span#someId).html(vote_count);
Starting iPhone app development in Linux?
You're right non-jailbroken phones are limited to Apple's App store and Apple "has the right" to enforce whatever rule, it's totally nonfree territory.
However while developing, one won't have to deal with Apple at all. You can use e.g. rsync to upload the code to the device and test it.
Declaring and using MySQL varchar variables
Looks like you forgot the @ in variable declaration. Also I remember having problems with SET
in MySql a long time ago.
Try
DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);
update mypermits
set person = @FOO
where person = @oldFOO;
Usage of unicode() and encode() functions in Python
You are using encode("utf-8")
incorrectly. Python byte strings (str
type) have an encoding, Unicode does not. You can convert a Unicode string to a Python byte string using uni.encode(encoding)
, and you can convert a byte string to a Unicode string using s.decode(encoding)
(or equivalently, unicode(s, encoding)
).
If fullFilePath
and path
are currently a str
type, you should figure out how they are encoded. For example, if the current encoding is utf-8, you would use:
path = path.decode('utf-8')
fullFilePath = fullFilePath.decode('utf-8')
If this doesn't fix it, the actual issue may be that you are not using a Unicode string in your execute()
call, try changing it to the following:
cur.execute(u"update docs set path = :fullFilePath where path = :path", locals())
What is the difference between a framework and a library?
I like Cohens answer, but a more technical definition is: Your code calls a library. A framework calls your code. For example a GUI framework calls your code through event-handlers. A web framework calls your code through some request-response model.
This is also called inversion of control - suddenly the framework decides when and how to execute you code rather than the other way around as with libraries. This means that a framework also have a much larger impact on how you have to structure your code.
Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?
With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified. This makes it seem as if the array is passed by value when in actual fact it isn't.
For example, in this first case, even though you aren't defining your function to accept $my_array by reference (by using the & character in the parameter definition), it still gets passed by reference (ie: you don't waste memory with an unnecessary copy).
function handle_array($my_array) {
// ... read from but do not modify $my_array
print_r($my_array);
// ... $my_array effectively passed by reference since no copy is made
}
However if you modify the array, a copy of it is made first (which uses more memory but leaves your original array unaffected).
function handle_array($my_array) {
// ... modify $my_array
$my_array[] = "New value";
// ... $my_array effectively passed by value since requires local copy
}
FYI - this is known as "lazy copy" or "copy-on-write".
How to consume a SOAP web service in Java
I will use CXF also you can think of AXIS 2 .
The best way to do it may be using JAX RS Refer this example
Example:
wsimport -p stockquote http://stockquote.xyz/quote?wsdl
This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.
I
SQL Server Regular expressions in T-SQL
How about the PATINDEX function?
The pattern matching in TSQL is not a complete regex library, but it gives you the basics.
(From Books Online)
Wildcard Meaning
% Any string of zero or more characters.
_ Any single character.
[ ] Any single character within the specified range
(for example, [a-f]) or set (for example, [abcdef]).
[^] Any single character not within the specified range
(for example, [^a - f]) or set (for example, [^abcdef]).
HTML favicon won't show on google chrome
These are the locations where browsers store the Temporary data in Linux:
Note: you can see hidden files in File Manager using Ctrl + H
for Terminal use the command ls -la
Chromium
~/.cache/chromium/[profile]/Cache/
Google Chrome
~/.cache/google-chrome/[profile]/Cache/
Also, Chromium and Google Chrome store some additional cache at
~/.config/chromium/[profile]/Application Cache/Cache/
and
~/.config/google-chrome/[profile]/Application Cache/Cache/
and generally here:
/tmp/
so to apply new FAVICON or try to show it up is to clean them
make sure u are inside each of these directories use the command:
rm -rf *
Where is the default log location for SharePoint/MOSS?
For SharePoint 2016
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs
For SharePoint 2013
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs
For SharePoint 2010
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\14\Logs
For SharePoint 2007
%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\12\Logs
Note: The sharePoint Trace log path can be changed by opening Central
Administration > Monitoring > Reporting > Configure Diagnostic Logs
For more details check SHAREPOINT ULS VIEWER
How to save all files from source code of a web site?
In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as
save page as
filename : any_name.html
save as type : webpage complete.
Then you will get any_name.html
and any_name folder
.
Select method of Range class failed via VBA
The correct answer to this particular questions is "don't select". Sometimes you have to select or activate, but 99% of the time you don't. If your code looks like
Select something
Do something to the selection
Select something else
Do something to the selection
You probably need to refactor and consider not selecting.
The error, Method 'Range' of object '_Worksheet' failed, error 1004, that you're getting is because the sheet with the button on it doesn't have a range named "Result". Most (maybe all) properties that return an object have a default Parent object. In this case, you're using the Range property to return a Range object. Because you don't qualify the Range property, Excel uses the default.
The default Parent object can be different based on the circumstances. If your code were in a standard module, then the ActiveSheet would be the default Parent and Excel would try to resolve ActiveSheet.Range("Result"). Your code is in a sheet's class module (the sheet with the button on it). When the unqualified reference is used there, the default Parent is the sheet that's attached to that module. In this case they're the same because the sheet has to be active to click the button, but that isn't always the case.
When Excel gives the error that includes text like '_Object' (yours said '_Worksheet') it's always referring to the default Parent object - the underscore gives that away. Generally the way to fix that is to qualify the reference by being explicit about the parent. But in the case of selecting and activating when you don't need to, it's better to just refactor the code.
Here's one way to write your code without any selecting or activating.
Private Sub cmdRecord_Click()
Dim shSource As Worksheet
Dim shDest As Worksheet
Dim rNext As Range
'Me refers to the sheet whose class module you're in
'Me.Parent refers to the workbook
Set shSource = Me.Parent.Worksheets("BxWsn Simulation")
Set shDest = Me.Parent.Worksheets("Reslt Record")
Set rNext = shDest.Cells(shDest.Rows.Count, 1).End(xlUp).Offset(1, 0)
shSource.Range("Result").Copy
rNext.PasteSpecial xlPasteFormulasAndNumberFormats
Application.CutCopyMode = False
End Sub
When I'm in a class module, like the sheet's class module that you're working in, I always try to do things in terms of that class. So I use Me.Parent instead of ActiveWorkbook. It makes the code more portable and prevents unexpected problems when things change.
I'm sure the code you have now runs in milliseconds, so you may not care, but avoiding selecting will definitely speed up your code and you don't have to set ScreenUpdating. That may become important as your code grows or in a different situation.
Best way to deploy Visual Studio application that can run without installing
It is possible and is deceptively easy:
- "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
- But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the
bin\Debug
folder below the project file (.csproj).
- Zip that folder (leave out any *.vhost.* files and the
app.publish
folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.
An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.
It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.
How to launch an Activity from another Application in Android
It is possible to start an app's activity by using Intent.setClassName
according to the docs.
An example:
val activityName = "com.google.android.apps.muzei.MuzeiActivity" // target activity name
val packageName = "net.nurik.roman.muzei" // target package's name
val intent = Intent().setClassName(packageName, activityName)
startActivity(intent)
To open it outside the current app, add this flag before starting the intent.
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
A related answer here
Remove Server Response Header IIS7
Add this to your global.asax.cs:
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("Server");
Response.Headers.Remove("X-AspNet-Version");
Response.Headers.Remove("X-AspNetMvc-Version");
}
Understanding Linux /proc/id/maps
memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more
get DATEDIFF excluding weekends using sql server
I found when i used this there was a problem when d1 fell on saturday. Below is what i used to correct this.
declare @d1 datetime, @d2 datetime
select @d1 = '11/19/2011' , @d2 = '11/28/2011'
select datediff(dd, @d1, @d2) +case when datepart(dw, @d1) = 7 then 1 else 0 end - (datediff(wk, @d1, @d2) * 2) -
case when datepart(dw, @d1) = 1 then 1 else 0 end +
case when datepart(dw, @d2) = 1 then 1 else 0 end
How to change lowercase chars to uppercase using the 'keyup' event?
The only issue with changing user input on the fly like this is how disconcerting it can look to the end user (they'll briefly see the lowercase chars jump to uppercase).
What you may want to consider instead is applying the following CSS style to the input field:
text-transform: uppercase;
That way, any text entered always appears in uppercase. The only drawback is that this is a purely visual change - the value of the input control (when viewed in the code behind) will retain the case as it was originally entered.
Simple to get around this though, force the input val() .toUpperCase(); then you've got the best of both worlds.
Explanation of <script type = "text/template"> ... </script>
Those script tags are a common way to implement templating functionality (like in PHP) but on the client side.
By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.
Backbone doesn't force you to use any particular templating library - there are quite a few out there: Mustache, Haml, Eco,Google Closure template, and so on (the one used in the example you linked to is underscore.js). These will use their own syntax for you to write within those script tags.
Is there a stopwatch in Java?
Use Guava's Stopwatch
class.
An object that measures elapsed time in nanoseconds. It is useful to
measure elapsed time using this class instead of direct calls to
System.nanoTime()
for a few reasons:
- An alternate time source can be substituted, for testing or performance reasons.
- As documented by nanoTime, the value returned has no absolute meaning, and can only be interpreted as relative to another timestamp
returned by nanoTime at a different time. Stopwatch is a more
effective abstraction because it exposes only these relative values,
not the absolute ones.
Stopwatch stopwatch = Stopwatch.createStarted();
doSomething();
stopwatch.stop(); // optional
long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
Text File Parsing with Python
There are a few ways to go about this. One option would be to use inputfile.read()
instead of inputfile.readlines()
- you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.
A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text)
. This is a little inefficient, but if speed isn't a major concern, the code will be simplest.
Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:
def data_parser(lines, dic):
for i, j in dic.iteritems():
for (k, line) in enumerate(lines):
lines[k] = line.replace(i, j)
return lines
Local storage in Angular 2
Here is an example of a simple service, that uses localStorage to persist data:
import { Injectable } from '@angular/core';
@Injectable()
export class PersistanceService {
constructor() {}
set(key: string, data: any): void {
try {
localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
console.error('Error saving to localStorage', e);
}
}
get(key: string) {
try {
return JSON.parse(localStorage.getItem(key));
} catch (e) {
console.error('Error getting data from localStorage', e);
return null;
}
}
}
To use this services, provide it in some module in your app like normal, for example in core module. Then use like this:
import { Injectable } from '@angular/core';
@Injectable()
export class SomeOtherService {
constructor(private persister: PersistanceService) {}
someMethod() {
const myData = {foo: 'bar'};
persister.set('SOME_KEY', myData);
}
someOtherMethod() {
const myData = persister.get('SOME_KEY');
}
}
What does "fatal: bad revision" mean?
I had a similar issue with Intellij. The issue was that someone added the file that I am trying to compare in Intellij to .gitignore, without actually deleting the file from Git.
Generating CSV file for Excel, how to have a newline inside a value
Test this:
It fully works for me:
Put the following lines in a xxxx.csv
file
hola_x,="este es mi text1"&CHAR(10)&"I sigo escribiendo",hola_a
hola_y,="este es mi text2"&CHAR(10)&"I sigo escribiendo",hola_b
hola_z,="este es mi text3"&CHAR(10)&"I sigo escribiendo",hola_c
Open with excel.
in some cases will open directly otherwise will need to use column to data conversion.
expand the column width and hit the wrap text button. or format cells and activate wrap text.
and thanks for the other suggestions, but they did not work for me. I am in a pure windows env, and did not want to play with unicode or other funny thing.
This way you putting a formula from csv to excel. It may be many uses for this method of work.
(note the = before the quotes)
pd:In your suggestions please put some samples of the data not only the code.
Is it necessary to use # for creating temp tables in SQL server?
Yes. You need to prefix the table name with "#" (hash) to create temporary tables.
If you do NOT need the table later, go ahead & create it.
Temporary Tables are very much like normal tables. However, it gets created in tempdb.
Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.
"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.
Refer the below link for the Basics of Temporary Tables:
http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005
If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.
They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.
DECLARE @ItemBack1 TABLE
(
column1 int,
column2 int,
someInt int,
someVarChar nvarchar(50)
);
INSERT INTO @ItemBack1
SELECT column1,
column2,
someInt,
someVarChar
FROM table2
WHERE table2.ID = 7;
More Info on Table Variables:
http://odetocode.com/articles/365.aspx
How to find length of a string array?
As all the above answers have suggested it will throw a NullPointerException.
Please initialise it with some value(s) and then you can use the length property correctly. For example:
String[] str = { "plastic", "paper", "use", "throw" };
System.out.println("Length is:::" + str.length);
The array 'str' is now defined, and so it's length also has a defined value.
How do I create a link to add an entry to a calendar?
UPDATE (free for personal use):
HTTPS IS NOW SUPPORTED
While my answer below detailing how-to for each service WILL work, IMO it's much easier now to go with a third-party like AddThisEvent [https://addthisevent.com]. It lets you customize lots of options as well as add to Facebook and more. Unfortunately, they've now made it a paid service for anything other than personal use and do enforce this.
I assume there are other third-party solutions like this one, but I can only speak to this one, and it has worked great for us so far.
For an "Add to my Google Calendar", they used to have a code generator form you could use, but have since taken it down. For more details on Google Calendar links, see squarecandy's answer below.
For Outlook, it's a BIT more complicated, but basically you need to create a .vcs
file with the event's data, and just make a link to that file. Step-by-step instructions here.
For an iCal link, you could use a PHP class like this one, or follow this page's instructions on how to create an ics
file (iCal file).
Remove final character from string
What you are trying to do is an extension of string slicing in Python:
Say all strings are of length 10, last char to be removed:
>>> st[:9]
'abcdefghi'
To remove last N
characters:
>>> N = 3
>>> st[:-N]
'abcdefg'
Sending mail attachment using Java
If you allow me, it works fine also for multi-attachments, the 1st above answer of NINCOMPOOP, with just a little modification like follows:
DataSource source,source2,source3,source4, ...;
source = new FileDataSource(myfile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(myfile);
multipart.addBodyPart(messageBodyPart);
source2 = new FileDataSource(myfile2);
messageBodyPart.setDataHandler(new DataHandler(source2));
messageBodyPart.setFileName(myfile2);
multipart.addBodyPart(messageBodyPart);
source3 = new FileDataSource(myfile3);
messageBodyPart.setDataHandler(new DataHandler(source3));
messageBodyPart.setFileName(myfile3);
multipart.addBodyPart(messageBodyPart);
source4 = new FileDataSource(myfile4);
messageBodyPart.setDataHandler(new DataHandler(source4));
messageBodyPart.setFileName(myfile4);
multipart.addBodyPart(messageBodyPart);
...
message.setContent(multipart);
VBA Convert String to Date
Try using Replace
to see if it will work for you. The problem as I see it which has been mentioned a few times above is the CDate function is choking on the periods. You can use replace to change them to slashes. To answer your question about a Function in vba that can parse any date format, there is not any you have very limited options.
Dim current as Date, highest as Date, result() as Date
For Each itemDate in DeliveryDateArray
Dim tempDate As String
itemDate = IIf(Trim(itemDate) = "", "0", itemDate) 'Added per OP's request.
tempDate = Replace(itemDate, ".", "/")
current = Format(CDate(tempDate),"dd/mm/yyyy")
if current > highest then
highest = current
end if
' some more operations an put dates into result array
Next itemDate
'After activating final sheet...
Range("A1").Resize(UBound(result), 1).Value = Application.Transpose(result)
Convert milliseconds to date (in Excel)
Converting your value in milliseconds to days is simply (MsValue / 86,400,000)
We can get 1/1/1970 as numeric value by DATE(1970,1,1)
= (MsValueCellReference / 86400000) + DATE(1970,1,1)
Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss
gives me a date and time of 19/04/2010 08:16:11
How do I navigate to a parent route from a child route?
constructor(private router: Router) {}
navigateOnParent() {
this.router.navigate(['../some-path-on-parent']);
}
The router supports
- absolute paths
/xxx
- started on the router of the root component
- relative paths
xxx
- started on the router of the current component
- relative paths
../xxx
- started on the parent router of the current component
How do I test if a string is empty in Objective-C?
You can have an empty string in two ways:
1) @"" // Does not contain space
2) @" " // Contain Space
Technically both the strings are empty. We can write both the things just by using ONE Condition
if ([firstNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].length==0)
{
NSLog(@"Empty String");
}
else
{
NSLog(@"String contains some value");
}
Which versions of SSL/TLS does System.Net.WebRequest support?
This is an important question. The SSL 3 protocol (1996) is irreparably broken by the Poodle attack published 2014. The IETF have published "SSLv3 MUST NOT be used". Web browsers are ditching it. Mozilla Firefox and Google Chrome have already done so.
Two excellent tools for checking protocol support in browsers are SSL Lab's client test and https://www.howsmyssl.com/ . The latter does not require Javascript, so you can try it from .NET's HttpClient:
// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");
File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);
// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");
The result is damning:
Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.
That's concerning. It's comparable to 2006's Internet Explorer 7.
To list exactly which protocols a HTTP client supports, you can try the version-specific test servers below:
var test_servers = new Dictionary<string, string>();
test_servers["SSL 2"] = "https://www.ssllabs.com:10200";
test_servers["SSL 3"] = "https://www.ssllabs.com:10300";
test_servers["TLS 1.0"] = "https://www.ssllabs.com:10301";
test_servers["TLS 1.1"] = "https://www.ssllabs.com:10302";
test_servers["TLS 1.2"] = "https://www.ssllabs.com:10303";
var supported = new Func<string, bool>(url =>
{
try { return new HttpClient().GetAsync(url).Result.IsSuccessStatusCode; }
catch { return false; }
});
var supported_protocols = test_servers.Where(server => supported(server.Value));
Console.WriteLine(string.Join(", ", supported_protocols.Select(x => x.Key)));
I'm using .NET Framework 4.6.2. I found HttpClient supports only SSL 3 and TLS 1.0. That's concerning. This is comparable to 2006's Internet Explorer 7.
Update: It turns HttpClient does support TLS 1.1 and 1.2, but you have to turn them on manually at System.Net.ServicePointManager.SecurityProtocol
. See https://stackoverflow.com/a/26392698/284795
I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?
Full path from file input using jQuery
You can't: It's a security feature in all modern browsers.
For IE8, it's off by default, but can be reactivated using a security setting:
When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.
The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.
In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.
More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.
how to use XPath with XDocument?
you can use the example from Microsoft - for you without namespace:
using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");
should do it
Execution failed for task ':app:compileDebugAidl': aidl is missing
I had the same error i fixed it by going to the build.gradle (Module: app)
and changed this line from :
buildToolsVersion "23.0.0 rc1"
to :
buildToolsVersion "22.0.1"
You will need to go the SDK Manager and check if you have the 22.0.1 build tools. If not, you can use the right build tools but avoid the 23.0.0 rc1.
Text in HTML Field to disappear when clicked?
This is as simple I think the solution that should solve all your problems:
<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">
This is your submit button:
<input type="submit" id= "submitBtn" value="Submit">
then put this small jQuery in a js file:
//this will submit only if the value is not default
$("#submitBtn").click(function () {
if ($("#valueText").val() === "ENTER VALUE")
{
alert("please insert a valid value");
return false;
}
});
//this will put default value if the field is empty
$("#valueText").blur(function () {
if(this.value == ''){
this.value = 'ENTER VALUE';
}
});
//this will empty the field is the value is the default one
$("#valueText").focus(function () {
if (this.value == 'ENTER VALUE') {
this.value = '';
}
});
And it works also in older browsers. Plus it can easily be converted to normal javascript if you need.
Visual Studio 2015 or 2017 does not discover unit tests
If you are working with multiple App or Web.Config files. eg:
Its likely you are using a Config that is RELEASE MODE and that will strip the Debug mode setting from the config:
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
Change the Config to one that doesn't remove DEBUG MODE.
How to restrict user to type 10 digit numbers in input element?
The snippet below does the job as expected!
<input type="text" name="AUS" pattern="[0-9]{10}" title="You can enter only 10 digits..." />
//type="text" <!-- always -->
//name="AUS" <!-- for Australia -->
//pattern="[0-9]{10}" <!-- 10 digits from 0 to 9 -->
//title="You can enter only 10 digits..." <!-- Pops a warning when input mismatches -->
How to solve error: "Clock skew detected"?
One of the reason may be improper date/time of your PC.
In Ubuntu PC to check the date and time using:
date
Example, One of the ways to update date and time is:
date -s "23 MAR 2017 17:06:00"
Invoking JavaScript code in an iframe from the parent page
Quirksmode had a post on this.
Since the page is now broken, and only accessible via archive.org, I reproduced it here:
IFrames
On this page I give a short overview of accessing iframes from the page they’re on. Not surprisingly, there are some browser considerations.
An iframe is an inline frame, a frame that, while containing a completely separate page with its own URL, is nonetheless placed inside another HTML page. This gives very nice possibilities in web design. The problem is to access the iframe, for instance to load a new page into it. This page explains how to do it.
Frame or object?
The fundamental question is whether the iframe is seen as a frame or as an object.
- As explained on the Introduction to frames pages, if you use frames the browser creates a frame hierarchy for you (
top.frames[1].frames[2]
and such). Does the iframe fit into this frame hierarchy?
- Or does the browser see an iframe as just another object, an object that happens to have a src property? In that case we have to use a standard DOM call (like
document.getElementById('theiframe'))
to access it.
In general browsers allow both views on 'real' (hard-coded) iframes, but generated iframes cannot be accessed as frames.
NAME attribute
The most important rule is to give any iframe you create a name
attribute, even if you also use an id
.
<iframe src="iframe_page1.html"
id="testiframe"
name="testiframe"></iframe>
Most browsers need the name
attribute to make the iframe part of the frame hierarchy. Some browsers (notably Mozilla) need the id
to make the iframe accessible as an object. By assigning both attributes to the iframe you keep your options open. But name
is far more important than id
.
Access
Either you access the iframe as an object and change its src
or you access the iframe as a frame and change its location.href
.
document.getElementById('iframe_id').src = 'newpage.html';
frames['iframe_name'].location.href = 'newpage.html';
The frame syntax is slightly preferable because Opera 6 supports it but not the object syntax.
Accessing the iframe
So for a complete cross–browser experience you should give the iframe a name and use the
frames['testiframe'].location.href
syntax. As far as I know this always works.
Accessing the document
Accessing the document inside the iframe is quite simple, provided you use the name
attribute. To count the number of links in the document in the iframe, do
frames['testiframe'].document.links.length
.
Generated iframes
When you generate an iframe through the W3C DOM the iframe is not immediately entered into the frames
array, though, and the frames['testiframe'].location.href
syntax will not work right away. The browser needs a little time before the iframe turns up in the array, time during which no script may run.
The document.getElementById('testiframe').src
syntax works fine in all circumstances.
The target
attribute of a link doesn't work either with generated iframes, except in Opera, even though I gave my generated iframe both a name
and an id
.
The lack of target
support means that you must use JavaScript to change the content of a generated iframe, but since you need JavaScript anyway to generate it in the first place, I don't see this as much of a problem.
Text size in iframes
A curious Explorer 6 only bug:
When you change the text size through the View menu, text sizes in iframes are correctly changed. However, this browser does not change the line breaks in the original text, so that part of the text may become invisible, or line breaks may occur while the line could still hold another word.
iPhone - Grand Central Dispatch main thread
Dispatching a block to the main queue is usually done from a background queue to signal that some background processing has finished e.g.
- (void)doCalculation
{
//you can use any string instead "com.mycompany.myqueue"
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(backgroundQueue, ^{
int result = <some really long calculation that takes seconds to complete>;
dispatch_async(dispatch_get_main_queue(), ^{
[self updateMyUIWithResult:result];
});
});
}
In this case, we are doing a lengthy calculation on a background queue and need to update our UI when the calculation is complete. Updating UI normally has to be done from the main queue so we 'signal' back to the main queue using a second nested dispatch_async.
There are probably other examples where you might want to dispatch back to the main queue but it is generally done in this way i.e. nested from within a block dispatched to a background queue.
- background processing finished -> update UI
- chunk of data processed on background queue -> signal main queue to start next chunk
- incoming network data on background queue -> signal main queue that message has arrived
- etc etc
As to why you might want to dispatch to the main queue from the main queue... Well, you generally wouldn't although conceivably you might do it to schedule some work to do the next time around the run loop.
how to call service method from ng-change of select in angularjs?
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
Communication between multiple docker-compose projects
Just a small adittion to @johnharris85's great answer,
when you are running a docker compose file, a "default
" network is created
so you can just add it to the other compose file as an external network:
# front/docker-compose.yml
version: '2'
services:
front_service:
...
...
# api/docker-compose.yml
version: '2'
services:
api_service:
...
networks:
- front_default
networks:
front_default:
external: true
For me this approach was more suited because I did not own the first docker-compose file and wanted to communicate with it.
to call onChange event after pressing Enter key
pressing Enter when the focus in on a form control (input) normally triggers a submit
(onSubmit) event on the form itself (not the input) so you could bind your this.handleInput
to the form onSubmit.
Alternatively you could bind it to the blur
(onBlur) event on the input
which happens when the focus is removed (e.g. tabbing to the next element that can get focus)
What are .tpl files? PHP, web design
The files are using some sort of template engine in which curly braces indicate variables being generated by that templating engine, the files creating such variables must be present elsewhere with the more or less same name as the tpl file name. Here are some of templates engine mostly used.
Smarty
Savant
Tinybutstrong
etc
With smarty being widely used.
Using global variables in a function
If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.
Say you've got a module like this:
# sample.py
myGlobal = 5
def func1():
myGlobal = 42
def func2():
print myGlobal
func1()
func2()
You might expecting this to print 42, but instead it prints 5. As has already been mentioned, if you add a 'global
' declaration to func1()
, then func2()
will print 42.
def func1():
global myGlobal
myGlobal = 42
What's going on here is that Python assumes that any name that is assigned to, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).
When you assign 42 to the name myGlobal
, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is garbage-collected when func1()
returns; meanwhile, func2()
can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of myGlobal
inside func1()
before you assign to it, you'd get an UnboundLocalError
, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the 'global
' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally.
(I believe that this behavior originated largely through an optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.)
Keep CMD open after BAT file executes
Depending on how you are running the command, you can put /k
after cmd
to keep the window open.
cmd /k my_script.bat
Simply adding cmd /k
to the end of your batch file will work too. Credit to Luigi D'Amico who posted about this in the comments below.
Execute PHP script in cron job
Cron is a time-based scheduling service in Linux / Unix-like computer operating systems. Cron job are used to schedule commands to be executed periodically.
You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, /etc/cron./* directories. It also checks the /var/spool/cron/ directory.
Configuring Cron Tasks
In the following example, the crontab command shown below will activate the cron tasks automatically every ten minutes:
*/10 * * * * /usr/bin/php /opt/test.php
In the above sample, the */10 * * * * represents when the task should happen. The first figure represents minutes – in this case, on every "ten" minute. The other figures represent, respectively, hour, day, month and day of the week.
*
is a wildcard, meaning "every time".
Start with finding out your PHP binary by typing in command line:
whereis php
The output should be something like:
php: /usr/bin/php /etc/php.ini /etc/php.d /usr/lib64/php /usr/include/php /usr/share/php /usr/share/man/man1/php.1.gz
Specify correctly the full path in your command.
Type the following command to enter cronjob:
crontab -e
To see what you got in crontab.
EDIT 1:
To exit from vim editor without saving just click:
Shift+:
And then type q!
Prevent any form of page refresh using jQuery/Javascript
You can't prevent the user from refreshing, nor should you really be trying. You should go back to why you need this solution, what's the root problem here?. Start there and find a different way to go about solving the problem. Perhaps is you elaborated on why you think you need to do this it would help in finding such a solution.
Breaking fundamental browser features is never a good idea, over 99.999999999% of the internet works and refreshes with F5, this is an expectation of the user, one you shouldn't break.
Pass variables to AngularJS controller, best practice?
You could create a basket service. And generally in JS you use objects instead of lots of parameters.
Here's an example: http://jsfiddle.net/2MbZY/
var app = angular.module('myApp', []);
app.factory('basket', function() {
var items = [];
var myBasketService = {};
myBasketService.addItem = function(item) {
items.push(item);
};
myBasketService.removeItem = function(item) {
var index = items.indexOf(item);
items.splice(index, 1);
};
myBasketService.items = function() {
return items;
};
return myBasketService;
});
function MyCtrl($scope, basket) {
$scope.newItem = {};
$scope.basket = basket;
}
TypeError: can't use a string pattern on a bytes-like object in re.findall()
The problem is that your regex is a string, but html
is bytes:
>>> type(html)
<class 'bytes'>
Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.
You can either decode
the bytes to a string:
html = html.decode('ISO-8859-1') # encoding may vary!
title = re.findall(pattern, html) # no more error
Or use a bytes regex:
regex = rb'<title>(,+?)</title>'
# ^
In this particular context, you can get the encoding from the response headers:
with urllib.request.urlopen(url) as response:
encoding = response.info().get_param('charset', 'utf8')
html = response.read().decode(encoding)
See the urlopen
documentation for more details.
ruby 1.9: invalid byte sequence in UTF-8
In Ruby 1.9.3 it is possible to use String.encode to "ignore" the invalid UTF-8 sequences. Here is a snippet that will work both in 1.8 (iconv) and 1.9 (String#encode) :
require 'iconv' unless String.method_defined?(:encode)
if String.method_defined?(:encode)
file_contents.encode!('UTF-8', 'UTF-8', :invalid => :replace)
else
ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
file_contents = ic.iconv(file_contents)
end
or if you have really troublesome input you can do a double conversion from UTF-8 to UTF-16 and back to UTF-8:
require 'iconv' unless String.method_defined?(:encode)
if String.method_defined?(:encode)
file_contents.encode!('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
file_contents.encode!('UTF-8', 'UTF-16')
else
ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
file_contents = ic.iconv(file_contents)
end
Simple bubble sort c#
I wanted to add to the accepted answer something different:
Number of iterations can be reduced as well, as below.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
int arrLength = arr.Length;
for (int write = 0; write < arr.Length - 1; write++, arrLength--)
{
for (int sort = 0; sort < arrLength - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
foreach (var item in arr)
{
Console.WriteLine(item);
}
Catch multiple exceptions in one line (except block)
From Python Documentation:
An except clause may name multiple exceptions as a parenthesized tuple, for example
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
Or, for Python 2 only:
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as
.
Font awesome is not showing icon
In my case, I needed to combine the answers from sst & Bruno Leveque:
Example Django:
# in myapplication/vendor/fontawesome/ everything unpacked
<link rel="stylesheet" href="{% static 'myapplication/vendor/fontawesome/css/all.min.css' %}">
How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#
Just made this in a few minutes:
using System;
using System.Management;
namespace WindowsFormsApplication_CS
{
class NetworkManagement
{
public void setIP(string ip_address, string subnet_mask)
{
ManagementClass objMC =
new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
ManagementBaseObject setIP;
ManagementBaseObject newIP =
objMO.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { ip_address };
newIP["SubnetMask"] = new string[] { subnet_mask };
setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
}
}
}
public void setGateway(string gateway)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
ManagementBaseObject setGateway;
ManagementBaseObject newGateway =
objMO.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { gateway };
newGateway["GatewayCostMetric"] = new int[] { 1 };
setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
}
}
}
public void setDNS(string NIC, string DNS)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
// if you are using the System.Net.NetworkInformation.NetworkInterface
// you'll need to change this line to
// if (objMO["Caption"].ToString().Contains(NIC))
// and pass in the Description property instead of the name
if (objMO["Caption"].Equals(NIC))
{
ManagementBaseObject newDNS =
objMO.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = DNS.Split(',');
ManagementBaseObject setDNS =
objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
public void setWINS(string NIC, string priWINS, string secWINS)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
if (objMO["Caption"].Equals(NIC))
{
ManagementBaseObject setWINS;
ManagementBaseObject wins =
objMO.GetMethodParameters("SetWINSServer");
wins.SetPropertyValue("WINSPrimaryServer", priWINS);
wins.SetPropertyValue("WINSSecondaryServer", secWINS);
setWINS = objMO.InvokeMethod("SetWINSServer", wins, null);
}
}
}
}
}
}
php create object without class
you can always use new stdClass()
. Example code:
$object = new stdClass();
$object->property = 'Here we go';
var_dump($object);
/*
outputs:
object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/
Also as of PHP 5.4 you can get same output with:
$object = (object) ['property' => 'Here we go'];
ggplot combining two plots from different data.frames
As Baptiste said, you need to specify the data argument at the geom level. Either
#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) +
geom_point() +
geom_step(data = df2)
)
or
#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) +
geom_point(data = df1) +
geom_step(data = df2)
)
Computed / calculated / virtual / derived columns in PostgreSQL
I have a code that works and use the term calculated, I'm not on postgresSQL pure tho we run on PADB
here is how it's used
create table some_table as
select category,
txn_type,
indiv_id,
accum_trip_flag,
max(first_true_origin) as true_origin,
max(first_true_dest ) as true_destination,
max(id) as id,
count(id) as tkts_cnt,
(case when calculated tkts_cnt=1 then 1 else 0 end) as one_way
from some_rando_table
group by 1,2,3,4 ;
Intellij IDEA Java classes not auto compiling on save
WARNING
Eclipse Mode plug-in is obsolete and is not compatible with the recent IDEA 12+ builds. If you install it, IDE will hang on every file change and will respond extremely slow.
IntelliJ IDEA doesn't use automatic build, it detects errors on the fly, not via compiler. Similar to Eclipse mode will be available in IDEA 12:
Use Build
| Make
, it invokes the incremental make process that will compile only changed and dependent files (it's very fast).
There is also a FAQ entry that may help.
Update on the automatic make feature:
When run/debug configuration is running, Make project automatically
has no effect. Classes on disk will change only on Build
| Make
. It's the core design decision as in our opinion class changes on disk should be always under user's control. Automatic make is not the copycat of Eclipse feature, it works differently and it's main purpose is to save time waiting for the classes to be ready when they are really needed (before running the app or tests). Automatic make doesn't replace the explicit compilation that you still need to trigger like in the case described in this question. If you are looking for different behavior, EclipseMode plug-in linked in the FAQ above would be a better choice.
Python - 'ascii' codec can't decode byte
You use u"??".encode('utf8')
to encode an unicode string.
But if you want to represent "??"
, you should decode it. Just like:
"??".decode("utf8")
You will get what you want. Maybe you should learn more about encode & decode.
How to prevent a jQuery Ajax request from caching in Internet Explorer?
you can define it like this :
let table = $('.datatable-sales').DataTable({
processing: true,
responsive: true,
serverSide: true,
ajax: {
url: "<?php echo site_url("your url"); ?>",
cache: false,
type: "POST",
data: {
<?php echo your api; ?>,
}
}
or like this :
$.get({url: <?php echo json_encode(site_url('your api'))?>, cache: false})
hope it helps
How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?
If you have a one to many relationship in your query, duplicate rows may occurs on one side.
Suppose the following
TABLE TEAM
ID TEAM_NAME
0 BULLS
1 LAKERS
TABLE PLAYER
ID TEAM_ID PLAYER_NAME
0 0 JORDAN
1 0 PIPPEN
And you execute a query like
SELECT
TEAM.TEAM_NAME,
PLAYER.PLAYER_NAME
FROM TEAM
INNER JOIN PLAYER
You will get
TEAM_NAME PLAYER_NAME
BULLS JORDAN
BULLS PIPPEN
So you will have duplicate TEAM NAME. Even using DISTINCT clause, your result set will contain duplicate TEAM NAME
So if you do not want duplicate TEAM_NAME in your query, do the following
SELECT ID, TEAM_NAME FROM TEAM
And for each team ID encountered executes
SELECT PLAYER_NAME FROM PLAYER WHERE TEAM_ID = <PUT_TEAM_ID_RIGHT_HERE>
So this way you will not get duplicates references on one side
regards,
How to find EOF through fscanf?
If you have integers in your file fscanf returns 1 until integer occurs. For example:
FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;
for ( int i = 0; i < 10; i++ ) {
counter = fscanf(in, "%d", &sequence);
if ( counter == 1 ) {
length += 1;
}
}
To find out the end of the file with symbols you can use EOF. For example:
char symbol;
FILE *in = fopen("./task.in", "r");
for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
printf("%c", symbol);
}
pandas read_csv and filter columns with usecols
This code achieves what you want --- also its weird and certainly buggy:
I observed that it works when:
a) you specify the index_col
rel. to the number of columns you really use -- so its three columns in this example, not four (you drop dummy
and start counting from then onwards)
b) same for parse_dates
c) not so for usecols
;) for obvious reasons
d) here I adapted the names
to mirror this behaviour
import pandas as pd
from StringIO import StringIO
csv = """dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5
"""
df = pd.read_csv(StringIO(csv),
index_col=[0,1],
usecols=[1,2,3],
parse_dates=[0],
header=0,
names=["date", "loc", "", "x"])
print df
which prints
x
date loc
2009-01-01 a 1
2009-01-02 a 3
2009-01-03 a 5
2009-01-01 b 1
2009-01-02 b 3
2009-01-03 b 5
no pg_hba.conf entry for host
For those who are getting this error in DBeaver the solution was found here at line:
@lcustodio on the SSL page, set SSL mode: require and either leave the SSL Factory blank or use the org.postgresql.ssl.NonValidatingFactory
Under Network -> SSL tab I checked the Use SLL checkbox and set Advance -> SSL Mode = require and it now works.
Trigger change event <select> using jquery
Give links in value of the option tag
<select size="1" name="links" onchange="window.location.href=this.value;">
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
How to SELECT a dropdown list item by value programmatically
If you know that the dropdownlist contains the value you're looking to select, use:
ddl.SelectedValue = "2";
If you're not sure if the value exists, use (or you'll get a null reference exception):
ListItem selectedListItem = ddl.Items.FindByValue("2");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
}
How to alter SQL in "Edit Top 200 Rows" in SSMS 2008
The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:
- Go to Tools in top nav
- Select options, then SQL Service Object Explorer (on left)
- On right side of panel, click into the field that contains 200 and change to 300 (or whatever number you wish)
- Click OK and voila, you're all set!
sum two columns in R
You can use a for loop:
for (i in 1:nrow(df)) {
df$col3[i] <- df$col1[i] + df$col2[i]
}
What is a elegant way in Ruby to tell if a variable is a Hash or an Array?
You can just do:
@some_var.class == Hash
or also something like:
@some_var.is_a?(Hash)
It's worth noting that the "is_a?" method is true if the class is anywhere in the objects ancestry tree. for instance:
@some_var.is_a?(Object) # => true
the above is true if @some_var is an instance of a hash or other class that stems from Object. So, if you want a strict match on the class type, using the == or instance_of? method is probably what you're looking for.
Finding non-numeric rows in dataframe in pandas?
You could use np.isreal
to check the type of each element (applymap applies a function to each element in the DataFrame):
In [11]: df.applymap(np.isreal)
Out[11]:
a b
item
a True True
b True True
c True True
d False True
e True True
If all in the row are True then they are all numeric:
In [12]: df.applymap(np.isreal).all(1)
Out[12]:
item
a True
b True
c True
d False
e True
dtype: bool
So to get the subDataFrame of rouges, (Note: the negation, ~, of the above finds the ones which have at least one rogue non-numeric):
In [13]: df[~df.applymap(np.isreal).all(1)]
Out[13]:
a b
item
d bad 0.4
You could also find the location of the first offender you could use argmin:
In [14]: np.argmin(df.applymap(np.isreal).all(1))
Out[14]: 'd'
As @CTZhu points out, it may be slightly faster to check whether it's an instance of either int or float (there is some additional overhead with np.isreal):
df.applymap(lambda x: isinstance(x, (int, float)))
Convert a String to int?
let my_u8: u8 = "42".parse::<u8>().unwrap();
let my_u32: u32 = "42".parse::<u32>().unwrap();
// or, to be safe, match the `Err`
match "foobar".parse::<i32>() {
Ok(n) => do_something_with(n),
Err(e) => weep_and_moan(),
}
str::parse::<u32>
returns a Result<u32, core::num::ParseIntError>
and Result::unwrap
"Unwraps a result, yielding the content of an Ok
[or] panics if the value is an Err
, with a panic message provided by the Err
's value."
str::parse
is a generic function, hence the type in angle brackets.
C++ error: "Array must be initialized with a brace enclosed initializer"
The syntax to statically initialize an array uses curly braces, like this:
int array[10] = { 0 };
This will zero-initialize the array.
For multi-dimensional arrays, you need nested curly braces, like this:
int cipher[Array_size][Array_size]= { { 0 } };
Note that Array_size
must be a compile-time constant for this to work. If Array_size
is not known at compile-time, you must use dynamic initialization. (Preferably, an std::vector
).
Drawing in Java using Canvas
Suggestions:
- Don't use Canvas as you shouldn't mix AWT with Swing components unnecessarily.
- Instead use a JPanel or JComponent.
- Don't get your Graphics object by calling
getGraphics()
on a component as the Graphics object obtained will be transient.
- Draw in the JPanel's
paintComponent()
method.
- All this is well explained in several tutorials that are easily found. Why not read them first before trying to guess at this stuff?
Key tutorial links:
Virtualbox "port forward" from Guest to Host
That's not possible. localhost
always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.
If you want to access it e.g. in a browser, connect to it using the local IP instead:
http://192.168.180.1:8000
This is just an example of course, you can find out the actual IP by issuing an ifconfig
command on a shell in the guest operating system.
Handling very large numbers in Python
The python interpreter will handle it for you, you just have to do your operations (+, -, *, /), and it will work as normal.
The int
value is unlimited.
Careful when doing division, by default the quotient is turned into float
, but float
does not support such large numbers. If you get an error message saying float
does not support such large numbers, then it means the quotient is too large to be stored in float
you’ll have to use floor division (//
).
It ignores any decimal that comes after the decimal point, this way, the result will be int
, so you can have a large number result.
>>>10//3
3
>>>10//4
2
when exactly are we supposed to use "public static final String"?
final
indicates that the value of the variable won't change - in other words, a constant whose value can't be modified after it is declared.
Use public final static String
when you want to create a String
that:
- belongs to the class (
static
: no instance necessary to use it), and that
- won't change (
final
), for instance when you want to define a String
constant that will be available to all instances of the class, and to other objects using the class.
Example:
public final static String MY_CONSTANT = "SomeValue";
// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT)
Similarly:
public static final int ERROR_CODE = 127;
It isn't required to use final
, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.
Even if the constant will only be used - read - in the current class and/or in only one place, it's good practice to declare all constants as final
: it's clearer, and during the lifetime of the code the constant may end up being used in more than one place.
Furthermore using final
may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.
Optional Parameters in Web Api Attribute Routing
For an incoming request like /v1/location/1234
, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid
and not to deviceid
.
I think you should change your route template to be like
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
and then parse the deiveOrAppid
to figure out the type of id.
Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ?
character in this case.
For example:
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
Is Laravel really this slow?
Laravel is not actually that slow. 500-1000ms is absurd; I got it down to 20ms in debug mode.
The problem was Vagrant/VirtualBox + shared folders. I didn't realize they incurred such a performance hit. I guess because Laravel has so many dependencies (loads ~280 files) and each of those file reads is slow, it adds up really quick.
kreeves pointed me in the right direction, this blog post describes a new feature in Vagrant 1.5 that lets you rsync your files into the VM rather than using a shared folder.
There's no native rsync client on Windows, so you'll have to use cygwin. Install it, and make sure to check off Net/rsync. Add C:\cygwin64\bin
to your paths. [Or you can install it on Win10/Bash]
Vagrant introduces the new feature. I'm using Puphet, so my Vagrantfile looks a bit funny. I had to tweak it to look like this:
data['vm']['synced_folder'].each do |i, folder|
if folder['source'] != '' && folder['target'] != '' && folder['id'] != ''
config.vm.synced_folder "#{folder['source']}", "#{folder['target']}",
id: "#{folder['id']}",
type: "rsync",
rsync__auto: "true",
rsync__exclude: ".hg/"
end
end
Once you're all set up, try vagrant up
. If everything goes smoothly your machine should boot up and it should copy all the files over. You'll need to run vagrant rsync-auto
in a terminal to keep the files up to date. You'll pay a little bit in latency, but for 30x faster page loads, it's worth it!
If you're using PhpStorm, it's auto-upload feature works even better than rsync. PhpStorm creates a lot of temporary files which can trip up file watchers, but if you let it handle the uploads itself, it works nicely.
One more option is to use lsyncd. I've had great success using this on Ubuntu host -> FreeBSD guest. I haven't tried it on a Windows host yet.
Does Arduino use C or C++?
Both are supported. To quote the Arduino homepage,
The core libraries are written in C and C++ and compiled using avr-gcc
Note that C++ is a superset of C (well, almost), and thus can often look very similar. I am not an expert, but I guess that most of what you will program for the Arduino in your first year on that platform will not need anything but plain C.
Android Studio - Unable to find valid certification path to requested target
It usually happen when your have included the dependency and it won't have repository reference like mavenCentral() or jcenter() etc to download it
What I usually do identify such dependency is set gradle to work offline, Android studio will automatically show a dependency which is not locally available, then look for the dependency details in their providers github page like from which repository to pick from and update your repositories and sink it. Hope it will work
UITableView Separator line
My project is based on iOS 7
This helps me
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
Then put a subview into cell as separator!
Comparing strings in C# with OR in an if statement
Here's a more valid way which also check if your textbox is filled with only blanks.
// When spaces are not allowed
if (string.IsNullOrWhiteSpace(txtBox1.Text) || string.IsNullOrWhiteSpace(txtBox2.Text))
//...give error...
// When spaces are allowed
if (string.IsNullOrEmpty(txtBox1.Text) || string.IsNullOrEmpty(txtBox2.Text))
//...give error...
The edited answer of @Habib.OSU is also fine, this is just another approach.
Pure CSS collapse/expand div
You just need to iterate the anchors in the two links.
<a href="#hide2" class="hide" id="hide2">+</a>
<a href="#show2" class="show" id="show2">-</a>
See this jsfiddle http://jsfiddle.net/eJX8z/
I also added some margin to the FAQ call to improve the format.
Binding an Image in WPF MVVM
Displaying an Image
in WPF is much easier than that. Try this:
<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left"
Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom"
Grid.Row="8" Width="200" Grid.ColumnSpan="2" />
And the property can just be a string
:
public string DisplayedImage
{
get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}
Although you really should add your images to a folder named Images
in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
UPDATE >>>
As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.
UPDATE 2 >>>
If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image
control. Using the string
property that I suggested, try this:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
If you can't see the file path in the TextBlock
, then you probably haven't set your DataContext
to the instance of your view model. If you can see the text, then the problem is with your file path.
UPDATE 3 >>>
In .NET 4, the above Image.Source
values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack
path like this:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.
What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?
Differences in SOAP versions
Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.
The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.
The changes to the SOAP 1.2 specification that are significant include the following updates:
SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset).
The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.
In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.
SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ.
SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations.
SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages.
The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations.
Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.
There is not difine POST AND GET method for particular android....but all here is differance
GET
The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.
What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.
POST
The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.
Link to original IBM source
Center a H1 tag inside a DIV
You can use display: table-cell
in order to render the div as a table cell and then use vertical-align
like you would do in a normal table cell.
#AlertDiv {
display: table-cell;
vertical-align: middle;
text-align: center;
}
You can try it here:
http://jsfiddle.net/KaXY5/424/
Combining C++ and C - how does #ifdef __cplusplus work?
extern "C"
doesn't change the presence or absence of the __cplusplus
macro. It just changes the linkage and name-mangling of the wrapped declarations.
You can nest extern "C"
blocks quite happily.
If you compile your .c
files as C++ then anything not in an extern "C"
block, and without an extern "C"
prototype will be treated as a C++ function. If you compile them as C then of course everything will be a C function.
Yes
You can safely mix C and C++ in this way.
shorthand If Statements: C#
To use shorthand to get the direction:
int direction = column == 0
? 0
: (column == _gridSize - 1 ? 1 : rand.Next(2));
To simplify the code entirely:
if (column == gridSize - 1 || rand.Next(2) == 1)
{
}
else
{
}
How do you convert epoch time in C#?
Use the method DateTimeOffset.ToUnixTimeMilliseconds() It returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z.
This is only supported with Framework 4.6 or higher
var EPOCH = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
It's well documented here DateTimeOffset.ToUnixTimeMilliseconds
The other way out is to use the following
long EPOCH = DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1,0,0,0,0).Ticks;
To get the EPOCH with seconds only you may use
var Epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
and convert the Epoch
to DateTime
with the following method
private DateTime Epoch2UTCNow(int epoch)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch);
}
add an element to int [] array in java
The ...
can only be used in JDK 1.5 or later. If you are using JDK 4 or lower, use this code:'
public static int[] addElement(int[] original, int newelement) {
int[] nEw = new int[original.length + 1];
System.arraycopy(original, 0, nEw, 0, original.length);
nEw[original.length] = newelement;
}
otherwise (JDK 5 or higher):
public static int[] addElement(int[] original, int... elements) { // This can add multiple elements at once; addElement(int[], int) will still work though.
int[] nEw = new int[original.length + elements.length];
System.arraycopy(original, 0, nEw, 0, original.length);
System.arraycopy(elements, 0, nEw, original.length, elements.length);
return nEw;
}
Of course, as many have mentioned above, you could use a Collection
or an ArrayList
, which allows you to use the .add()
method.
string in namespace std does not name a type
Nouns.h
doesn't include <string>
, but it needs to. You need to add
#include <string>
at the top of that file, otherwise the compiler doesn't know what std::string
is when it is encountered for the first time.
How to Alter Constraint
No. We cannot alter the constraint, only thing we can do is drop and recreate it
ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]
Foreign Key Constraint
Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade
Primary Key constraint
Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)
Java balanced expressions check {[()]}
Please try this.
import java.util.Stack;
public class PatternMatcher {
static String[] patterns = { "{([])}", "{}[]()", "(}{}]]", "{()", "{}" };
static String openItems = "{([";
boolean isOpen(String sy) {
return openItems.contains(sy);
}
String getOpenSymbol(String byCloseSymbol) {
switch (byCloseSymbol) {
case "}":
return "{";
case "]":
return "[";
case ")":
return "(";
default:
return null;
}
}
boolean isValid(String pattern) {
if(pattern == null) {
return false;
}
Stack<String> stack = new Stack<String>();
char[] symbols = pattern.toCharArray();
if (symbols.length == 0 || symbols.length % 2 != 0) {
return false;
}
for (char c : symbols) {
String symbol = Character.toString(c);
if (isOpen(symbol)) {
stack.push(symbol);
} else {
String openSymbol = getOpenSymbol(symbol);
if (stack.isEmpty()
|| openSymbol == null
|| !openSymbol.equals(stack.pop())) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
PatternMatcher patternMatcher = new PatternMatcher();
for (String pattern : patterns) {
boolean valid = patternMatcher.isValid(pattern);
System.out.println(pattern + "\t" + valid);
}
}
}
How to use BigInteger?
Biginteger
is an immutable class.
You need to explicitly assign value of your output to sum like this:
sum = sum.add(BigInteger.valueof(i));
What is null in Java?
null
is special value, it is not instance of anything. For obviously reason it cannot be instanceof
anything.
Entity Framework vs LINQ to SQL
I think the quick and dirty answer is that
- LINQ to SQL is the quick-and-easy way to do it. This means you will get going quicker, and deliver quicker if you are working on something smaller.
- Entity Framework is the all-out, no-holds-barred way to do it. This means you will take more time up-front, develop slower, and have more flexibility if you are working on something larger.
Connecting PostgreSQL 9.2.1 with Hibernate
Yes by using spring-boot with hibernate configuration files we can persist the data to the database.
keep hibernating .cfg.xml in your src/main/resources folder for reading the configurations related to database.
Trigger change event of dropdown
I don't know that much JQuery but I've heard it allows to fire native events with this syntax.
$(document).ready(function(){
$('#countrylist').change(function(e){
// Your event handler
});
// And now fire change event when the DOM is ready
$('#countrylist').trigger('change');
});
You must declare the change event handler before calling trigger() or change() otherwise it won't be fired. Thanks for the mention @LenielMacaferi.
More information here.
How do I enter a multi-line comment in Perl?
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
ASP.net using a form to insert data into an sql server table
There are tons of sample code online as to how to do this.
Here is just one example of how to do this:
http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx
you define the text boxes between the following tag:
<form id="form1" runat="server">
you create your textboxes and define them to runat="server" like so:
<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
define a button to process your logic like so (notice the onclick):
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
in the code behind, you define what you want the server to do if the user clicks on the button by defining a method named
protected void Button1_Click(object sender, EventArgs e)
or you could just double click the button in the design view.
Here is a very quick sample of code to insert into a table in the button click event (codebehind)
protected void Button1_Click(object sender, EventArgs e)
{
string name = TxtName.Text; // Scrub user data
string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
SqlConnection conn = null;
try
{
conn = new SqlConnection(connString);
conn.Open();
using(SqlCommand cmd = new SqlCommand())
{
cmd.Conn = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO dummyTable(name) Values (@var)";
cmd.Parameters.AddWithValue("@var", name);
int rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected ==1)
{
//Success notification
}
else
{
//Error notification
}
}
}
catch(Exception ex)
{
//log error
//display friendly error to user
}
finally
{
if(conn!=null)
{
//cleanup connection i.e close
}
}
}
manage.py runserver
You can run it for machines in your network by
./manage.py runserver 0.0.0.0:8000
And than you will be able to reach you server from any machine in your network.
Just type on other machine in browser http://192.168.0.1:8000
where 192.168.0.1
is IP of you server... and it ready to go....
or in you case:
- On machine
A
in command line ./manage.py runserver 0.0.0.0:8000
- Than try in machine
B
in browser type http://A:8000
- Make a sip of beer.
Source from django docs
File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?
If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator
.
This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator")
can be overriden via command line options and isn't as type safe as java.io.File.separator
.
The last one, java.nio.file.FileSystems.getDefault().getSeparator();
was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.
So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.
What is the difference between __str__ and __repr__?
str
- Creates a new string object from the given object.
repr
- Returns the canonical string representation of the object.
The differences:
str():
- makes object readable
- generates output for end-user
repr():
- needs code that reproduces object
- generates output for developer
How do I read any request header in PHP
if only one key is required to retrieved, For example "Host"
address is required, then we can use
apache_request_headers()['Host']
So that we can avoid loops and put it inline to the echo outputs
How to include SCSS file in HTML
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out.
Lynda provides great video tutorials on SASS.
there are also free screencasts you can google...
For official documentation visit this site
http://sass-lang.com/documentation/file.SASS_REFERENCE.html
And why have you chosen notepad to write Sass??
you can easily download some free text editors for better code handling.
Laravel 5.4 redirection to custom url after login
For newer versions of Laravel, please replace protected $redirectTo = RouteServiceProvider::HOME;
with protected $redirectTo = '/newurl';
and replace newurl
accordingly.
Tested with Laravel version-6
Combine or merge JSON on node.js without jQuery
Here is simple solution, to merge JSON.
I did the following.
- Convert each of the JSON to strings using
JSON.stringify(object)
.
- Concatenate all the JSON strings using
+
operator.
- Replace the pattern
/}{/g
with ","
Parse the result string back to JSON object
var object1 = {name: "John"};
var object2 = {location: "San Jose"};
var merged_object = JSON.parse((JSON.stringify(object1) + JSON.stringify(object2)).replace(/}{/g,","))
The resulting merged JSON will be
{name: "John", location: "San Jose"}
Why doesn't importing java.util.* include Arrays and Lists?
The difference between
import java.util.*;
and
import java.util.*;
import java.util.List;
import java.util.Arrays;
becomes apparent when the code refers to some other List
or Arrays
(for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays
declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays
will be used.
Plotting multiple curves same graph and same scale
I'm not sure what you want, but i'll use lattice.
x = rep(x,2)
y = c(y1,y2)
fac.data = as.factor(rep(1:2,each=5))
df = data.frame(x=x,y=y,z=fac.data)
# this create a data frame where I have a factor variable, z, that tells me which data I have (y1 or y2)
Then, just plot
xyplot(y ~x|z, df)
# or maybe
xyplot(x ~y|z, df)
How do I get the value of text input field using JavaScript?
You can read value by
searchTxt.value
_x000D_
_x000D_
function searchURL() {
let txt = searchTxt.value;
console.log(txt);
// window.location = "http://www.myurl.com/search/" + txt; ...
}
document.querySelector('.search').addEventListener("click", ()=>searchURL());
_x000D_
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
<button class="search">Search</button>
_x000D_
_x000D_
_x000D_
UPDATE
I see many downvotes but any comments - however (for future readers) actually this solution works
How do I create a Linked List Data Structure in Java?
The obvious solution to developers familiar to Java is to use the LinkedList class already provided in java.util. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. Enhancements to this implementation include making it a double-linked list, adding methods to insert and delete from the middle or end, and by adding get and sort methods as well.
Note: In the example, the Link object doesn't actually contain another Link object - nextLink is actually only a reference to another link.
class Link {
public int data1;
public double data2;
public Link nextLink;
//Link constructor
public Link(int d1, double d2) {
data1 = d1;
data2 = d2;
}
//Print Link data
public void printLink() {
System.out.print("{" + data1 + ", " + data2 + "} ");
}
}
class LinkList {
private Link first;
//LinkList constructor
public LinkList() {
first = null;
}
//Returns true if list is empty
public boolean isEmpty() {
return first == null;
}
//Inserts a new Link at the first of the list
public void insert(int d1, double d2) {
Link link = new Link(d1, d2);
link.nextLink = first;
first = link;
}
//Deletes the link at the first of the list
public Link delete() {
Link temp = first;
if(first == null){
return null;
//throw new NoSuchElementException(); // this is the better way.
}
first = first.nextLink;
return temp;
}
//Prints list data
public void printList() {
Link currentLink = first;
System.out.print("List: ");
while(currentLink != null) {
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
class LinkListTest {
public static void main(String[] args) {
LinkList list = new LinkList();
list.insert(1, 1.01);
list.insert(2, 2.02);
list.insert(3, 3.03);
list.insert(4, 4.04);
list.insert(5, 5.05);
list.printList();
while(!list.isEmpty()) {
Link deletedLink = list.delete();
System.out.print("deleted: ");
deletedLink.printLink();
System.out.println("");
}
list.printList();
}
}
The remote host closed the connection. The error code is 0x800704CD
I was getting this on an asp.net 2.0 iis7 Windows2008 site. Same code on iis6 worked fine. It was causing an issue for me because it was messing up the login process. User would login and get a 302 to default.asxp, which would get through page_load, but not as far as pre-render before iis7 would send a 302 back to login.aspx without the auth cookie. I started playing with app pool settings, and for some reason 'enable 32 bit applications' seems to have fixed it. No idea why, since this site isn't doing anything special that should require any 32 bit drivers. We have some sites that still use Access that require 32bit, but not our straight SQL sites like this one.
Resizing an Image without losing any quality
private static Image resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
Python Pandas - Missing required dependencies ['numpy'] 1
Uninstall all pip packages that you're having problems with. Manually remove all site-packages files. If you're using MacPorts, sudo port clean .
Then try reinstalling. Sometimes, there are files that should have been removed, but weren't if the installation was abruptly interrupted or something.
There could be an issue with conflicting versions of the package(s), as well as potentially issues with Pathing. Are you sure you've set the correct Path for your binaries? (/opt/local/bin, /anaconda2/bin, etc.)
Another issue could be some PYTHONPATH that's explicitly looking in the wrong place for the file.
How can I convert a Unix timestamp to DateTime and vice versa?
Written a simplest extension that works for us. If anyone looks for it...
public static class DateTimeExtensions
{
public static DateTime FromUnixTimeStampToDateTime(this string unixTimeStamp)
{
return DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimeStamp)).UtcDateTime;
}
}
How to stick text to the bottom of the page?
An old thread, but...Answer of Konerak works, but why would you even set size of a container by default. What I prefer is to use code wherever no matter of hog big page size is. So this my code:
<style>
#container {
position: relative;
height: 100%;
}
#footer {
position: absolute;
bottom: 0;
}
</style>
</HEAD>
<BODY>
<div id="container">
<h1>Some heading</h1>
<p>Some text you have</p>
<br>
<br>
<div id="footer"><p>Rights reserved</p></div>
</div>
</BODY>
</HTML>
The trick is in <br>
where you break new line. So, when page is small you'll see footer at bottom of page, as you want.
BUT, when a page is big SO THAT YOU MUST SCROLL IT DOWN, then your footer is going to be 2 new lines under the whole content above. And If you will then make page bigger, your footer is allways going to go DOWN. I hope somebody will find this useful.
NVIDIA NVML Driver/library version mismatch
reboot.
If the problem still exist:
sudo rmmod nvidia_drm
sudo rmmod nvidia_modeset
sudo rmmod nvidia
nvidia-smi
for cent/rhel
cd /boot
mv initramfs-$(uname -r).img /boot/initramfs-$(uname -r).img.bak
dracut -vf initramfs-$(uname -r).img $(uname -r)
then
reboot
for debian/ubuntu
update-initramfs -u
if problem exist persist
apt install -y dkms && dkms install -m nvidia -v 440.82
Change 440.82 to your actual version.
tip: get the Nvidia driver version:
ls /usr/src
you will find the Nvidia driver dir such as nvidia-440.82
also you can remove all Nvidia pkg and reinstall driver again
apt purge nvidia*
apt purge *cuda*
#check
apt list -i |grep nvidia
apt list -i |grep cuda
jQuery Form Validation before Ajax submit
first you don't need to add the classRules
explicitly since required
is automatically detected by the jquery.validate plugin.
so you can use this code :
- on form submit , you prevent the default behavior
- if the form is Invalid stop the execution.
- else if valid send the ajax request.
$('#form').submit(function (e) {
e.preventDefault();
var $form = $(this);
// check if the input is valid using a 'valid' property
if (!$form.valid) return false;
$.ajax({
type: 'POST',
url: 'add.php',
data: $('#form').serialize(),
success: function (response) {
$('#answers').html(response);
},
});
});
How to use a WSDL
Use WSDL.EXE utility to generate a Web Service proxy from WSDL.
You'll get a long C# source file that contains a class that looks like this:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
...
}
In your client-side, Web-service-consuming code:
- instantiate MyService.
- set its Url property
- invoke Web methods
Target elements with multiple classes, within one rule
Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.
The following:
.blue-border, .background {
border: 1px solid #00f;
background: #fff;
}
is for when you want to add styles to elements that have either the blue-border or background class, for example:
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
would all get a blue border and white background applied to them.
However, the accepted answer is different.
.blue-border.background {
border: 1px solid #00f;
background: #fff;
}
This applies the styles to elements that have both classes so in this example only the <div>
with both classes should get the styles applied (in browsers that interpret the CSS properly):
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.
Using Mockito to test abstract classes
Assuming your test classes are in the same package (under a different source root) as your classes under test you can simply create the mock:
YourClass yourObject = mock(YourClass.class);
and call the methods you want to test just as you would any other method.
You need to provide expectations for each method that is called with the expectation on any concrete methods calling the super method - not sure how you'd do that with Mockito, but I believe it's possible with EasyMock.
All this is doing is creating a concrete instance of YouClass
and saving you the effort of providing empty implementations of each abstract method.
As an aside, I often find it useful to implement the abstract class in my test, where it serves as an example implementation that I test via its public interface, although this does depend on the functionality provided by the abstract class.
Install specific branch from github using Npm
There are extra square brackets in the command you tried.
To install the latest version from the v1
branch, you can use:
npm install git://github.com/shakacode/bootstrap-loader.git#v1 --save
Message: Trying to access array offset on value of type null
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
Determine whether a Access checkbox is checked or not
Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.
In Access, there are two types:
2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.
3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.
Minor quibble with the answers:
There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:
?Me!MyCheckBox.Value
?Me!MyCheckBox
The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:
If Me!MyCheckBox Then
...write one of these options:
If (Me!MyCheckBox) Then ' forces evaluation of the control
If Me!MyCheckBox = True Then
If (Me!MyCheckBox = True) Then
If (Me!MyCheckBox = Not False) Then
Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.
Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.
How to convert array values to lowercase in PHP?
use array_map()
:
$yourArray = array_map('strtolower', $yourArray);
In case you need to lowercase nested array (by Yahya Uddin):
$yourArray = array_map('nestedLowercase', $yourArray);
function nestedLowercase($value) {
if (is_array($value)) {
return array_map('nestedLowercase', $value);
}
return strtolower($value);
}
Undo git pull, how to bring repos to old state
If you have gitk (try running "gitk --all from your git command line"), it's simple. Just run it, select the commit you want to rollback to (right-click), and select "Reset master branch to here". If you have no uncommited changes, chose the "hard" option.
Check if year is leap year in javascript
My Code Is Very Easy To Understand
var year = 2015;
var LeapYear = year % 4;
if (LeapYear==0) {
alert("This is Leap Year");
} else {
alert("This is not leap year");
}
Batchfile to create backup and rename with timestamp
Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.
You can also run your batch script through a vbs script like this:
'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True
This will execute your batch file with no cmd window shown.
CSS selector last row from main table
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
Alternative solution
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
Convert DataFrame column type from string to datetime, dd/mm/yyyy format
If your date column is a string of the format '2017-01-01'
you can use pandas astype to convert it to datetime.
df['date'] = df['date'].astype('datetime64[ns]')
or use datetime64[D] if you want Day precision and not nanoseconds
print(type(df_launath['date'].iloc[0]))
yields
<class 'pandas._libs.tslib.Timestamp'>
the same as when you use pandas.to_datetime
You can try it with other formats then '%Y-%m-%d' but at least this works.
Getting permission denied (public key) on gitlab
Go to the terminal and regenerate the ssh key again. Type ssh-keygen
. It will ask you where you want to save it, type the path.
Then copy the public key to gitlabs platform. It usually starts with ssh-rsa.