Open an administrator command prompt, and do this command:
fsutil fsinfo ntfsinfo [your drive]
The Bytes Per Cluster is the equivalent of the allocation unit.
Some time it's very helpful to execute eclipse from command line with "-clean" parameter to enforce it produce clean up for workspace.
You just need to add a /A
behind the line.
Example:
get-childitem C:\temp\ -exclude *.svn-base,".svn" -recurse | foreach ($_) {remove-item $_.fullname} /a
I would set up a shortcut, either to CMD or to the thing you want to run, then set the properties of the shortcut to require admin, and then run the shortcut from your batch file. I haven't tested to confirm it will respect the properties, but I think it's more elegant and doesn't require activating the Administrator account.
Also if you do it as a scheduled task (which can be set up from code) there is an option to run it elevated there.
The accepted answer gave two locations:
here
C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache
and possibly here
C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache
Did you try those?
Edited to add
On my Windows Vista machine, it's located in
%Temp%\VWDWebCache
and in
%LocalAppData%\Microsoft\WebsiteCache
From your additional information (regarding team edition) this comes from Clear Client TFS Cache:
Clear Client TFS Cache
Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.
To solve it..
For Windows Vista delete contents of this folder
%LocalAppData%\Microsoft\Team Foundation\1.0\Cache
I've modified Foxidrive's answer to copy entire folders and all their contents. this script will create a folder and backup another folder's contents into it, including any subfolders underneath.
If you put this in say an hourly scheduled task you need to be careful as you could fill up your drive quickly with copies of your original folder. Before bitbucket etc i was using as similar script to save my code offline.
@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=YourPrefixHere_%YYYY%%MM%%DD%@%HH%%Min%
rem you could for example want to create a folder in Gdrive and save backup there
cd C:\YourGoogleDriveFolder
mkdir %stamp%
cd %stamp%
xcopy C:\FolderWithDataToBackup\*.* /s
Try this:
Process.Start("Location Of File.exe");
(Make sure you use the System.Diagnostics library)
On Linux, I often use curl with the --head parameter. It is available for several operating systems, including Windows.
[edit] related to the answer below, gknw.net is currently down as of February 23 2012. Check curl.haxx.se for updated info.
Actually it is 256, see File System Functionality Comparison, Limits.
To repeat a post on http://fixunix.com/microsoft-windows/30758-windows-xp-file-name-length-limit.html
"Assuming we're talking about NTFS and not FAT32, the "255 characters for path+file" is a limitation of Explorer, not the filesystem itself. NTFS supports paths up to 32,000 Unicode characters long, with each component up to 255 characters.
Explorer -and the Windows API- limits you to 260 characters for the path, which include drive letter, colon, separating slashes and a terminating null character. It's possible to read a longer path in Windows if you start it with a
\\
"
If you read the above posts you'll see there is a 5th thing you can be certain of: Finding at least one obstinate computer user!
As of 2017, an easy method to achieve this is the following:
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
# Code of your program here
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
If you are using Python 2.x, then you should replace the last line for:
ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1)
Also note that if you converted you python script into an executable file (using tools like py2exe
, cx_freeze
, pyinstaller
) then you should use sys.argv[1:]
instead of sys.argv
in the fourth parameter.
Some of the advantages here are:
ctypes
and sys
from standard library.Documentation for the underlying ShellExecute call is here.
Service
extends ContextWrapper
which extends Context
. Hence the Service
is a Context
.
Use 'this'
keyword in the service.
I had similar situation and here is my approach which is somewhat different:
HADOOP_USER_NAME=hdfs hdfs dfs -put /root/MyHadoop/file1.txt /
What you actually do is you read local file in accordance to your local permissions but when placing file on HDFS you are authenticated like user hdfs
. You can do this with other ID (beware of real auth schemes configuration but this is usually not a case).
Advantages:
sudo
.We can use case statement Like this
select Name,EmailId,gender=case
when gender='M' then 'F'
when gender='F' then 'M'
end
from [dbo].[Employees]
WE can also it as follow.
select Name,EmailId,case gender
when 'M' then 'F'
when 'F' then 'M'
end
from [dbo].[Employees]
There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0
tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.
The closest link I could find to be useful for more information is this
Quote from above link:
What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.
From the Documentation for GetEXitCodeThread
Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.
My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.
If you use ==
, php treats an empty string or array as null
. To make the distinction between null
and empty
, either use ===
or is_null
. So:
if($a === NULL)
or if(is_null($a))
The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:
%SystemRoot%'SYSVOL'sysvol''scripts
It can presumably be changes from this default but I've never met anyone that had a reason to.
To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx
Unique is a keyword used in the Create Table() directive to denote that a field will contain unique data, usually used for natural keys, foreign keys etc.
For example:
Create Table Employee(
Emp_PKey Int Identity(1, 1) Constraint PK_Employee_Emp_PKey Primary Key,
Emp_SSN Numeric Not Null Unique,
Emp_FName varchar(16),
Emp_LName varchar(16)
)
i.e. Someone's Social Security Number would likely be a unique field in your table, but not necessarily the primary key.
Distinct is used in the Select statement to notify the query that you only want the unique items returned when a field holds data that may not be unique.
Select Distinct Emp_LName
From Employee
You may have many employees with the same last name, but you only want each different last name.
Obviously if the field you are querying holds unique data, then the Distinct keyword becomes superfluous.
If you want to send data with form serialize you may try this
var form= $("#formId");
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()+"&variable="+otherData,
success: function (data) {
var result=data;
$('#result').attr("value",result);
}
});
Build solution only builds those projects which have changed in the solution, and does not effect assemblies that have not changed,
ReBuild first cleans, all the assemblies from the solution and then builds entire solution regardless of changes done.
Clean, simply cleans the solution.
If you encode the & in your URL to %26 it works correctly. Just tested and verified.
Here is the best tutorial I found over there:
http://www.w3schools.com/php/filter_validate_url.asp
<?php
$url = "http://www.qbaki.com";
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
// Validate url
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
Possible flags:
FILTER_FLAG_SCHEME_REQUIRED - URL must be RFC compliant (like http://example)
FILTER_FLAG_HOST_REQUIRED - URL must include host name (like http://www.example.com)
FILTER_FLAG_PATH_REQUIRED - URL must have a path after the domain name (like www.example.com/example1/)
FILTER_FLAG_QUERY_REQUIRED - URL must have a query string (like "example.php?name=Peter&age=37")
Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial
The MDN Documentation is very eloquent and features examples.
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
Alternatively, you can just do:
import matplotlib as mpl
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size
The answers above me got me tempted so much, that I decided to dry run all the possible combinations with OS, Eclipse and JVM trio. Anyway, whoever is digging down and reading my post, check the following as a hot spot (I am Windows 7 user).
You understand Program Files and Program File (x86) are two different folders... x86 stands for the 32-bit version of programs and the former is the 64-bit version.
If you have multiple versions of Java installed with different bitness and release versions, which is bound to happen with so many open source IDEs, managers, administrative consoles, the best option is to set the VM argument directly in the eclipse.ini
file. If you don't, Eclipse will go crazy and try searching itself which is not good.
Your code is OK. Note though that if you return a pointer to an array, and that array goes out of scope, you should not use that pointer anymore. Example:
int* test (void)
{
int out[5];
return out;
}
The above will never work, because out
does not exist anymore when test()
returns. The returned pointer must not be used anymore. If you do use it, you will be reading/writing to memory you shouldn't.
In your original code, the arr
array goes out of scope when main()
returns. Obviously that's no problem, since returning from main()
also means that your program is terminating.
If you want something that will stick around and cannot go out of scope, you should allocate it with new
:
int* test (void)
{
int* out = new int[5];
return out;
}
The returned pointer will always be valid. Remember do delete it again when you're done with it though, using delete[]
:
int* array = test();
// ...
// Done with the array.
delete[] array;
Deleting it is the only way to reclaim the memory it uses.
Same with something more complex...getting the ec2 instance region from within the instance.
INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")
echo $INSTANCE_REGION
window.location = document.getElementById('myAnchor').href
I just discovered Telerik has some great components, including Grid, and they are open source too. http://demos.telerik.com/aspnet-mvc/
var temp = "This is a string.";_x000D_
console.log((temp.match(new RegExp("is", "g")) || []).length);
_x000D_
If you're assembling the HTML in Java, you can use this nice utility class from Apache commons-lang to do all the escaping correctly:
org.apache.commons.lang.StringEscapeUtils
Escapes and unescapes Strings for Java, Java Script, HTML, XML, and SQL.
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:
<T extends ClassA & InterfaceB>
See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName
for each one that you need.
This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max
, which (wrapped onto two lines) is:
public static <T extends Object & Comparable<? super T>> T
max(Collection<? extends T> coll)
why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.
It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:
class classB { }
interface interfaceC { }
public class MyClass<T extends classB & interfaceC> {
Class<T> variable;
}
to get variable
that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>
, the class name must come first, and interfaces follow. And of course you can only list a single class.
//where [1] - column number which you want to make text
ExcelWorksheet.Columns[1].NumberFormat = "@";
//If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes.
//path were excel file is kept
string ResultsFilePath = @"C:\\Users\\krakhil\\Desktop\\TGUW EXCEL\\TEST";
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath);
ExcelApp.Visible = true;
//Looping through all available sheets
foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
{
//Selecting the worksheet where we want to perform action
ExcelWorksheet.Select(Type.Missing);
ExcelWorksheet.Columns[1].NumberFormat = "@";
}
//saving excel file using Interop
ExcelWorkbook.Save();
//closing file and releasing resources
ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(ExcelWorkbook);
ExcelApp.Quit();
Marshal.FinalReleaseComObject(ExcelApp);
The reason your functor example does not work is that you need an instance to invoke the operator()
.
I didn't see an answer that's clean and suitable for production-ready software, so here it goes:
/*
* Get current error_reporting value,
* so that we don't lose preferences set in php.ini and .htaccess
* and accidently reenable message types disabled in those.
*
* If you want to disable e.g. E_STRICT on a global level,
* use php.ini (or .htaccess for folder-level)
*/
$old_error_reporting = error_reporting();
/*
* Disable E_STRICT on top of current error_reporting.
*
* Note: do NOT use ^ for disabling error message types,
* as ^ will re-ENABLE the message type if it happens to be disabled already!
*/
error_reporting($old_error_reporting & ~E_STRICT);
// code that should not emit E_STRICT messages goes here
/*
* Optional, depending on if/what code comes after.
* Restore old settings.
*/
error_reporting($old_error_reporting);
What's wrong with this 1 simple line?
new LocalDateTime(new Date().getTime()).toLocalDate();
I had this issue with offline mode enable. I disabled offline mode and synced.
File > Settings
.Build, Execution, Deployment > Gradle
.Offline work
.This works for me every time:
if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
//THEN CLICK ON THE SUBMIT BUTTON
}else{
//DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
}
In your code, jQuery just looks for the first instance of an input with name q12_3
, which in this case has a value of 1
. You want an input with name q12_3
that is :checked
.
$("#submit").click(() => {_x000D_
const val = $('input[name=q12_3]:checked').val();_x000D_
alert(val);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>Sales Promotion</td>_x000D_
<td><input type="radio" name="q12_3" value="1">1</td>_x000D_
<td><input type="radio" name="q12_3" value="2">2</td>_x000D_
<td><input type="radio" name="q12_3" value="3">3</td>_x000D_
<td><input type="radio" name="q12_3" value="4">4</td>_x000D_
<td><input type="radio" name="q12_3" value="5">5</td>_x000D_
</tr>_x000D_
</table>_x000D_
<button id="submit">submit</button>
_x000D_
Note that the above code is not the same as using .is(":checked")
. jQuery's is()
function returns a boolean (true or false) and not (an) element(s).
Because this answer keeps getting a lot of attention, I'll also include a vanilla JavaScript snippet.
document.querySelector("#submit").addEventListener("click", () => {_x000D_
const val = document.querySelector("input[name=q12_3]:checked").value;_x000D_
alert(val);_x000D_
});
_x000D_
<table>_x000D_
<tr>_x000D_
<td>Sales Promotion</td>_x000D_
<td><input type="radio" name="q12_3" value="1">1</td>_x000D_
<td><input type="radio" name="q12_3" value="2">2</td>_x000D_
<td><input type="radio" name="q12_3" value="3">3</td>_x000D_
<td><input type="radio" name="q12_3" value="4">4</td>_x000D_
<td><input type="radio" name="q12_3" value="5">5</td>_x000D_
</tr>_x000D_
</table>_x000D_
<button id="submit">submit</button>
_x000D_
Try the new Text Encoding API:
// create an array view of some valid bytes_x000D_
let bytesView = new Uint8Array([104, 101, 108, 108, 111]);_x000D_
_x000D_
console.log(bytesView);_x000D_
_x000D_
// convert bytes to string_x000D_
// encoding can be specfied, defaults to utf-8 which is ascii._x000D_
let str = new TextDecoder().decode(bytesView); _x000D_
_x000D_
console.log(str);_x000D_
_x000D_
// convert string to bytes_x000D_
// encoding can be specfied, defaults to utf-8 which is ascii._x000D_
let bytes2 = new TextEncoder().encode(str);_x000D_
_x000D_
// look, they're the same!_x000D_
console.log(bytes2);_x000D_
console.log(bytesView);
_x000D_
Cross-platform, true three-way merges and it's completely free for commercial or personal usage.
In TS we can type functions in the in the following manners:
Functions types/signatures
This is used for real implementations of functions/methods it has the following syntax:
(arg1: Arg1type, arg2: Arg2type) : ReturnType
Example:
function add(x: number, y: number): number {
return x + y;
}
class Date {
setTime(time: number): number {
// ...
}
}
Function Type Literals
Function type literals are another way to declare the type of a function. They're usually applied in the function signature of a higher-order function. A higher-order function is a function which accepts functions as parameters or which returns a function. It has the following syntax:
(arg1: Arg1type, arg2: Arg2type) => ReturnType
Example:
type FunctionType1 = (x: string, y: number) => number;
class Foo {
save(callback: (str: string) => void) {
// ...
}
doStuff(callback: FunctionType1) {
// ...
}
}
Why does it have to be so complicated?
#include <windows.h>
int main(int argc, char** argv) // argv[0] = C:\dev\test.exe
{
char *p = strrchr(argv[0], '\\');
if(p) p[0] = 0;
printf(argv[0]); // argv[0] = C:\dev
}
You can submit form by just clicking on checkbox by simple method in JavaScript. Inside form tag or Input attribute add following attribute:
onchange="this.form.submit()"
Example:
<form>
<div>
<input type="checkbox">
</div>
</form>
There doesn't seem to be a static valueOf
method for this, which is a bit surprising.
One rather ugly, but simple, way, would be to iterate over Locale.getAvailableLocales()
, comparing their toString
values with your value.
Not very nice, but no string parsing required. You could pre-populate a Map
of Strings to Locales, and look up your database string in that Map.
According to http://api.jquery.com/jquery.ajax/
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Do you want the first and last name of the row with the largest id?
If so (and you were missing a FROM clause):
SELECT firstname, lastname, id
FROM foo
ORDER BY id DESC
LIMIT 1;
Did they add a runtime List<> and/or Map<> type class to typepad 1.0
No, providing a runtime is not the focus of the TypeScript team.
is there a solid library out there someone wrote that provides this functionality?
I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections
JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts
: https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want
CAST both fields to datatype DATE and you can use a minus:
(CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
Test case:
SELECT (CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
FROM
generate_series('2014-01-01'::timestamp, '2014-02-01'::timestamp, interval '1 hour') g(joindate);
Result: 31
Or create a function datediff():
CREATE OR REPLACE FUNCTION datediff(timestamp, timestamp)
RETURNS int
LANGUAGE sql
AS
$$
SELECT CAST($1 AS date) - CAST($2 AS date) as DateDifference
$$;
I just wrote a script that lets you achieve this. It gives you two global functions: hasEvent(Node elm, String event)
and getEvents(Node elm)
which you can utilize. Be aware that it modifies the EventTarget
prototype method add/RemoveEventListener
, and does not work for events added through HTML markup or javascript syntax of elm.on_event = ...
Script:
var hasEvent,getEvents;!function(){function b(a,b,c){c?a.dataset.events+=","+b:a.dataset.events=a.dataset.events.replace(new RegExp(b),"")}function c(a,c){var d=EventTarget.prototype[a+"EventListener"];return function(a,e,f,g,h){this.dataset.events||(this.dataset.events="");var i=hasEvent(this,a);return c&&i||!c&&!i?(h&&h(),!1):(d.call(this,a,e,f),b(this,a,c),g&&g(),!0)}}hasEvent=function(a,b){var c=a.dataset.events;return c?new RegExp(b).test(c):!1},getEvents=function(a){return a.dataset.events.replace(/(^,+)|(,+$)/g,"").split(",").filter(function(a){return""!==a})},EventTarget.prototype.addEventListener=c("add",!0),EventTarget.prototype.removeEventListener=c("remove",!1)}();
How about .delay()
?
$("#test").animate({"top":"-=80px"},1500)
.delay(1000)
.animate({"opacity":"0"},500);
In this case, ' is not a comment character. It's used to delimit string literals. The comic artist is banking on the idea that the school in question has dynamic sql somewhere that looks something like this:
$sql = "INSERT INTO `Students` (FirstName, LastName) VALUES ('" . $fname . "', '" . $lname . "')";
So now the ' character ends the string literal before the programmer was expecting it. Combined with the ; character to end the statement, an attacker can now add whatever sql they want. The -- comment at the end is to make sure any remaining sql in the original statement does not prevent the query from compiling on the server.
FWIW, I also think the comic in question has an important detail wrong: if you're thinking about sanitizing your database inputs, as the comic suggests, you're still doing it wrong. Instead, you should think in terms of quarantining your database inputs, and the correct way to do this is via parameterized queries.
j[0];
dereferences a pointer to int
, so its type is int
.
(*j)[0]
has no type. *j
dereferences a pointer to an int
, so it returns an int
, and (*j)[0]
attempts to dereference an int
. It's like attempting int x = 8; x[0];
.
Some people try to fix it using one way, some the second. Basically, there are 2 issues, which if you check them out & solve both - in 99% it should fix this issue:
Old device simulators located at YOUR_MAC_NAME
(e.g. Macintosh
) -> Users
-> YOUR_USERNAME
(daniel
) -> Library
-> Developer
-> Xcode
-> iOS Device Support
. Leave there, the newest one, as of today this is 13.2.3 (17B111)
, but in future it'll change. The highest number (here 13.2.3
) of the iOS version indicates that it's newer.
After this list your devices in Terminal
by running xcrun simctl list devices
. Many of them might be unavailable
, therefore delete them by running xcrun simctl delete unavailable
. It'll free some space as well. To be sure that everything is fine check it again by running xcrun simctl list devices
. You should see devices only from the newest version (here 13.2.3
) like the screenshot below shows.
As a bonus which is slightly less relevant to this question, but still free's some space. Go to YOUR_MAC_NAME
(e.g. Macintosh
) -> Users
-> YOUR_USERNAME
(e.g. daniel
) -> Library
-> Developer
-> Xcode
-> Archives
. You'll see many archived deployed application, most probably you don't need all of them. Try to delete these ones, which are not being used anymore.
Using these 2 methods and the bonus method I was able to get extra 15 GB of space on my Mac.
PS. Simply deleting simulators from Xcode by going to Xcode
-> Window
-> Devices and Simulators
-> Simulators
(or simply CMD
+ SHIFT
+ 2
when using keyboard shortcut) and deleting it there won't help. You really need to go for the described steps.
Leaving aside the fact that they are private
, since a
and b
are members of A
, they are meant to be initialized by A
's constructors, not by some other class's constructors (derived or not).
Try:
class A
{
int a, b;
protected: // or public:
A(int a, int b): a(a), b(b) {}
};
class B : public A
{
B() : A(0, 0) {}
};
A natural join is just a shortcut to avoid typing, with a presumption that the join is simple and matches fields of the same name.
SELECT
*
FROM
table1
NATURAL JOIN
table2
-- implicitly uses `room_number` to join
Is the same as...
SELECT
*
FROM
table1
INNER JOIN
table2
ON table1.room_number = table2.room_number
What you can't do with the shortcut format, however, is more complex joins...
SELECT
*
FROM
table1
INNER JOIN
table2
ON (table1.room_number = table2.room_number)
OR (table1.room_number IS NULL AND table2.room_number IS NULL)
Use the formatting operator %
:
buf = "A = %d\n , B= %s\n" % (a, b)
print >>f, buf
You are not passing the variable correctly. One fast solution is to make a global variable like this:
var global_json_data;
$(document).ready(function() {
var json_source = "https://spreadsheets.google.com/feeds/list/0ApL1zT2P00q5dG1wOUMzSlNVV3VRV2pwQ2Fnbmt3M0E/od7/public/basic?alt=json";
var string_data ="";
var json_data = $.ajax({
dataType: 'json', // Return JSON
url: json_source,
success: function(data){
var data_obj = [];
for (i=0; i<data.feed.entry.length; i++){
var el = {'key': data.feed.entry[i].title['$t'], 'value': '<p><a href="'+data.feed.entry[i].content['$t']+'>'+data.feed.entry[i].title['$t']+'</a></p>'};
data_obj.push(el)};
console.log("data grabbed");
global_json_data = data_obj;
return data_obj;
},
error: function(jqXHR, textStatus, errorThrown){
$('#results_box').html('<h2>Something went wrong!</h2><p><b>' + textStatus + '</b> ' + errorThrown + '</p>');
}
});
$(':submit').click(function(event){
var json_data = global_json_data;
event.preventDefault();
console.log(json_data.length);
//function
if ($('#place').val() !=''){
var copy_string = $('#place').val();
var converted_string = copy_string;
for (i=0; i<json_data.length; i++){
//console_log(data.feed.entry[i].title['$t']);
converted_string = converted_string.replace(json_data.feed.entry[i].title['$t'],
'<a href="'+json_data.feed.entry[i].content['$t']+'>'+json_data.feed.entry[i].title['$t']+'</a>');
}
$('#results_box').text(converted_string).html();
}
});
});//document ready end
The include_path setting works like $PATH in unix (there is a similar setting in Windows too).It contains multiple directory names, seperated by colons (:). When you include or require a file, these directories are searched in order, until a match is found or all directories are searched.
So, to make sure that your application always includes from your path if the file exists there, simply put your include dir first in the list of directories.
ini_set("include_path", "/your_include_path:".ini_get("include_path"));
This way, your include directory is searched first, and then the original search path (by default the current directory, and then PEAR). If you have no problem modifying include_path, then this is the solution for you.
Using Lambda expressions:
If we don't have a specific class to bind the result:
var stores = context.Stores.Select(x => new { x.id, x.name, x.city }).ToList();
If we have a specific class then we need to bind the result with it:
List<SelectListItem> stores = context.Stores.Select(x => new SelectListItem { Id = x.id, Name = x.name, City = x.city }).ToList();
Using simple LINQ expressions:
If we don't have a specific class to bind the result:
var stores = (from a in context.Stores select new { x.id, x.name, x.city }).ToList();
If we have a specific class then we need to bind the result with it:
List<SelectListItem> stores = (from a in context.Stores select new SelectListItem{ Id = x.id, Name = x.name, City = x.city }).ToList();
I know there is an approved answer already, but I kinda like this JSON approach.
npm start '{"PROJECT_NAME_STR":"my amazing stuff", "CRAZY_ARR":[0,7,"hungry"], "MAGICAL_NUMBER_INT": 42, "THING_BOO":true}';
Usually I have like 1 var I need, such as a project name, so I find this quick n' simple.
Also I often have something like this in my package.json
"scripts": {
"start": "NODE_ENV=development node local.js"
}
And being greedy I want "all of it", NODE_ENV and the CMD line arg stuff.
You simply access these things like so in your file (in my case local.js)
console.log(process.env.NODE_ENV, starter_obj.CRAZY_ARR, starter_obj.PROJECT_NAME_STR, starter_obj.MAGICAL_NUMBER_INT, starter_obj.THING_BOO);
You just need to have this bit above it (I'm running v10.16.0 btw)
var starter_obj = JSON.parse(JSON.parse(process.env.npm_config_argv).remain[0]);
Anyhoo, question already answered. Thought I'd share, as I use this method a lot.
It is not possible in on step or you need to keep the reference to the array. If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
In python 3.x all strings are sequences of Unicode characters. and doing the isinstance check for str (which means unicode string by default) should suffice.
isinstance(x, str)
With regards to python 2.x, Most people seem to be using an if statement that has two checks. one for str and one for unicode.
If you want to check if you have a 'string-like' object all with one statement though, you can do the following:
isinstance(x, basestring)
str.split()
without any arguments splits on runs of whitespace characters:
>>> s = 'I am having a very nice day.'
>>>
>>> len(s.split())
7
From the linked documentation:
If sep is not specified or is
None
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
A callback
is a function passed as an parameter to a Higher Order Function
(wikipedia). A simple implementation of a callback would be:
const func = callback => callback('Hello World!');
To call the function, simple pass another function as argument to the function defined.
func(string => console.log(string));
You can use SELECT
as lambacck said
or add parentheses:
SET @times = (SELECT COUNT(DidWin)as "I Win"
FROM thetable
WHERE DidWin = 1 AND Playername='Me');
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
You can use Newtonsoft library and use it as follows
using Newtonsoft.Json;
public class jb
{
public DateTime Date { set; get; }
public string Artist { set; get; }
public int Year { set; get; }
public string album { set; get; }
}
var jsonObject = new jb();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(jsonObject );
BEST SOLUTION IS:
// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
// ...
// restore index and position
mList.post(new Runnable() {
@Override
public void run() {
mList.setSelectionFromTop(index, top);
}
});
YOU MUST CALL IN POST AND IN THREAD!
Set priority for default python in Linux terminal by adding this:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 1
Here, we set python3
to have priority 10 and python2
to priority 1. This will make python3
the default python. If you want Python2 as default then make a priority of python2 higher then python3
In the client side handle the click event of the button, use the ClientID property to get he id of the button:
$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(
function() {
$.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
// do something with the data
return false;
}
});
});
In your page on the server:
protected void Page_Load(object sender,EventArgs e) {
// check if it is an ajax request
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
if (Request.QueryString["id"]==myButton.ClientID) {
// call the click event handler of the myButton here
Response.End();
}
if (Request.QueryString["id"]==mySecondButton.ClientID) {
// call the click event handler of the mySecondButton here
Response.End();
}
}
}
Try giving
default width, display it with block and center it with margin: 0 auto;
like this:
<p style="display:block; line-height: 70px; width:200px; margin:0 auto;"><button type="submit" class="btn">Confirm</button></p>
You could use the update()
immutability helper from react-addons-update
, which effectively does the same thing under the hood, but what you're doing is fine.
this.setState(prevState => ({
data: update(prevState.data, {$splice: [[index, 1]]})
}))
If you just want to output the first 5 elements, you should write something like:
<?php
if (!empty ( $an_array ) ) {
$min = min ( count ( $an_array ), 5 );
$i = 0;
foreach ($value in $an_array) {
echo $value;
$i++;
if ($i == $min) break;
}
}
?>
If you want to write a function which returns part of the array, you should use array_slice:
<?php
function GetElements( $an_array, $elements ) {
return array_slice( $an_array, 0, $elements );
}
?>
APIs are messy because they keep changing. This pure javascript way worked for me:
<div id="divScope" class="boom-lightbox" style="display: none;">
<iframe id="ytplayer" width="720" height="405" src="https://www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen> </iframe>
</div>
//if I want i can set scope to a specific region
var myScope = document.getElementById('divScope');
//otherwise set scope as the entire document
//var myScope = document;
//if there is an iframe inside maybe embedded multimedia video/audio, we should reload so it stops playing
var iframes = myScope.getElementsByTagName("iframe");
if (iframes != null) {
for (var i = 0; i < iframes.length; i++) {
iframes[i].src = iframes[i].src; //causes a reload so it stops playing, music, video, etc.
}
}
Note : Use it if calculating / adding days from current date.
Be aware: this answer has issues (see comments)
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
It should be like
var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:
>>> df[condition]
This will return a slice of your dataframe which you can index using iloc
. Here are your examples:
Get first row where A > 3 (returns row 2)
>>> df[df.A > 3].iloc[0]
A 4
B 6
C 3
Name: 2, dtype: int64
If what you actually want is the row number, rather than using iloc
, it would be df[df.A > 3].index[0]
.
Get first row where A > 4 AND B > 3:
>>> df[(df.A > 4) & (df.B > 3)].iloc[0]
A 5
B 4
C 5
Name: 4, dtype: int64
Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)
>>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
A 4
B 6
C 3
Name: 2, dtype: int64
Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:
>>> def series_or_default(X, condition, default_col, ascending=False):
... sliced = X[condition]
... if sliced.shape[0] == 0:
... return X.sort_values(default_col, ascending=ascending).iloc[0]
... return sliced.iloc[0]
>>>
>>> series_or_default(df, df.A > 6, 'A')
A 5
B 4
C 5
Name: 4, dtype: int64
As expected, it returns row 4.
As the compiler says, grid
was not declared in the scope of your function :) "Scope" basically means a set of curly braces. Every variable is limited to the scope in which it is declared (it cannot be accessed outside that scope). In your case, you're declaring the grid
variable in your main()
function and trying to use it in nonrecursivecountcells()
. You seem to be passing it as the argument colors
however, so I suggest you just rename your uses of grid
in nonrecursivecountcells()
to colors
. I think there may be something wrong with trying to pass the array that way, too, so you should probably investigate passing it as a pointer (unless someone else says something to the contrary).
DEFAULT
is the value that will be inserted in the absence of an explicit value in an insert / update statement. Lets assume, your DDL did not have the NOT NULL
constraint:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT 'MyDefault'
Then you could issue these statements
-- 1. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B) VALUES (NULL, NULL);
-- 2. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, DEFAULT);
-- 3. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) DEFAULT VALUES;
-- 4. This will insert NULL into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, NULL);
Alternatively, you can also use DEFAULT
in UPDATE
statements, according to the SQL-1992 standard:
-- 5. This will update 'MyDefault' into tbl.col
UPDATE tbl SET col = DEFAULT;
-- 6. This will update NULL into tbl.col
UPDATE tbl SET col = NULL;
Note, not all databases support all of these SQL standard syntaxes. Adding the NOT NULL
constraint will cause an error with statements 4, 6
, while 1-3, 5
are still valid statements. So to answer your question: No, they're not redundant.
There's a different solution to this error if you're using ASP.NET MVC:
C# sample:
[HttpPost, ValidateInput(false)]
public ActionResult Edit(FormCollection collection)
{
// ...
}
Visual Basic sample:
<AcceptVerbs(HttpVerbs.Post), ValidateInput(False)> _
Function Edit(ByVal collection As FormCollection) As ActionResult
...
End Function
All three way you can use for newline character :
'\n'
"\n"
"""\n"""
I know there are a lot of answers, but another solution could be to go with decorators. This is an example to repeat a function everyday at a specific time. The cool think about using this way is that you only need to add the Syntactic Sugar to the function you want to schedule:
@repeatEveryDay(hour=6, minutes=30)
def sayHello(name):
print(f"Hello {name}")
sayHello("Bob") # Now this function will be invoked every day at 6.30 a.m
And the decorator will look like:
def repeatEveryDay(hour, minutes=0, seconds=0):
"""
Decorator that will run the decorated function everyday at that hour, minutes and seconds.
:param hour: 0-24
:param minutes: 0-60 (Optional)
:param seconds: 0-60 (Optional)
"""
def decoratorRepeat(func):
@functools.wraps(func)
def wrapperRepeat(*args, **kwargs):
def getLocalTime():
return datetime.datetime.fromtimestamp(time.mktime(time.localtime()))
# Get the datetime of the first function call
td = datetime.timedelta(seconds=15)
if wrapperRepeat.nextSent == None:
now = getLocalTime()
wrapperRepeat.nextSent = datetime.datetime(now.year, now.month, now.day, hour, minutes, seconds)
if wrapperRepeat.nextSent < now:
wrapperRepeat.nextSent += td
# Waiting till next day
while getLocalTime() < wrapperRepeat.nextSent:
time.sleep(1)
# Call the function
func(*args, **kwargs)
# Get the datetime of the next function call
wrapperRepeat.nextSent += td
wrapperRepeat(*args, **kwargs)
wrapperRepeat.nextSent = None
return wrapperRepeat
return decoratorRepeat
I may be doing this a little differently. I'm not sure why I use this syntax, copied it from some book a long time ago. But each of my js files defines a variable. The first file, for no reason at all, is called R:
var R =
{
somevar: 0,
othervar: -1,
init: function() {
...
} // end init function
somefunction: function(somearg) {
...
} // end somefunction
...
}; // end variable R definition
$( window ).load(function() {
R.init();
})
And then if I have a big piece of code that I want to segregate, I put it in a separate file and a different variable name, but I can still reference the R variables and functions. I called the new one TD for no good reason at all:
var TD =
{
xvar: 0,
yvar: -1,
init: function() {
...
} // end init function
sepfunction: function() {
...
R.somefunction(xvar);
...
} // end somefunction
...
}; // end variable TD definition
$( window ).load(function() {
TD.init();
})
You can see that where in the TD 'sepfunction' I call the R.somefunction. I realize this doesn't give any runtime efficiencies because both scripts to need to load, but it does help me keep my code organized.
change this
audio.src='audio/ogg/' + document.getElementById(song1.ogg);
to
audio.src='audio/ogg/' + document.getElementById('song1');
Here is an archived article from Jim Mischel at InformIt that handles sorting for both rectangular and jagged multi-dimensional arrays.
To help people who might search for answer to this same question, it is important to know what type of projects you are using in Studio.
Gradle
The default project type when creating new project, and the recommended one in general is Gradle.
For a new project called "Foo", the structure under the main folder will be
Foo/
settings.gradle
Foo/
build.gradle
build/
Where the internal "Foo" folder is the main module (this structure allows you to create more modules later on in the same structure without changes).
In this setup, the location of the generated APK will be under
Foo/Foo/build/apk/...
Note that each module can generate its own output, so the true output is more
Foo/*/build/apk/...
EDIT On the newest version of the Android Studio location path for generated output is
Foo/*/build/outputs/apk/...
IntelliJ
If you are a user of IntelliJ before switching to Studio, and are importing your IntelliJ project directly, then nothing changed. The location of the output will be the same under:
out/production/...
Note: this is will become deprecated sometimes around 1.0
Eclipse
If you are importing Android Eclipse project directly, do not do this! As soon as you have dependencies in your project (jars or Library Projects), this will not work and your project will not be properly setup. If you have no dependencies, then the apk would be under the same location as you'd find it in Eclipse:
bin/...
However I cannot stress enough the importance of not doing this.
Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.
In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )
I strongly recommend the use of getopt.
If you want help to print out for your options then take a look at GetOptionKit.
Assuming you are on Linux, check if php-fpm is running by searching through the process list:
ps aux | grep php-fpm
If running over IP (as opposed to over Unix socket) then you can also check for the port:
netstat -an | grep :9000
Or using nmap:
nmap localhost -p 9000
Lastly, I've read that you can request the status, but in my experience this has proven unreliable:
/etc/init.d/php5-fpm status
First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.
If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
'do something
End If
End If
select email, count(*) as c FROM orders GROUP BY email
This is my solution using the wrapper, just removing border-collapse
might not be helpful always, because you might want to have borders.
.wrapper {_x000D_
overflow: auto;_x000D_
border-radius: 6px;_x000D_
border: 1px solid red;_x000D_
}_x000D_
_x000D_
table {_x000D_
border-spacing: 0;_x000D_
border-collapse: collapse;_x000D_
border-style: hidden;_x000D_
_x000D_
width:100%;_x000D_
max-width: 100%;_x000D_
}_x000D_
_x000D_
th, td {_x000D_
padding: 10px;_x000D_
border: 1px solid #CCCCCC;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column 1</th>_x000D_
<th>Column 2</th>_x000D_
<th>Column 3</th>_x000D_
</tr>_x000D_
</thead>_x000D_
_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Foo Bar boo</td>_x000D_
<td>Lipsum</td>_x000D_
<td>Beehuum Doh</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Dolor sit</td>_x000D_
<td>ahmad</td>_x000D_
<td>Polymorphism</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Kerbalium</td>_x000D_
<td>Caton, gookame kyak</td>_x000D_
<td>Corona Premium Beer</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table> _x000D_
</div>
_x000D_
This article helped: https://css-tricks.com/table-borders-inside/
After trying out both of the top two suggestions, I've settled on a shady-looking middle route for Python 2.7. Maybe 3 is saner, but for me:
class MyDict(MutableMapping):
# ... the few __methods__ that mutablemapping requires
# and then this monstrosity
@property
def __class__(self):
return dict
which I really hate, but seems to fit my needs, which are:
**my_dict
dict
, this bypasses your code. try it out.isinstance(my_dict, dict)
dict
If you need to tell yourself apart from others, personally I use something like this (though I'd recommend better names):
def __am_i_me(self):
return True
@classmethod
def __is_it_me(cls, other):
try:
return other.__am_i_me()
except Exception:
return False
As long as you only need to recognize yourself internally, this way it's harder to accidentally call __am_i_me
due to python's name-munging (this is renamed to _MyDict__am_i_me
from anything calling outside this class). Slightly more private than _method
s, both in practice and culturally.
So far I have no complaints, aside from the seriously-shady-looking __class__
override. I'd be thrilled to hear of any problems that others encounter with this though, I don't fully understand the consequences. But so far I've had no problems whatsoever, and this allowed me to migrate a lot of middling-quality code in lots of locations without needing any changes.
As evidence: https://repl.it/repls/TraumaticToughCockatoo
Basically: copy the current #2 option, add print 'method_name'
lines to every method, and then try this and watch the output:
d = LowerDict() # prints "init", or whatever your print statement said
print '------'
splatted = dict(**d) # note that there are no prints here
You'll see similar behavior for other scenarios. Say your fake-dict
is a wrapper around some other datatype, so there's no reasonable way to store the data in the backing-dict; **your_dict
will be empty, regardless of what every other method does.
This works correctly for MutableMapping
, but as soon as you inherit from dict
it becomes uncontrollable.
Edit: as an update, this has been running without a single issue for almost two years now, on several hundred thousand (eh, might be a couple million) lines of complicated, legacy-ridden python. So I'm pretty happy with it :)
Edit 2: apparently I mis-copied this or something long ago. @classmethod __class__
does not work for isinstance
checks - @property __class__
does: https://repl.it/repls/UnitedScientificSequence
Yes, div can take as many classes as you need. Use space to separate one from another.
<div class="active dropdown-toggle custom-class">Example of multiple classses</div>
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
You can do it calling setRowSelectionInterval :
table.setRowSelectionInterval(0, 0);
to select the first row.
You need to use OPENROWSET
Check this question: import-excel-spreadsheet-columns-into-sql-server-database
$res = ActivityServer::query()->select('channel_id')->where(['id' => $id])->first()->attributesToArray();
I use get()
, it returns an object, I use the attributesToArray()
to change the object attribute to an array.
I wonder why the best answer that I've found is only in the comments! (by Daenyth with 86 up votes)
git reset --hard origin
This command will sync the local repository with the remote repository getting rid of every change you have made on your local. You can also do the following to fetch the exact branch that you have in the origin.
git reset --hard origin/<branch>
$SQL_Part="("
$i=0;
while ($i<length($cat)-1)
{
$SQL_Part+=$cat[i]+",";
}
$SQL_Part=$SQL_Part+$cat[$i+1]+")"
$SQL="SELECT * FROM products WHERE catid IN "+$SQL_Part;
It's more generic and will fit for any array!!
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
I personally use the following batch script that can be used on many types of files (C, makefile, Perl scripts, shell scripts, batch, ...).
How to use it:
"$(SYS.APPDATA)\Notepad++\runNcompile.bat" "$(FULL_CURRENT_PATH)"
(optionally, you can put npp_save
on the first line to save the file before running it)This page explains quite clearly the global flow: https://www.thecrazyprogrammer.com/2015/08/configure-notepad-to-run-c-cpp-and-java-programs.html
Hope it can help
@echo off
REM ----------------------
REM ----- ARGUMENTS ------
REM ----------------------
set FPATH=%~1
set FILE=%~n1
set DIR=%~dp1
set EXTENSION=%~x1
REM ----------------------
REM ----------------------
REM ------- CONFIG -------
REM ----------------------
REM C Compiler (gcc.exe or cl.exe) + options + object extension
set CL_compilo=gcc.exe
set CFLAGS=-c "%FPATH%"
set OBJ_Ext=o
REM GNU make
set GNU_make=make.exe
REM ----------------------
IF /I "%FILE%"==Makefile GOTO _MAKEFILE
IF /I %EXTENSION%==.bat GOTO _BAT
IF /I %EXTENSION%==.sh GOTO _SH
IF /I %EXTENSION%==.pl GOTO _PL
IF /I %EXTENSION%==.tcl GOTO _TCL
IF /I %EXTENSION%==.c GOTO _C
IF /I %EXTENSION%==.mak GOTO _MAKEFILE
IF /I %EXTENSION%==.mk GOTO _MAKEFILE
IF /I %EXTENSION%==.html GOTO _HTML
echo Format of argument (%FPATH%) not supported!
GOTO END
REM Batch shell files (bat)
:_BAT
call "%FPATH%"
goto END
REM Linux shell scripts (sh)
:_SH
call sh.exe "%FPATH%"
goto END
REM Perl Script files (pl)
:_PL
call perl.exe "%FPATH%"
goto END
REM Tcl Script files (tcl)
:_TCL
call tclsh.exe "%FPATH%"
goto END
REM Compile C Source files (C)
:_C
REM MAKEFILES...
IF EXIST "%DIR%Makefile" ( cd "%DIR%" )
IF EXIST "%DIR%../Makefile" ( cd "%DIR%/.." )
IF EXIST "%DIR%../../Makefile" ( cd "%DIR%/../.." )
IF EXIST "Makefile" (
call %GNU_make% all
goto END
)
REM COMPIL...
echo -%CL_compilo% %CFLAGS%-
call %CL_compilo% %CFLAGS%
IF %ERRORLEVEL% EQU 0 (
echo -%CL_compilo% -o"%DIR%%FILE%.exe" "%DIR%%FILE%.%OBJ_Ext%"-
call %CL_compilo% -o"%DIR%%FILE%.exe" "%DIR%%FILE%.%OBJ_Ext%"
)
IF %ERRORLEVEL% EQU 0 (del "%DIR%%FILE%.%OBJ_Ext%")
goto END
REM Open HTML files in web browser (html and htm)
:_HTML
start /max /wait %FPATH%
goto END
REM ... END ...
:END
echo.
IF /I "%2" == "-pause" pause
I found this on exceljet.net and works for me:
=LEFT(B4,FIND(" ",B4)-1)
What seems easy is actually tricky if you want to be completely compatible.
var e = document.createElement('div');
Let's say you have an id of 'div1' to add.
e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).
But there are contingencies, of course.
Will not work in IE prior to 8:e.attributes['style']
Will not error but won't actually set the class, it must be className:e['class']
.
However, if you're using attributes then this WILL work:e.attributes['class']
In summary, think of attributes as literal and object-oriented.
In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.
Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.
It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.
This was longer than I wanted, but CSS manipulation in JS is tricky business.
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
Building off of Fabio's answer, I created two functions that will probably be useful for anyone stumbling upon this question. With these two functions, you can call insertParam()
with a key and value as an argument. It will either add the URL parameter or, if a query param already exists with the same key, it will change that parameter to the new value:
//function to remove query params from a URL
function removeURLParameter(url, parameter) {
//better to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
return url;
} else {
return url;
}
}
//function to add/update query params
function insertParam(key, value) {
if (history.pushState) {
// var newurl = window.location.protocol + "//" + window.location.host + search.pathname + '?myNewUrlQuery=1';
var currentUrlWithOutHash = window.location.origin + window.location.pathname + window.location.search;
var hash = window.location.hash
//remove any param for the same key
var currentUrlWithOutHash = removeURLParameter(currentUrlWithOutHash, key);
//figure out if we need to add the param with a ? or a &
var queryStart;
if(currentUrlWithOutHash.indexOf('?') !== -1){
queryStart = '&';
} else {
queryStart = '?';
}
var newurl = currentUrlWithOutHash + queryStart + key + '=' + value + hash
window.history.pushState({path:newurl},'',newurl);
}
}
You might also try an elseif.
x <- 1
if (x ==1){
print('same')
} else if (x > 1){
print('bigger')
} else {
print('smaller')
}
As far as I know Angular-cli file can't be created via a command like Package-lock file, If you want to create it, you have to do it manually.
You can type ng new to create a new angular project
Locate its .angular-cli.json file
Copy all its content
Create a folder in your original project, and name it .angular-cli.json
Paste what copied from new project in newly created angular cli file of original project.
Locate this line in angular cli file you created, and change the name field to original project's name. You can find the project name in package.json file
project": { "name": "<name of the project>" },
However, in newer angular version now it uses angular.json instead of angular-cli.json.
By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.
In C++ projects past, I have used PCRE with good success. It's very complete and well-tested since it's used in many high profile projects. And I see that Google has contributed a set of C++ wrappers for PCRE recently, too.
As Brad Wilson states in his answer here:
ModelState.IsValid tells you if any model errors have been added to ModelState.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
Try using :-
if (!ModelState.IsValid)
{
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
// Breakpoint, Log or examine the list with Exceptions.
}
If it helps catching you the error. Courtesy this and this
Thanks to this question (and answers), I discovered an easy way to get at the exact NumberFormat string for virtually any format that Excel has to offer.
Step 1: In the user interface, set a cell to the NumberFormat you want to use.
In my example, I selected the Chinese (PRC) Currency from the options contained in the "Account Numbers Format" combo box.
Step 2: Expand the Number Format dropdown and select "More Number Formats...".
Step 3: In the Number tab, in Category, click "Custom".
The "Sample" section shows the Chinese (PRC) currency formatting that I applied.
The "Type" input box contains the NumberFormat string that you can use programmatically.
So, in this example, the NumberFormat of my Chinese (PRC) Currency cell is as follows:
_ [$¥-804]* #,##0.00_ ;_ [$¥-804]* -#,##0.00_ ;_ [$¥-804]* "-"??_ ;_ @_
If you do these steps for each NumberFormat that you desire, then the world is yours.
I hope this helps.
Async/Await with axios
useEffect(() => {
const getData = async () => {
await axios.get('your_url')
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
});
}
getData()
}, [])
Sometimes it is useful to temporarily change Git's case sensitivity.
Method #1 - Change case sensitivity for a single command:
git -c core.ignorecase=true checkout mybranch
to turn off case-sensitivity for a single checkout
command. Or more generally: git -c core.ignorecase=
<<true or false>>
<<command>>
. (Credit to VonC for suggesting this in the comments.)
Method #2 - Change case sensitivity for multiple commands:
To change the setting for longer (e.g. if multiple commands need to be run before changing it back):
git config core.ignorecase
(this returns the current setting, e.g. false
).git config core.ignorecase
<<true or false>>
- set the desired new setting.git config core.ignorecase
<<false or true>>
- set config value back to its previous setting.Also if you want different status-bar
color for different activity (fragments) you can do it with following steps (work on API 21 and above):
First create values21/style.xml
and put following code:
<style name="AIO" parent="AIOBase">
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:windowContentTransitions">true</item>
</style>
Then define White|Dark themes in your values/style.xml
like following:
<style name="AIOBase" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/color_primary</item>
<item name="colorPrimaryDark">@color/color_primary_dark</item>
<item name="colorAccent">@color/color_accent</item>
<item name="android:textColorPrimary">@android:color/black</item>
<item name="android:statusBarColor" tools:targetApi="lollipop">@color/color_primary_dark
</item>
<item name="android:textColor">@color/gray_darkest</item>
<item name="android:windowBackground">@color/default_bg</item>
<item name="android:colorBackground">@color/default_bg</item>
</style>
<style name="AIO" parent="AIOBase" />
<style name="AIO.Dark" parent="AIOBase">
<item name="android:statusBarColor" tools:targetApi="lollipop">#171717
</item>
</style>
<style name="AIO.White" parent="AIOBase">
<item name="android:statusBarColor" tools:targetApi="lollipop">#bdbdbd
</item>
</style>
Also don't forget to apply themes in your manifest.xml
.
I have edited the given above example...
public class YourActivity extends implements OnMarkerClickListener
{
......
private void setMarker()
{
.......
googleMap.setOnMarkerClickListener(this);
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
......
}
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(this,marker.getTitle(),Toast.LENGTH_LONG).show();
}
}
it's nil
in Ruby, not null
. And it's enough to say if @objectname
to test whether it's not nil. And no then
. You can find more on if
syntax here:
http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Control_Structures#if
func lastIndexOfCharacter(_ c: Character) -> Int? {
return range(of: String(c), options: .backwards)?.lowerBound.encodedOffset
}
Since advancedBy(Int)
is gone since Swift 3 use String
's method index(String.Index, Int)
. Check out this String
extension with substring and friends:
public extension String {
//right is the first encountered string after left
func between(_ left: String, _ right: String) -> String? {
guard let leftRange = range(of: left), let rightRange = range(of: right, options: .backwards)
, leftRange.upperBound <= rightRange.lowerBound
else { return nil }
let sub = self.substring(from: leftRange.upperBound)
let closestToLeftRange = sub.range(of: right)!
return sub.substring(to: closestToLeftRange.lowerBound)
}
var length: Int {
get {
return self.characters.count
}
}
func substring(to : Int) -> String {
let toIndex = self.index(self.startIndex, offsetBy: to)
return self.substring(to: toIndex)
}
func substring(from : Int) -> String {
let fromIndex = self.index(self.startIndex, offsetBy: from)
return self.substring(from: fromIndex)
}
func substring(_ r: Range<Int>) -> String {
let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
return self.substring(with: Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex)))
}
func character(_ at: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: at)]
}
func lastIndexOfCharacter(_ c: Character) -> Int? {
guard let index = range(of: String(c), options: .backwards)?.lowerBound else
{ return nil }
return distance(from: startIndex, to: index)
}
}
public extension String {
//right is the first encountered string after left
func between(_ left: String, _ right: String) -> String? {
guard
let leftRange = range(of: left), let rightRange = range(of: right, options: .backwards)
, leftRange.upperBound <= rightRange.lowerBound
else { return nil }
let sub = self[leftRange.upperBound...]
let closestToLeftRange = sub.range(of: right)!
return String(sub[..<closestToLeftRange.lowerBound])
}
var length: Int {
get {
return self.count
}
}
func substring(to : Int) -> String {
let toIndex = self.index(self.startIndex, offsetBy: to)
return String(self[...toIndex])
}
func substring(from : Int) -> String {
let fromIndex = self.index(self.startIndex, offsetBy: from)
return String(self[fromIndex...])
}
func substring(_ r: Range<Int>) -> String {
let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
let indexRange = Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex))
return String(self[indexRange])
}
func character(_ at: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: at)]
}
func lastIndexOfCharacter(_ c: Character) -> Int? {
guard let index = range(of: String(c), options: .backwards)?.lowerBound else
{ return nil }
return distance(from: startIndex, to: index)
}
}
Usage:
let text = "www.stackoverflow.com"
let at = text.character(3) // .
let range = text.substring(0..<3) // www
let from = text.substring(from: 4) // stackoverflow.com
let to = text.substring(to: 16) // www.stackoverflow
let between = text.between(".", ".") // stackoverflow
let substringToLastIndexOfChar = text.lastIndexOfCharacter(".") // 17
P.S. It's really odd that developers forced to deal with String.Index
instead of plain Int
. Why should we bother about internal String
mechanics and not just have simple substring()
methods?
commands
also works.
import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result
It works on linux, python 2.7.
repalce content with the CSS
h1{ font-size: 0px;}
h1:after {
content: "new content";
font-size: 15px;
}
Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed()
function:
var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?
sudo apt-get remove docker docker-engine docker.io containerd runc
sudo rm -rf /var/lib/docker
sudo apt-get autoclean
sudo apt-get update
WordPress' implementation is definitly the safest for UTF8 strings. For Latin1 strings, a simple strtr does the job, but ensure you're saving your script in LATIN1 format, not UTF-8.
If I've understood your problem correctly, there are two possible problems here:
resultset
is null
- I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.resultset.getString(i++)
will get columns 1,2,3 and so on from each subsequent row.I think that the second point is probably your problem here.
Lets say you only had 1 row returned, as follows:
Col 1, Col 2, Col 3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
Edit:
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
One of the best compressors (not specifically an obfuscator) is the YUI Compressor.
You can remove bullets by setting the list-style-type
to none
on the CSS for the parent element (typically a <ul>
), for example:
ul {
list-style-type: none;
}
You might also want to add padding: 0
and margin: 0
to that if you want to remove indentation as well.
See Listutorial for a great walkthrough of list formatting techniques.
If you check Thrown
for Common Language Runtime Exception
in the break when an exception window (Ctrl+Alt+E in Visual Studio), then the execution should break while you are debugging when the exception is thrown.
This will probably give you some insight into what is going on.
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization();
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
else{
print("Location service disabled");
}
}
This is your view did load method and in the ViewController Class also include the mapStart updating method as follows
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue : CLLocationCoordinate2D = manager.location.coordinate;
let span2 = MKCoordinateSpanMake(1, 1)
let long = locValue.longitude;
let lat = locValue.latitude;
print(long);
print(lat);
let loadlocation = CLLocationCoordinate2D(
latitude: lat, longitude: long
)
mapView.centerCoordinate = loadlocation;
locationManager.stopUpdatingLocation();
}
Also do not forget to add CoreLocation.FrameWork and MapKit.Framework in your project (no longer necessary as of XCode 7.2.1)
Junit is included by default with Eclipse (at least the Java EE version I'm sure). You may just need to add the view to your perspective.
There's no need to manually put class files on Tomcat. Just make sure your package declaration for Member
is correctly defined as
package pageNumber;
since, that's the only application package you're importing in your JSP.
<%@ page import="pageNumber.*, java.util.*, java.io.*" %>
If you need a more convenient way to access the results, it's possible to transform the result of an arbitrarily complex SQL query to a Java class with minimal hassle:
Query query = em.createNativeQuery("select 42 as age, 'Bob' as name from dual",
MyTest.class);
MyTest myTest = (MyTest) query.getResultList().get(0);
assertEquals("Bob", myTest.name);
The class needs to be declared an @Entity, which means you must ensure it has an unique @Id.
@Entity
class MyTest {
@Id String name;
int age;
}
There is some good information in these answers. Suppose you are dealing with databases which you can't alter, and that you are copying data from one version of the table to another, or from the same table in one database to another. Suppose also that there are lots of columns, and you either need data from all the columns, or the columns which you don't need don't have default values. You need to write a query with all the column names.
Here is a query which returns all the non-timestamp column names for a table, which you can cut and paste into your insert query. FYI: 189 is the type ID for timestamp.
declare @TableName nvarchar(50) = 'Product';
select stuff(
(select
', ' + columns.name
from
(select id from sysobjects where xtype = 'U' and name = @TableName) tables
inner join syscolumns columns on tables.id = columns.id
where columns.xtype <> 189
for xml path('')), 1, 2, '')
Just change the name of the table at the top from 'Product' to your table name. The query will return a list of column names:
ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate
If you are copying data from one database (DB1) to another database(DB2) you could use this query.
insert DB2.dbo.Product (ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate)
select ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate
from DB1.dbo.Product
You need to do
./configure --with-ssl=openssl --with-libssl-prefix=/usr/local/ssl
Instead of this
./configure --with-ssl=openssl
To add to Preston's answer, here's the complete list of the HttpContent
derived classes available in the standard library:
Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/
There's also a supposed ObjectContent
but I was unable to find it in ASP.NET Core
.
Of course, you could skip the whole HttpContent
thing all together with Microsoft.AspNet.WebApi.Client
extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:
var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
Title = "New Article Title",
Body = "New Article Body"
});
Moment.js can convert unix timestamps into any custom format
In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");
will print 18-10-2013 11:53:14
;
Here's a plunker that demonstrates this.
Assuming that you do not want to change orig
, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:
from itertools import chain
dest = dict(chain(orig.items(), extra.items()))
Or without itertools:
dest = dict(list(orig.items()) + list(extra.items()))
Note that you only need to pass the result of items()
into list()
on Python 3, on 2.x dict.items()
already returns a list so you can just do dict(orig.items() + extra.items())
.
As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:
from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))
Try getppid()
if you want your C program to print your shell's PID.
You want to initialize an array. (For more info - Tutorial)
int []ar={11,22,33};
String []stringAr={"One","Two","Three"};
From the JLS
The []
may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:
byte[] rowvector, colvector, matrix[];
This declaration is equivalent to:
byte rowvector[], colvector[], matrix[][];
If your string contains special characters you can hash it to md5 and then convert it to a guid/uniqueidentifier.
SELECT CONVERT(UNIQUEIDENTIFIER, HASHBYTES('MD5','~öü߀a89b1acd95016ae6b9c8aabb07da2010'))
I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.
Open Installation Details:
Choose Plug-ins tab => type org.eclipse.platform => check Version column.
You can match version code and version name on https://wiki.eclipse.org/Older_Versions_Of_Eclipse
For example, check out GitEye (Git GUI client)
Or checkout DBBeaver (DB manager):
You can also use function truncate
$truncate -s0 yourfile
if permission denied, use sudo
$sudo truncate -s0 yourfile
Help/Manual: man truncate
tested on ubuntu Linux
Here is how I solved my problem:
Directive
app.directive("directive_name", function(){
return {
restrict: 'E',
transclude: true,
template: function(elem, attr){
return '<div><h2>{{'+attr.scope+'}}</h2></div>';
},
replace: true
};
})
Controller
$scope.building = function(data){
var chart = angular.element(document.createElement('directive_name'));
chart.attr('scope', data);
$compile(chart)($scope);
angular.element(document.getElementById('wrapper')).append(chart);
}
I now can use different scopes through the same directive and append them dynamically.
Description:
quirksmode.org has a nice description of this. In a nutshell (copied from quirksmode):
Event capturing
When you use event capturing
| | ---------------| |----------------- | element1 | | | | -----------| |----------- | | |element2 \ / | | | ------------------------- | | Event CAPTURING | -----------------------------------
the event handler of element1 fires first, the event handler of element2 fires last.
Event bubbling
When you use event bubbling
/ \ ---------------| |----------------- | element1 | | | | -----------| |----------- | | |element2 | | | | | ------------------------- | | Event BUBBLING | -----------------------------------
the event handler of element2 fires first, the event handler of element1 fires last.
What to use?
It depends on what you want to do. There is no better. The difference is the order of the execution of the event handlers. Most of the time it will be fine to fire event handlers in the bubbling phase but it can also be necessary to fire them earlier.
sb.AppendLine();
or
sb.Append( "\n" );
And
sb.Append( "\t" );
In Hive, tables are actually stored in a few places. Specifically, if you use partitions (which you should, if your tables are very large or growing) then each partition can have its own storage.
To show the default location where table data or partitions will be created if you create them through default HIVE commands: (insert overwrite ... partition ...
and such):
describe formatted dbname.tablename
To show the actual location of a particular partition within a HIVE table, instead do this:
describe formatted dbname.tablename partition (name=value)
If you look in your filesystem where a table "should" live, and you find no files there, it's very likely that the table is created (usually incrementally) by creating a new partition and pointing that partition at some other location. This is a great way of building tables from things like daily imports from third parties and such, which avoids having to copy the files around or storing them more than once in different places.
Node.js is exactly used for back-end development, but it is popular as a full-stack and front-end solution as well. It is used primarily to build web applications, but it is a very popular choice for building enterprise applications too.
Developers like it because of its versatility, agility and performance. It increases productivity and application performance in a significant way. Since Node.js has a long-term support (LTS) plan that provides security and stability, it's no wonder that huge enterprises constantly add it to their stacks.
It is non-blocking and event-driven. Node.js applications uses “Single Threaded Event Loop Model” architecture to handle multiple concurrent clients. These features are key factors to make real time web applications.
There's no widget for toast in flutter, You can go to this plugin Usecase:
Fluttertoast.showToast(
msg: "My toast messge",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,);
All the answers above are correct. In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :
I have an HTML :
<div id="contents"></div>
Go to console (cntrl+shift+c)
and use these commands to see your result clearly
document.getElementById('contents')
>>> div#contents
$('#contents')
>>> [div#contents,
context: document,
selector: "#contents",
jquery: "1.10.1",
constructor: function,
init: function …]
As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects. And as mentioned by other answers above, you can use the following command:
$('#contents')[0]
>>> div#contents
I have encountered the same error as well. I am sure my indentation did not have any problem. Only restarting the python sell solved the problem.
To incorporate third-party DLLs into my VS 2008 C++ project I did the following (you should be able to translate into 2010, 2012 etc.)...
I put the header files in my solution with my other header files, made changes to my code to call the DLLs' functions (otherwise why would we do all this?). :^) Then I changed the build to link the LIB code into my EXE, to copy the DLLs into place, and to clean them up when I did a 'clean' - I explain these changes below.
Suppose you have 2 third-party DLLs, A.DLL and B.DLL, and you have a stub LIB file for each (A.LIB and B.LIB) and header files (A.H and B.H).
(You'll have to make the next set of changes once for each source build target that you use (Debug, Release).)
Make your EXE dependent on the LIB files
A.LIB B.LIB
$(SolutionDir)fodder
there, you change it to $(SolutionDir)fodder;$(SolutionDir)lib
to add "lib".Force the DLLs to get copied to the output directory
XCOPY "$(SolutionDir)"\lib\*.DLL "$(TargetDir)" /D /K /Y
Copy DLLs to Target Directory
No
.
Click OK
.Tell VS to clean up the DLLs when it cleans up an output folder:
*.dll
to the end of the list and click OK
.Sending data to some service page.
<form class="form-horizontal" role="form" ng-submit="submit_form()">
<input type="text" name="user_id" ng-model = "formAdata.user_id">
<input type="text" id="name" name="name" ng-model = "formAdata.name">
</form>
$scope.submit_form = function()
{
$http({
url: "http://localhost/services/test.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.formAdata)
}).success(function(data, status, headers, config) {
$scope.status = status;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}
Use this:
((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(),
typeof(AssemblyFileVersionAttribute), false)
).Version;
Or this:
new Version(System.Windows.Forms.Application.ProductVersion);
Sometimes if you change the starting activity you have to click edit in the run dropdown play button and in app change the Launch Options Activity to the one you have set the LAUNCHER intent filter in the manifest.
Take a look at Beaker:
Some plugins require one to run as an Administrator
and will not load unless one has those credentials active in the shell.
#include <iostream>
//////////////
// C++ code //
//////////////
struct A
{
int i;
int j;
A() {i=1; j=2; std::cout << "class A created\n";}
void dump() {std::cout << "class A dumped: " << i << ":" << j << std::endl;}
~A() {std::cout << "class A destroyed\n";}
};
extern "C" {
// this is the C code interface to the class A
static void *createA (void)
{
// create a handle to the A class
return (void *)(new A);
}
static void dumpA (void *thisPtr)
{
// call A->dump ()
if (thisPtr != NULL) // I'm an anal retentive programmer
{
A *classPtr = static_cast<A *>(thisPtr);
classPtr->dump ();
}
}
static void *deleteA (void *thisPtr)
{
// destroy the A class
if (thisPtr != NULL)
{
delete (static_cast<A *>(thisPtr));
}
}
}
////////////////////////////////////
// this can be compiled as C code //
////////////////////////////////////
int main (int argc, char **argv)
{
void *handle = createA();
dumpA (handle);
deleteA (handle);
return 0;
}
So with Angular 1.5.1 ( had existing app dependency on some other MEAN stack dependencies is why I'm not currently using 1.6.4 )
This works for me like the OP saying {{myVar === "two" ? "it's true" : "it's false"}}
{{vm.StateName === "AA" ? "ALL" : vm.StateName}}
One question that the answers given so far don't seem to address: if the runtime libraries (not the OS, really) can keep track of the number of things in the array, then why do we need the delete[]
syntax at all? Why can't a single delete
form be used to handle all deletes?
The answer to this goes back to C++'s roots as a C-compatible language (which it no longer really strives to be.) Stroustrup's philosophy was that the programmer should not have to pay for any features that they aren't using. If they're not using arrays, then they should not have to carry the cost of object arrays for every allocated chunk of memory.
That is, if your code simply does
Foo* foo = new Foo;
then the memory space that's allocated for foo
shouldn't include any extra overhead that would be needed to support arrays of Foo
.
Since only array allocations are set up to carry the extra array size information, you then need to tell the runtime libraries to look for that information when you delete the objects. That's why we need to use
delete[] bar;
instead of just
delete bar;
if bar is a pointer to an array.
For most of us (myself included), that fussiness about a few extra bytes of memory seems quaint these days. But there are still some situations where saving a few bytes (from what could be a very high number of memory blocks) can be important.
Firefox and other programs allow you to increase and decrease the font size with C-+ and C--. I set up my .emacs so that I have that same ability by adding these lines of code:
(global-set-key [C-kp-add] 'text-scale-increase)
(global-set-key [C-kp-subtract] 'text-scale-decrease)
If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.
I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.
A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.
Here is a more generic solution based on @rindeal solution which does not work on MacOS/BSD (/r
expects a file):
cat << DOC > input.txt
abc
cdef
line
DOC
$ cat << EOF | sed '/^cdef$/ r /dev/stdin' input.txt
line 1
line 2
EOF
# outputs:
abc
cdef
line 1
line 2
line
This can be used to pipe anything into the file at the given position:
$ date | sed '/^cdef$/ r /dev/stdin' input.txt
# outputs
abc
cdef
Tue Mar 17 10:50:15 CET 2020
line
Also, you could add multiple commands which allows deleting the marker line cdef
:
$ date | sed '/^cdef$/ {
r /dev/stdin
d
}' input.txt
# outputs
abc
Tue Mar 17 10:53:53 CET 2020
line
I think this will help, Base64 is addressed by CSS in a different way, you should set the data type of the image to base64, this will help the CSS to change the base64 to image and display it to the user. and you can use this from javascript by assigning the background image using the jquery script, it will automatically change the base64 to mage and display it
url = "data:image;base64,"+data.replace(/(\r\n|\n|\r)/gm, "");_x000D_
$("body").css("background-image", "url('" + url.replace(/(\r\n|\n|\r)/gm, "") + "')");
_x000D_
here is how I dealed: I pushed an array "colors", with same number of entries than number of datas. For this I added a function "getRandomColor" at the end of the script. Hope it helps...
for (var i in arr) {
customers.push(arr[i].customer);
nb_cases.push(arr[i].nb_cases);
colors.push(getRandomColor());
}
window.onload = function() {
var config = {
type: 'pie',
data: {
labels: customers,
datasets: [{
label: "Nomber of cases by customers",
data: nb_cases,
fill: true,
backgroundColor: colors
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Cases by customers"
},
}
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.
But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.
To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.
Symbolic or soft link (files or directories, more flexible and self documenting)
# Source Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx
Hard link (files only, less flexible and not self documenting)
# Source Link
ln /home/jake/doc/test/2000/something /home/jake/xxx
More information: man ln
/home/jake/xxx
is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:
cd /home/jake/
ln -s /home/jake/doc/test/2000/something xxx
I have used the following method in a project and it's working successfully.
private string identifier(string wmiClass, string wmiProperty)
//Return a hardware identifier
{
string result = "";
System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
return result;
}
you can call the above method as mentioned below,
string modelNo = identifier("Win32_DiskDrive", "Model");
string manufatureID = identifier("Win32_DiskDrive", "Manufacturer");
string signature = identifier("Win32_DiskDrive", "Signature");
string totalHeads = identifier("Win32_DiskDrive", "TotalHeads");
If you need a unique identifier, use a combination of these IDs.
I know this question already has answers but I will give my solution to this problem. I am using template function and integer constraint on it.
Here is my solution:
#include <type_traits>
#include <vector>
template <typename T,
typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
std::vector<uint8_t> splitValueToBytes(T const& value)
{
std::vector<uint8_t> bytes;
for (size_t i = 0; i < sizeof(value); i++)
{
uint8_t byte = value >> (i * 8);
bytes.insert(bytes.begin(), byte);
}
return bytes;
}
res = request.GET['paymentid']
will raise a KeyError
if paymentid
is not in the GET data.
Your sample php code checks to see if paymentid
is in the POST data, and sets $payID
to '' otherwise:
$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''
The equivalent in python is to use the get()
method with a default argument:
payment_id = request.POST.get('payment_id', '')
while debugging, this is what I see in the
response.GET: <QueryDict: {}>
,request.POST: <QueryDict: {}>
It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.
Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.
I was attempting something similar, and the RoboSpice example helped me work it out:
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity<String> request = new HttpEntity<>(input, createHeader());
String url = "http://awesomesite.org";
Uri.Builder uriBuilder = Uri.parse(url).buildUpon();
uriBuilder.appendQueryParameter(key, value);
uriBuilder.appendQueryParameter(key, value);
...
String url = uriBuilder.build().toString();
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request , String.class);
You can use the information schema views:
SELECT DISTINCT TABLE_SCHEMA, TABLE_NAME
FROM Information_Schema.Columns
WHERE COLUMN_NAME = 'ID'
Here's the MSDN reference for the "Columns" view: http://msdn.microsoft.com/en-us/library/ms188348.aspx
I had the same issue. Turns out, you need the EntityFramework.dll reference (and not System.Data.Entity).
I just pulled it from the MvcMusicStore application which you can download from: http://mvcmusicstore.codeplex.com/
It's also a useful example of how to use entity framework code-first with MVC.
If you got node __dirname not defined
with node --experimental-modules
, you can do :
const __dirname = path.dirname(import.meta.url)
.replace(/^file:\/\/\//, '') // can be usefull
Because othe example, work only with current/pwd directory not other directory.
The accepted answer by @Meherzad only works if the data is in a particular order. It happens to work with the data from the OP question. In my case, I had to modify it to work with my data.
Note This only works when every record's "id" (col1 in the question) has a value GREATER THAN that record's "parent id" (col3 in the question). This is often the case, because normally the parent will need to be created first. However if your application allows changes to the hierarchy, where an item may be re-parented somewhere else, then you cannot rely on this.
This is my query in case it helps someone; note it does not work with the given question because the data does not follow the required structure described above.
select t.col1, t.col2, @pv := t.col3 col3
from (select * from table1 order by col1 desc) t
join (select @pv := 1) tmp
where t.col1 = @pv
The difference is that table1
is being ordered by col1
so that the parent will be after it (since the parent's col1
value is lower than the child's).
There is an easy way to change the colors in Actionbar
Use ActionBar Generator and copy paste all file in your res
folder and change your theme in Android.manifest file.
In PostreSQL you can use SIMILAR TO operator (more):
-- only digits
select * from books where title similar to '^[0-9]*$';
-- start with digit
select * from books where title similar to '^[0-9]%$';
Martin Fowler defines the Lazy Load pattern in Patterns of Enterprise Application Architecture as such:
An object that doesn't contain all of the data you need but knows how to get it.
So, when loading a given object, the idea is to not eager load the related object(s) that you may not use immediately to save the related performance cost. Instead, the related object(s) will be loaded only when used.
This is not a pattern specific to data access and Hibernate but it is particularly useful in such fields and Hibernate supports lazy loading of one-to-many associations and single-point associations (one-to-one and many-to-one) also under certain conditions. Lazy interaction is discussed in more detail in Chapter 19 of the Hibernate 3.0 Reference Documentation.
GNU cp
has an option to create symlinks instead of copying.
cp -rs /mnt/usr/lib /usr/
Note this is a GNU extension not found in POSIX cp
.
I think this is the simplest solution. Pure shell builtins, no inline math. It borrows from previous answers.
Just substrings and the ${#...} meta-variable.
A="[>---------------------<]";
# Strip excess padding from the right
#
B="A very long header"; echo "${A:0:-${#B}} $B"
B="shrt hdr" ; echo "${A:0:-${#B}} $B"
Produces
[>----- A very long header
[>--------------- shrt hdr
# Strip excess padding from the left
#
B="A very long header"; echo "${A:${#B}} $B"
B="shrt hdr" ; echo "${A:${#B}} $B"
Produces
-----<] A very long header
---------------<] shrt hdr
Brought my answer over from other thread that may close as a duplicate...
From GIT documentation: Git Docs
Below gives the full information. In short, simple
will only push the current working branch
and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0
Whereas matching
will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.
In my personal usage, I generally use a different option: current
which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple
push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.
current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.
upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).
simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.
When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.
This mode will become the default in Git 2.0.
matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).
To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.
This is currently the default, but Git 2.0 will change the default to simple.
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
import sys
del sys.modules['module_name']
Use safely-turning-a-json-string-into-an-object
var jsonString = '{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
var jsonObject = (new Function("return " + jsonString))();
alert(jsonObject.id);
If you just want to print the raw XML you don't need Simple XML. I added some error handling and a simple example of how you might want to use SimpleXML.
<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
if ($result === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($curl);
//we can at this point echo the XML if you want
//echo $result;
//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);
if ($xml === false) {
die('Error parsing XML');
}
//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
print $item->title;
}
One of most upleasing functional forEach
's limitations is lack of checked exceptions support.
One possible workaround is to replace terminal forEach
with plain old foreach loop:
Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
Iterable<String> iterable = stream::iterator;
for (String s : iterable) {
fileWriter.append(s);
}
Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:
Java 8 Lambda function that throws exception?
Java 8: Lambda-Streams, Filter by Method with Exception
How can I throw CHECKED exceptions from inside Java 8 streams?
Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?
How about something like this?
<input name="myvalue" type="text" onfocus="if(this.value=='enter value')this.value='';" onblur="if(this.value=='')this.value='enter value';">
This will clear upon focusing the first time, but then won't clear on subsequent focuses after the user enters their value, when left blank it restores the given value.
EDIT: If you're a designer then Papyrus is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then ObjectAid is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !.
UPDATE Oct 11th, 2013
My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer.
I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway.
The Answer (Oct 11th, 2013)
Tools
Steps
Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml
Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one.
ALT+W -> show view -> papyrus -> model explorer
In that view, you'll find your classes like in the picture
In the view Right click root model -> New diagram
Then start grabbing classes to the diagram from the view
Some features
To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !!
You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram
one very important setting is Arrange when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All
Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc
After all of that your settings will show diagrams like
Synchronization isn't available as far as I know you'll need to manually import any new classes.
That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something.
Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools.
To avoid leaving the file open, it is best to pass a block to File.open. This way, the file will be closed after the block executes.
contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }
For multiple lines the best way I find is to do this:
IEnumerable<string> lines = new List<string>
{
string.Format("{{ line with formatting... {0} }}", id),
"line 2",
"line 3"
};
StringBuilder sb = new StringBuilder();
foreach(var line in lines)
sb.AppendLine(line);
In this way you don't have to clutter the screen with the Environment.NewLine or AppendLine() repeated multiple times. It will also be less error prone than having to remember to type them.
I don't much like an idea of writing binary protobuf to database, because it can one day become not backward-compatible with newer versions and break the system that way.
Converting protobuf to JSON for storage and then back to protobuf on load is much more likely to create compatibility problems, because:
With all that said, there are many libraries out there for converting protobufs to JSON, usually built on the Protobuf reflection interface (not to be confused with the Java reflection interface; Protobuf reflection is offered by the com.google.protobuf.Message
interface).
i don't know about converting into a byte array, but it's easy to convert it into a string:
import base64
with open("t.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print str
You can use inline styling to limit the height:
<img src="" class="img-responsive" alt="" style="max-height: 400px;">
var rotator = function(){
widget.Rotator.rotate();
setTimeout(rotator,5000);
};
rotator();
Or:
setInterval(
function(){ widget.Rotator.rotate() },
5000
);
Or:
setInterval(
widget.Rotator.rotate.bind(widget.Rotator),
5000
);
Late to the game.. and there are several great answers above-- essentially, that the compileSdkVersion
is the version of the API the app is compiled against, while the targetSdkVersion
indicates the version that the app was tested against.
I'd like to supplement those answers with the following notes:
targetSdkVersion
is 23 or higher, the app requests permissions from the user at run-time.targetSdkVersion
is 22 or lower, the system asks the user to grant the permissions when the user installs the app.If the compileSdkVersion
is higher than the version declared by your app's targetSdkVersion
, the system may enable compatibility behaviors to ensure that your app continues to work the way you expect. (ref)
With each new Android release...
targetSdkVersion
should be incremented to match the latest API level, then thoroughly test your application on the corresponding platform versioncompileSdkVersion
, on the other hand, does not need to be changed unless you're adding features exclusive to the new platform versiontargetSdkVersion
is often (initially) less than than the compileSdkVersion
, it's not uncommon to see a well-maintained/established app with targetSdkVersion > compileSdkVersion
$('.sys').children('input[type=text], select').each(function () { ... });
EDIT: Actually this code above is equivalent to the children selector .sys > input[type=text]
if you want the descendant select (.sys input[type=text]
) you need to use the options given by @NiftyDude.
More information:
My problem was selinux...
Go sestatus
If Current mode: enforcing
Then chcon -R -t httpd_sys_rw_content_t /var/www/html
EDIT: This applies to older versions of Visual Studio / MSBuild (specifically MSVC2015?). With more modern versions, MSBuild is included in Visual Studio Build Tools 2019, and compilers are located in different places and detected in different ways.
This is due to a mismatch of installed MSBuild toolsets and registry settings. It can happen if you did one or more of the following:
The only safe and reliable solution I know of is to reinstall your OS. If your project needs multiple versions of Visual Studio to build, install the oldest version first. Then fix your code so you can use one single tool to build it, or you or your colleagues will be in the same mess again soon.
If this is not an option for you, first read https://stackoverflow.com/a/41786593/2279059 for a better understanding of the problem and what the various "solutions" actually do. Then, depending on your Visual Studio version and setup, one of the other answers or variations of them may eventually help.
Some more hints:
You can use this:
var refreshIntervalId = null;
refreshIntervalId = setInterval(checkIfVariableIsSet, 1000);
var checkIfVariableIsSet = function()
{
if(typeof someVariable !== 'undefined'){
$('a.play').trigger("click");
clearInterval(refreshIntervalId);
}
};
Instead of using log4net which is an external library I have created my own simple class, highly customizable and easy to use (edit YOURNAMESPACEHERE
with the namespace that you need).
CONSOLE APP
using System;
using System.IO;
namespace YOURNAMESPACEHERE
{
enum LogEvent
{
Info = 0,
Success = 1,
Warning = 2,
Error = 3
}
internal static class Log
{
private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";
internal static void Write(LogEvent Level, string Message, bool ShowConsole = true, bool WritelogFile = true)
{
string Event = string.Empty;
ConsoleColor ColorEvent = Console.ForegroundColor;
switch (Level)
{
case LogEvent.Info:
Event = "INFO";
ColorEvent = ConsoleColor.White;
break;
case LogEvent.Success:
Event = "SUCCESS";
ColorEvent = ConsoleColor.Green;
break;
case LogEvent.Warning:
Event = "WARNING";
ColorEvent = ConsoleColor.Yellow;
break;
case LogEvent.Error:
Event = "ERROR";
ColorEvent = ConsoleColor.Red;
break;
}
if (ShowConsole)
{
Console.ForegroundColor = ColorEvent;
Console.WriteLine(" [{0}] => {1}", DateTime.Now.ToString("HH:mm:ss"), Message);
Console.ResetColor();
}
if (WritelogFile)
{
if (!Directory.Exists(LogPath))
Directory.CreateDirectory(LogPath);
File.AppendAllText(LogPath + @"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
}
}
}
}
NO CONSOLE APP (ONLY LOG)
using System;
using System.IO;
namespace YOURNAMESPACEHERE
{
enum LogEvent
{
Info = 0,
Success = 1,
Warning = 2,
Error = 3
}
internal static class Log
{
private static readonly string LogSession = DateTime.Now.ToLocalTime().ToString("ddMMyyyy_HHmmss");
private static readonly string LogPath = AppDomain.CurrentDomain.BaseDirectory + "logs";
internal static void Write(LogEvent Level, string Message)
{
string Event = string.Empty;
switch (Level)
{
case LogEvent.Info:
Event = "INFO";
break;
case LogEvent.Success:
Event = "SUCCESS";
break;
case LogEvent.Warning:
Event = "WARNING";
break;
case LogEvent.Error:
Event = "ERROR";
break;
}
if (!Directory.Exists(LogPath))
Directory.CreateDirectory(LogPath);
File.AppendAllText(LogPath + @"\" + LogSession + ".log", string.Format("[{0}] => {1}: {2}\n", DateTime.Now.ToString("HH:mm:ss"), Event, Message));
}
}
Usage:
CONSOLE APP
Log.Write(LogEvent.Info, "Test message"); // It will print an info in your console, also will save a copy of this print in a .log file.
Log.Write(LogEvent.Warning, "Test message", false); // It will save the print as warning only in your .log file.
Log.Write(LogEvent.Error, "Test message", true, false); // It will print an error only in your console.
NO CONSOLE APP (ONLY LOG)
Log.Write(LogEvent.Info, "Test message"); // It will print an info in your .log file.
rtrim
function
rtrim($my_string,',');
Second parameter indicates that comma to be deleted from right side.
If you are using the Rails 4.x you can now generate migrations with references, like this:
rails generate migration AddUserRefToProducts user:references
like you can see on rails guides
Differentiate between the two cases you named:
To indicate that the requested operation is not supported and most likely never will, throw an UnsupportedOperationException
.
To indicate the requested operation has not been implemented yet, choose between this:
Use the NotImplementedException
from apache commons-lang which was available in commons-lang2 and has been re-added to commons-lang3 in version 3.2.
Implement your own NotImplementedException
.
Throw an UnsupportedOperationException
with a message like "Not implemented, yet".
int belongs to System.ValueType and cannot have null as a value. When dealing with databases or other types where the elements can have a null value, it might be useful to check if the element is null. That is when int? comes into play. int? is a nullable type which can have values ranging from -2147483648 to 2147483648 and null.
Reference: https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx
If you are running a custom named service, you should see two executables in your Tomcat/bin directory
In my case with Tomcat 8
08/14/2019 10:24 PM 116,648 Tomcat-Custom.exe
08/14/2019 10:24 PM 119,720 Tomcat-Customw.exe
2 File(s) 236,368 bytes
Running the "w" terminated executable will let you configure Xmx in the Java
tab
here it it
var ffversion = '18';
var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox/'+ffversion) > -1;
alert(is_firefox);