Redux can't return a function instead of an action. It's just a fact. That's why people use Thunk. Read these 14 lines of code to see how it allows the async cycle to work with some added function layering:
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => (next) => (action) => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
In Linux, Open the VIM configuration file
$ sudo -H gedit /etc/vim/vimrc
Added following lines:
set fileencodings=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936
set termencoding=utf-8
set encoding=utf-8
Save and exit, and terminal command:
$ source /etc/vim/vimrc
At this time VIM will correctly display Chinese.
While sizeof
works for this specific type of string:
char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'
It does not work if str
is pointer (sizeof
returns size of pointer, usually 4 or 8) or array with specified length (sizeof
will return the byte count matching specified length, which for char type are same).
Just use strlen()
.
One useful line of code for you would be:
$sql = "Your SQL statement here";
$result = mysqli_query($this->db_link, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($this->db_link), E_USER_ERROR);
This method is better than die
, because you can use it for development AND production. It's the permanent solution.
hope this might help someone else out there
SELECT
.... FROM XXX XX
WHERE
....
AND(
param1 IS NULL
OR XX.param1 = param1
)
The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:
final String extensionRemoved = filename.split("\\.")[0];
I hope this helps
function getStringReminder(str, substr, occ) {
let index = str.indexOf(substr);
let preindex = '';
let i = 1;
while (index !== -1) {
preIndex = index;
if (occ == i) {
break;
}
index = str.indexOf(substr, index + 1)
i++;
}
return preIndex;
}
console.log(getStringReminder('bcdefgbcdbcd', 'bcd', 3));
It might be worth adding here there are a few pointers when using the @ you should be aware of, for a complete run down view this post: http://mstd.eu/index.php/2016/06/30/php-rapid-fire-what-is-the-symbol-used-for-in-php/
The error handler is still fired even with the @ symbol prepended, it just means a error level of 0 is set, this will have to be handled appropriately in a custom error handler.
Prepending a include with @ will set all errors in the include file to an error level of 0
This works using java.util.Scanner and will take multiple "enter" keystrokes:
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null) {
System.out.println(readString);
if (readString.isEmpty()) {
System.out.println("Read Enter Key.");
}
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
} else {
readString = null;
}
}
To break it down:
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
These lines initialize a new Scanner
that is reading from the standard input stream (the keyboard) and reads a single line from it.
while(readString!=null) {
System.out.println(readString);
While the scanner is still returning non-null data, print each line to the screen.
if (readString.isEmpty()) {
System.out.println("Read Enter Key.");
}
If the "enter" (or return, or whatever) key is supplied by the input, the nextLine()
method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
} else {
readString = null;
}
Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.
top
object makes more sense inside frames. Inside a frame, window
refers to current frame's window while top
refers to the outermost window that contains the frame(s). So:
window.location.href = 'somepage.html';
means loading somepage.html
inside the frame.
top.location.href = 'somepage.html';
means loading somepage.html
in the main browser window.
To get the path, you can use:
var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url = window.location.href; // Returns full URL (https://example.com/path/example.html)
var origin = window.location.origin; // Returns base URL (https://example.com)
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED
above will return values
however below query wont work
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED
as @INPUT_1 actually has varchar in it.
So your output column must have a varchar in it.
Short answer: H.264 MPEG (MP4)
Long answer from Apple.com:
Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,
Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
If you want to recursively convert the entire array into an Object type (stdClass) then , below is the best method and it's not time-consuming or memory deficient especially when you want to do a recursive (multi-level) conversion compared to writing your own function.
$array_object = json_decode(json_encode($array));
In the jar file you could just add this to your manifest.mft
Main-Class : A
The jar file would then be executable and would call the correct main.
On how to do this in Netbeans you can look at this: Producing executable jar in NetBeans
Presumably this would work:
IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment
When you use addEventListener
, this
will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this
from within your function:
productLineSelect.addEventListener('change',getSelection,false);
function getSelection(){
var value = sel.options[this.selectedIndex].value;
alert(value);
}
If you want to pass in some other argument from the context where you call addEventListener
, you can use a closure, like this:
productLineSelect.addEventListener('change', function(){
// pass in `this` (the element), and someOtherVar
getSelection(this, someOtherVar);
},false);
function getSelection(sel, someOtherVar){
var value = sel.options[sel.selectedIndex].value;
alert(value);
alert(someOtherVar);
}
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
These lines are your problem (or at least one of your problems, if there are more):
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
You reference some static members in the initializers for other static members. This is a bad idea, as the compiler doesn't know in which order to initialize them. The result is that during the initialization of s_bstCommonAppData
, the dependent field s_commonAppData
has not yet been initialized, so you are calling Path.Combine(null, "XXXX")
and this method does not accept null arguments.
You can fix this by making sure that fields used in the initialization of other fields are declared first:
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
Or use a static constructor to explicitly order the assignments:
private static string s_bstCommonAppData;
private static string s_bstUserDataDir;
private static string s_commonAppData;
static Logger()
{
s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
}
You can do this by using Apace common lang package (org.apache.commons.lang.ArrayUtils
class ). You need to do the following
byte[] concatBytes = ArrayUtils.addAll(one,two);
apparently it's bound to an int, which is 0x7FFFFFFF (2147483647).
plt.imshow
just finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add plt.show
.
I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:
Stream.of(objects)
.filter(c -> c instanceof Client)
.map(c -> (Client) c)
.map(Client::getID)
.forEach(System.out::println);
or, as suggested in the comments, you could use the cast
method - the former may be easier to read though:
Stream.of(objects)
.filter(Client.class::isInstance)
.map(Client.class::cast)
.map(Client::getID)
.forEach(System.out::println);
What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.
If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.
EDIT
I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.
It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc()
call, etc.) so those warnings would not be very useful due to the false positive frequency.
You can also do this in a .htaccess file assuming they are enabled on the website.
SetEnv KOHANA_ENV production
Would be all you need to add to a .htaccess to add the environment variable
Add following option for java application:
-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2
public class LambdaScopeTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
// The following statement causes the compiler to generate
// the error "local variables referenced from a lambda expression
// must be final or effectively final" in statement A:
//
// x = 99;
}
}
}
As others have said, a variable or parameter whose value is never changed after it is initialized is effectively final. In the above code, if you change the value of x
in inner class FirstLevel
then the compiler will give you the error message:
Local variables referenced from a lambda expression must be final or effectively final.
Building on other posted answers.
Both of these will produce the right values:
select distributor_id,
count(*) total,
sum(case when level = 'exec' then 1 else 0 end) ExecCount,
sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id
SELECT a.distributor_id,
(SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
(SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
(SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM myTable a ;
However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.
I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.
As an example, run the following script:
IF OBJECT_ID (N't1', N'U') IS NOT NULL
drop table t1
create table t1 (f1 int)
insert into t1 values (1)
insert into t1 values (1)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1
SELECT
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)
Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.
Adding a clustered index is also interesting. E.g.
Create clustered index t1f1 on t1(f1);
Update Statistics t1;
The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.
Today I had a scenario, where I was performing following:
myViewGroup.setVisibility(View.GONE);
Right on the next frame I was performing an if
check somewhere else for visibility state of that view. Guess what? The following condition was passing:
if(myViewGroup.getVisibility() == View.VISIBLE) {
// this `if` was fulfilled magically
}
Placing breakpoints you can see, that visibility changes to GONE
, but right on the next frame it magically becomes VISIBLE
. I was trying to understand how the hell this could happen.
Turns out there was an animation applied to this view, which internally caused the view to change it's visibility to VISIBLE
until finishing the animation:
public void someFunction() {
...
TransitionManager.beginDelayedTransition(myViewGroup);
...
myViewGroup.setVisibility(View.GONE);
}
If you debug, you'll see that myViewGroup
indeed changes its visibility to GONE
, but right on the next frame it would again become visible in order to run the animation.
So, if you come across with such a situation, make sure you are not performing an if
check in amidst of animating the view.
You can remove all animations on the view via View.clearAnimation()
.
finish()
gives you method to close current Activity not whole application. And you better don't try to look for methods to kill application. Little advice.
Have you tried conjunction of Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY
? Remember to use this flags in Intent
starting activity!
Once you've found your jar through mvnrepository.com, hover the "download (JAR)" link, and you'll see the link to the repository which contains your jar (you can probably Right clic and "Copy link URL" to get the URL, what ever your browser is).
Then, you have to add this repository to the repositories used by your project, in your pom.xml :
<project>
...
<repositories>
<repository>
<id>my-alternate-repository</id>
<url>http://myrepo.net/repo</url>
</repository>
</repositories>
...
</project>
EDIT : now MVNrepository.com has evolved : You can find the link to the repository in the "Repositories" section :
License
Categories
HomePage
Date
Files
Repositories
for python3 user, install python3-tk package by following command
sudo apt-get install python3-tk
The problem in your code is xml.LoadXml(filePath);
LoadXml
method take parameter as xml data not the xml file path
Try this code
string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlFile);
XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
string Short_Fall=string.Empty;
foreach (XmlNode node in nodeList)
{
Short_Fall = node.InnerText;
}
Edit
Seeing the last edit of your question i found the solution,
Just replace the below 2 lines
XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")
with
string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;
It should solve your problem or you can use the solution i provided earlier.
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"name" forKey:@"email"];
[contentDictionary setValue:@"name" forKey:@"username"];
[contentDictionary setValue:@"name" forKey:@"password"];
[contentDictionary setValue:@"name" forKey:@"firstName"];
[contentDictionary setValue:@"name" forKey:@"lastName"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);
NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
If you submit the form via Javascript (i.e. formElement.submit()
or anything equivalent), then none of the submit buttons are considered successful and none of their values are included in the submitted data. (Note that if you submit the form by using submitElement.click()
then the submit that you had a reference to is considered active; this doesn't really fall under the remit of your question since here the submit button is unambiguous but I thought I'd include it for people who read the first part and wonder how to make a submit button successful via JS form submission. Of course, the form's onsubmit handlers will still fire this way whereas they wouldn't via form.submit()
so that's another kettle of fish...)
If the form is submitted by hitting Enter while in a non-textarea field, then it's actually down to the user agent to decide what it wants here. The specs don't say anything about submitting a form using the enter key while in a text entry field (if you tab to a button and activate it using space or whatever, then there's no problem as that specific submit button is unambiguously used). All it says is that a form must be submitted when a submit button is activated, it's not even a requirement that hitting enter in e.g. a text input will submit the form.
I believe that Internet Explorer chooses the submit button that appears first in the source; I have a feeling that Firefox and Opera choose the button with the lowest tabindex, falling back to the first defined if nothing else is defined. There's also some complications regarding whether the submits have a non-default value attribute IIRC.
The point to take away is that there is no defined standard for what happens here and it's entirely at the whim of the browser - so as far as possible in whatever you're doing, try to avoid relying on any particular behaviour. If you really must know, you can probably find out the behaviour of the various browser versions but when I investigated this a while back there were some quite convoluted conditions (which of course are subject to change with new browser versions) and I'd advise you to avoid it if possible!
This should give you a list of all the tables in your database
SELECT Distinct TABLE_NAME FROM information_schema.TABLES
So you can use it similar to your database check.
If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
--CREATE TABLE Your_Table
END
GO
You can hide StackNavigator header like this:
const Stack = createStackNavigator();
function StackScreen() {
return (
<Stack.Navigator
screenOptions={{ headerShown: false }}>
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="Training" component={Training} />
<Stack.Screen name="Course" component={Course} />
<Stack.Screen name="Signup" component={Signup} />
</Stack.Navigator>
);
}
following links might help
http://labe.felk.cvut.cz/~xfaigl/mep/xml/java-xml.htm
You can compile your C programs with an ARM cross-compiler:
arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test
Then you can push your compiled binary file to somewhere (don't push it in to the SD card):
adb push test /data/local/tmp/test
To solve this problem on Linux, you need to recompile your PHP with the --enable-mbstring
flag.
There are multiple ways to log. console.warn() will through the log in the mobile screen itself.It can be useful if you want to log small things and dont want to bother opening console. Other is console.log(), for which you will have to open browser's console to view the logs.With the newer react native 0.62+ you can see the log in node itself. So they've made it pretty easier to view logs in newer version.
Create a new instance each time, where each new instance has the correct state, rather than continually modifying the state of the same instance.
Alternately, store an explicitly-made copy of the object (using the hint at this page) at each step, rather than the original.
Two ways to do that..
Option 1:
1. Go to "Start" -> "Run".
2. Write "CMD" and press on "Enter" key.
3. Write the command "net statistics server" and press on "Enter" key.
4. The line that start with "Statistics since …" provides the time that the server was up from.
The command "net stats srv" can be use instead.
Option 2:
Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher
http://support.microsoft.com/kb/232243
Hope it helped you!!
Use css property,
text-decoration:none;
To remove underline from the link.
Be careful of span
!
myspan.styles.width='100px'
doesn't want to work.
Change the span
to a div
.
Your results will not be helpful unless the arrays are first sorted. To sort an array, run it through Sort-Object.
$x = @(5,1,4,2,3)
$y = @(2,4,6,1,3,5)
Compare-Object -ReferenceObject ($x | Sort-Object) -DifferenceObject ($y | Sort-Object)
This will work as well:
.clearfix:before,
.clearfix:after {
content: "";
display: table;
}
.clearfix:after {
clear: both;
}
/* IE 6 & 7 */
.clearfix {
zoom: 1;
}
Give the class clearfix
to the parent element, for example your ul
element.
I know it's a several years old post and you may solve your problem with above solution. However, i just want to suggest using InverseProperty for someone who still need. At least you don't need to change anything in OnModelCreating.
The below code is un-tested.
public class Team
{
[Key]
public int TeamId { get; set;}
public string Name { get; set; }
[InverseProperty("HomeTeam")]
public virtual ICollection<Match> HomeMatches { get; set; }
[InverseProperty("GuestTeam")]
public virtual ICollection<Match> GuestMatches { get; set; }
}
public class Match
{
[Key]
public int MatchId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
You can read more about InverseProperty on MSDN: https://msdn.microsoft.com/en-us/data/jj591583?f=255&MSPPError=-2147217396#Relationships
PrintWriter out = null; // for writting in file
String newLine = System.getProperty("line.separator"); // taking new line
out.print("1st Line"+newLine); // print with new line
out.print("2n Line"+newLine); // print with new line
out.close();
There is no such thing as an interpreted language. Whether an interpreter or a compiler is used is purely a trait of the implementation and has absolutely nothing whatsoever to do with the language.
Every language can be implemented by either an interpreter or a compiler. The vast majority of languages have at least one implementation of each type. (For example, there are interpreters for C and C++ and there are compilers for JavaScript, PHP, Perl, Python and Ruby.) Besides, the majority of modern language implementations actually combine both an interpreter and a compiler (or even multiple compilers).
A language is just a set of abstract mathematical rules. An interpreter is one of several concrete implementation strategies for a language. Those two live on completely different abstraction levels. If English were a typed language, the term "interpreted language" would be a type error. The statement "Python is an interpreted language" is not just false (because being false would imply that the statement even makes sense, even if it is wrong), it just plain doesn't make sense, because a language can never be defined as "interpreted."
In particular, if you look at the currently existing Python implementations, these are the implementation strategies they are using:
You might notice that every single one of the implementations in that list (plus some others I didn't mention, like tinypy, Shedskin or Psyco) has a compiler. In fact, as far as I know, there is currently no Python implementation which is purely interpreted, there is no such implementation planned and there never has been such an implementation.
Not only does the term "interpreted language" not make sense, even if you interpret it as meaning "language with interpreted implementation", it is clearly not true. Whoever told you that, obviously doesn't know what he is talking about.
In particular, the .pyc
files you are seeing are cached bytecode files produced by CPython, Stackless Python or Unladen Swallow.
It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.
To change current working dir to the one containing your script you can use:
import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())
The __file__
variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?
/**
* Shows confirmation dialog about signing in.
*/
private void startAuthDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(800, 1400);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.auth_dialog, null);
alertDialog.getWindow().setContentView(dialogView);
EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
}
Use
<% String username = (String)request.getSession().getAttribute(...); %>
Note that your use of <%! ... %>
is translated to class-level, but request is only available in the service()
method of the translated servlet.
In Apache I edit the following configuration file: C:\xampp\php.ini
I make sure to have the following lines uncommented:
extension=php_pgsql.dll
extension=php_pdo_pgsql.dll
Finally restart Apache before attempting a new connection to the database engine.
Also, I leave my code that ensures that the connection is unique:
private static $pdo = null;
public static function provideDataBaseInstance() {
if (self::$pdo == null) {
$dsn = "pgsql:host=" . HOST .
";port=5432;dbname=" . DATABASE .
";user=" . POSTGRESQL_USER .
";password=" . POSTGRESQL_PASSWORD;
try {
self::$pdo = new PDO($dsn);
} catch (PDOException $exception) {
$msg = $exception->getMessage();
echo $msg .
". Do not forget to enable in the web server the database
manager for php and in the database instance authorize the
ip of the server instance if they not in the same
instance.";
}
}
return self::$pdo;
}
GL
$header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")
Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {
$record = $indexName
foreach ($property in $_.PSObject.Properties){
#doSomething $property.Name, $property.Value
if($property.Name -like '*TextWrittenAsNumber*'){
$record = $record + "," + '"' + $property.Value + '"'
}
else{
$record = $record + "," + $property.Value
}
}
$array.add($record) | out-null
#write-host $record
}
Before Java 7:
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Since Java 7, there is no need to close the stream, because it implements autocloseable
try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
I too was looking for a good way to do this, I found the best way was to set a transition on the "transform" property and then change the transform and then remove the transition.
I put it all together in a jQuery plugin
https://gist.github.com/dustinpoissant/8a4837c476e3939a5b3d1a2585e8d1b0
You would use the code like this:
$("#myElement").animateTransform("rotate(180deg)", 750, function(){
console.log("animation completed after 750ms");
});
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
maven {
url 'http://maven2.javacv.googlecode.com/git/'
}
}
dependencies {
compile 'com.android.support:support-v4:13.0.+'
compile 'com.googlecode.javacv:javacv:0.5'
instrumentTestCompile 'junit:junit:4.4'
}
android {
compileSdkVersion 14
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 14
}
}
This is worked for me :)
On wp8:
Wrap it:
Task GetCustomersSynchronously()
{
Task t = new Task(async () =>
{
myCustomers = await GetCustomers();
}
t.RunSynchronously();
}
Call it:
GetCustomersSynchronously();
For the record, none of the answers above helped except for one. To summarize, you can do the backup operation using --files-from=
by using either:
rsync -aSvuc `cat rsync-src-files` /mnt/d/rsync_test/
OR
rsync -aSvuc --recursive --files-from=rsync-src-files . /mnt/d/rsync_test/
The former command is self explanatory, beside the content of the file rsync-src-files
which I will elaborate down below. Now, if you want to use the latter version, you need to keep in mind the following four remarks:
--files-from
and the source directory--recursive
. rsync-src-files
is a user created file and it was placed within the src directory for this testrsyn-src-files
contain the files and folders to copy and they are taken relative to the source directory. IMPORTANT: Make sure there is not trailing spaces or blank lines in the file. In the example below, there are only two lines, not three (Figure it out by chance). Content of rsynch-src-files
is:folderName1
folderName2
The following answer is to merge data into same table
MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif')
WHEN NOT MATCHED THEN
INSERT ( d.USERS_ID, d.USER_NAME)
VALUES ('123','itszaif');
This command checks if USER_ID
and USER_NAME
are matched, if not matched then it will insert.
string query = "SELECT column_name FROM table_name"; //query the database
SqlCommand queryStatus = new SqlCommand(query, myConnection);
sqlDataReader reader = queryStatus.ExecuteReader();
while (reader.Read()) //loop reader and fill the combobox
{
ComboBox1.Items.Add(reader["column_name"].ToString());
}
There is an easier way than the one written by CommonsWare. Just create a drawable resource that specifies the way the EditText
will be drawn:
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:padding="10dp">
<solid android:color="#FFFFFF" />
<corners
android:bottomRightRadius="15dp"
android:bottomLeftRadius="15dp"
android:topLeftRadius="15dp"
android:topRightRadius="15dp" />
</shape>
Then, just reference this drawable in your layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip"
android:background="@drawable/rounded_edittext" />
</LinearLayout>
You will get something like:
Based on Mark's comment, I want to add the way you can create different states for your EditText
:
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext_states.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/rounded_focused" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/rounded_focused" />
<item
android:state_enabled="true"
android:drawable="@drawable/rounded_edittext" />
</selector>
These are the states:
<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext_focused.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#FFFFFF"/>
<stroke android:width="2dp" android:color="#FF0000" />
<corners
android:bottomRightRadius="15dp"
android:bottomLeftRadius="15dp"
android:topLeftRadius="15dp"
android:topRightRadius="15dp" />
</shape>
And... now, the EditText
should look like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:background="@drawable/rounded_edittext_states"
android:padding="5dip" />
</LinearLayout>
you can use servlet filter chain, but instead use the original one, you can create your own request yourownrequests extends HttpServletRequestWrapper.
///check Parenthesis
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(map.containsKey(c)){
stack.push(c);
} else if(!stack.empty() && map.get(stack.peek())==c){
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
Using the selectedOptions
property:
var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);
It works in all browsers except Internet Explorer.
You can do it like this
[btnTwo setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
Legacy. List was originally defined to be functional-languages-looking:
1 :: 2 :: Nil // a list
list1 ::: list2 // concatenation of two lists
list match {
case head :: tail => "non-empty"
case Nil => "empty"
}
Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++
to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.
JSFiddle wraps your code in a function, so start()
is not defined in the global scope.
Moral of the story: don't use inline event bindings. Use addEventListener
/attachEvent
.
Please don't pass strings to setTimeout
and setInterval
. It's eval
in disguise.
Use a function instead, and get cozy with var
and white space:
var input = document.getElementById("input"),
add;
function start() {
add = setInterval(function() {
input.value++;
}, 1000);
}
start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
_x000D_
you need to join the two tables:
for instance you want to copy the value of name
from tableA into tableB
where they have the same ID
UPDATE tableB t1
INNER JOIN tableA t2
ON t1.id = t2.id
SET t1.name = t2.name
WHERE t2.name = 'Joe'
UPDATE 1
UPDATE tableB t1
INNER JOIN tableA t2
ON t1.id = t2.id
SET t1.name = t2.name
UPDATE 2
UPDATE tableB t1
INNER JOIN tableA t2
ON t1.name = t2.name
SET t1.value = t2.value
Change SMTP=localhost to SMTP=smtp.gmail.com
Firebase doesn't allow querying with multiple conditions. However, I did find a way around for this:
We need to download the initial filtered data from the database and store it in an array list.
Query query = databaseReference.orderByChild("genre").equalTo("comedy");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ArrayList<Movie> movies = new ArrayList<>();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String lead = dataSnapshot1.child("lead").getValue(String.class);
String genre = dataSnapshot1.child("genre").getValue(String.class);
movie = new Movie(lead, genre);
movies.add(movie);
}
filterResults(movies, "Jack Nicholson");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Once we obtain the initial filtered data from the database, we need to do further filter in our backend.
public void filterResults(final List<Movie> list, final String genre) {
List<Movie> movies = new ArrayList<>();
movies = list.stream().filter(o -> o.getLead().equals(genre)).collect(Collectors.toList());
System.out.println(movies);
employees.forEach(movie -> System.out.println(movie.getFirstName()));
}
what if you could just run k8s within docker's vm? there's native support for this with the more recent versions of docker desktop... you just need to enable that support.
https://www.docker.com/blog/kubernetes-is-now-available-in-docker-desktop-stable-channel/ https://www.docker.com/blog/docker-windows-desktop-now-kubernetes/
how i found this out:
while reading the docs for helm, they give you a brief tutorial how to install minikube. that tutorial installs minikube in a vm that's different/separate from docker.
so when it came time to install my helm charts, i couldn't get helm/k8s to pull the images i had built using docker. that's how i arrived here at this question.
so... if you can live with whatever version of k8s comes with docker desktop, and you can live with it running in whatever vm docker has, then maybe this solution is a bit easier than some of the others.
disclaimer: not sure how switching between windows/linux containers would impact anything.
And here is a quick benchmark for both #sample
and #rand
:
irb(main):014:0* Benchmark.bm do |x|
irb(main):015:1* x.report('sample') { 1_000_000.times { (1..100).to_a.sample } }
irb(main):016:1> x.report('rand') { 1_000_000.times { rand(1..100) } }
irb(main):017:1> end
user system total real
sample 3.870000 0.020000 3.890000 ( 3.888147)
rand 0.150000 0.000000 0.150000 ( 0.153557)
So, doing rand(a..b)
is the right thing
this way is a bit more flexible than using all()
:
my_list = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
all_zeros = False if False in [x[2] == 0 for x in my_list] else True
any_zeros = True if True in [x[2] == 0 for x in my_list] else False
or more succinctly:
all_zeros = not False in [x[2] == 0 for x in my_list]
any_zeros = 0 in [x[2] for x in my_list]
select * from *tablename* where 1 having length(*fieldname*)=*fieldlength*
Example if you want to select from customer the entry's with a name shorter then 2 chars.
select * from customer where 1 **having length(name)<2**
According to the problem you can try this...
// looping between date range
while (startDate <= endDate)
{
//here will be your code block...
startDate = startDate.AddDays(1);
}
thanks......
Without any third-party tools and any app, you can find unused CSS and javascript by using chrome dev tools in the coverage tab. read the post below from google developers. chrome coverage tab
While it is true that there is no DROP ALL TABLES command you can use the following set of commands.
Note: These commands have the potential to corrupt your database, so make sure you have a backup
PRAGMA writable_schema = 1;
delete from sqlite_master where type in ('table', 'index', 'trigger');
PRAGMA writable_schema = 0;
you then want to recover the deleted space with
VACUUM;
and a good test to make sure everything is ok
PRAGMA INTEGRITY_CHECK;
I offer one more solution in case it is worthful for someone else.
I have a history.js
file where I have the following:
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
history.pushLater = (...args) => setImmediate(() => history.push(...args))
export default history
Next, on my Root where I define my router I use the following:
import history from '../history'
import { Provider } from 'react-redux'
import { Router, Route, Switch } from 'react-router-dom'
export default class Root extends React.Component {
render() {
return (
<Provider store={store}>
<Router history={history}>
<Switch>
...
</Switch>
</Router>
</Provider>
)
}
}
Finally, on my actions.js
I import History and make use of pushLater
import history from './history'
export const login = createAction(
...
history.pushLater({ pathname: PATH_REDIRECT_LOGIN })
...)
This way, I can push to new actions after API calls.
Hope it helps!
Cast to long or cast to int, be aware of the following.
These functions are one of the view functions in Excel VBA that are depending on the system regional settings. So if you use a comma in your double like in some countries in Europe, you will experience an error in the US.
E.g., in european excel-version 0,5 will perform well with CDbl(), but in US-version it will result in 5. So I recommend to use the following alternative:
Public Function CastLong(var As Variant)
' replace , by .
var = Replace(var, ",", ".")
Dim l As Long
On Error Resume Next
l = Round(Val(var))
' if error occurs, l will be 0
CastLong = l
End Function
' similar function for cast-int, you can add minimum and maximum value if you like
' to prevent that value is too high or too low.
Public Function CastInt(var As Variant)
' replace , by .
var = Replace(var, ",", ".")
Dim i As Integer
On Error Resume Next
i = Round(Val(var))
' if error occurs, i will be 0
CastInt = i
End Function
Of course you can also think of cases where people use commas and dots, e.g., three-thousand as 3,000.00. If you require functionality for these kind of cases, then you have to check for another solution.
KEY
is normally a synonym for INDEX
. The key attribute PRIMARY KEY
can also be specified as just KEY
when given in a column definition. This was implemented for compatibility with other database systems.
column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
...
Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
select isnull(nullif(CAR_OWNER_TEL, ''), 'NULLLLL') PHONE from TABLE
will replace CAR_OWNER_TEL if empty by NULLLLL (MS SQL)
try this
$sql= " INSERT INTO users (username, password) VALUES('test', 'test') ";
mysql_query($sql);
$user_id= mysql_insert_id();
if(!empty($user_id) {
$sql=INSERT INTO profiles (userid, bio, homepage) VALUES($user_id,'Hello world!', 'http://www.stackoverflow.com');
/* or
$sql=INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com'); */
mysql_query($sql);
};
Please find below the easy way :
XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 15);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
Row row = sheet.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
cell0.setCellStyle(style);
for(int j = 0; j<=3; j++)
row.getCell(j).setCellStyle(style);
Here's my take on this question following the msft documentation:
$gpParams = @{
Path = 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
ErrorAction = 'SilentlyContinue'
}
$release = Get-ItemProperty @gpParams | Select-Object -ExpandProperty Release
".NET Framework$(
switch ($release) {
({ $_ -ge 528040 }) { ' 4.8'; break }
({ $_ -ge 461808 }) { ' 4.7.2'; break }
({ $_ -ge 461308 }) { ' 4.7.1'; break }
({ $_ -ge 460798 }) { ' 4.7'; break }
({ $_ -ge 394802 }) { ' 4.6.2'; break }
({ $_ -ge 394254 }) { ' 4.6.1'; break }
({ $_ -ge 393295 }) { ' 4.6'; break }
({ $_ -ge 379893 }) { ' 4.5.2'; break }
({ $_ -ge 378675 }) { ' 4.5.1'; break }
({ $_ -ge 378389 }) { ' 4.5'; break }
default { ': 4.5+ not installed.' }
}
)"
This example works with all PowerShell versions and will work in perpetuity as 4.8 is the last .NET Framework version.
The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Example:
your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Output:
>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>
I used to get similar issues. Even after installing the support repository, the build used to fail.
Basically the issues is due to the way the version number of the jar files are specified in the gradle files are specified properly.
For example, in my case i had set it as "compile 'com.android.support:support-v4:21.0.3+'"
On removing "+" the build was sucessful!!
Assuming your script is something like the below snippet and named testargs.ps1
param ([string]$w)
Write-Output $w
You can call this at the commandline as:
PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"
This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.
I had the same need and used this:
select
case
when left(column,1) = '0'
then right(column, (len(column)-1))
else column
end
This will do the blur overlay over the content:
.blur {
display: block;
bottom: 0;
left: 0;
position: fixed;
right: 0;
top: 0;
-webkit-backdrop-filter: blur(15px);
backdrop-filter: blur(15px);
background-color: rgba(0, 0, 0, 0.5);
}
You can simply create a context and do something like below:-
private Context context = this;
And your animation:-
((Activity) context).overridePendingTransition(R.anim.abc_slide_in_bottom,R.anim.abc_slide_out_bottom);
You can use any animation you want.
This is a C++ interview test question not homework.
Then your interviewer needs to refresh his recollection with how the C++ standard works. And I quote:
For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration.
The whole "whose underlying type is not fixed" part is from C++11, but the rest is all standard C++98/03. In short, the sizeof(months_t)
is not 4. It is not 2 either. It could be any of those. The standard does not say what size it should be; only that it should be big enough to fit any enumerator.
why the all size is 4 bytes ? not 12 x 4 = 48 bytes ?
Because enums are not variables. The members of an enum are not actual variables; they're just a semi-type-safe form of #define. They're a way of storing a number in a reader-friendly format. The compiler will transform all uses of an enumerator into the actual numerical value.
Enumerators are just another way of talking about a number. january
is just shorthand for 0
. And how much space does 0 take up? It depends on what you store it in.
For me this happened because i merged a branch dev into master using web interface and then tried to sync/pull using VSCode which was open on dev branch.(its weird that i could not change to master without getting this error.)
git pull
Your configuration specifies to merge with the ref 'refs/heads/dev'
from the remote, but no such ref was fetched.'
It makes sense that is not finding it refs/heads/dev - for me it was easier to just delete the local folder and clone again.
After all this, I found a new easier method try this ..
It can join multiple photos together:
public static System.Drawing.Bitmap CombineBitmap(string[] files)
{
//read all images into memory
List<System.Drawing.Bitmap> images = new List<System.Drawing.Bitmap>();
System.Drawing.Bitmap finalImage = null;
try
{
int width = 0;
int height = 0;
foreach (string image in files)
{
//create a Bitmap from the file and add it to the list
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);
//update the size of the final bitmap
width += bitmap.Width;
height = bitmap.Height > height ? bitmap.Height : height;
images.Add(bitmap);
}
//create a bitmap to hold the combined image
finalImage = new System.Drawing.Bitmap(width, height);
//get a graphics object from the image so we can draw on it
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
{
//set background color
g.Clear(System.Drawing.Color.Black);
//go through each image and draw it on the final image
int offset = 0;
foreach (System.Drawing.Bitmap image in images)
{
g.DrawImage(image,
new System.Drawing.Rectangle(offset, 0, image.Width, image.Height));
offset += image.Width;
}
}
return finalImage;
}
catch (Exception ex)
{
if (finalImage != null)
finalImage.Dispose();
throw ex;
}
finally
{
//clean up memory
foreach (System.Drawing.Bitmap image in images)
{
image.Dispose();
}
}
}
I have used this library with sucess
http://plugins.krajee.com/checkbox-x
It requires jQuery and bootstrap 3.x
Download the zip here: https://github.com/kartik-v/bootstrap-checkbox-x/zipball/master
Put the contents of the zip in a folder within your project
Pop the needed libs in your header
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="path/to/css/checkbox-x.min.css" media="all" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="path/to/js/checkbox-x.min.js" type="text/javascript"></script>
Add the data controls to the element using the data-size="xl" to change the size as shown here http://plugins.krajee.com/cbx-sizes-demo
<label for="element_id">CheckME</label>
<input type="checkbox" name="my_element" id="element_id" value="1" data-toggle="checkbox-x" data-three-state="false" data-size="xl"/>
There are numerous other features as well if you browse the plugin site.
You can try.
$options['inputs'] = $options['inputs'] + $new_input;
This article seems to show the valid types that are acceptable
<time>2009-11-13</time>
<!-- without @datetime content must be a valid date, time, or precise datetime -->
<time datetime="2009-11-13">13<sup>th</sup> November</time>
<!-- when using @datetime the content can be anything relevant -->
<time datetime="20:00">starting at 8pm</time>
<!-- time example -->
<time datetime="2009-11-13T20:00+00:00">8pm on my birthday</time>
<!-- datetime with time-zone example -->
<time datetime="2009-11-13T20:00Z">8pm on my birthday</time>
<!-- datetime with time-zone “Z” -->
This one covers using it in the <input>
field:
<input type="date" name="d" min="2011-08-01" max="2011-08-15">
This example of the HTML5 input type "date" combine with the attributes min and max shows how we can restrict the dates a user can input. The attributes min and max are not dependent on each other and can be used independently.
<input type="time" name="t" value="12:00">
The HTML5 input type "time" allows users to choose a corresponding time that is displayed in a 24hour format. If we did not include the default value of "12:00" the time would set itself to the time of the users local machine.
<input type="week" name="w">
The HTML5 Input type week will display the numerical version of the week denoted by a "W" along with the corresponding year.
<input type="month" name="m">
The HTML5 input type month does exactly what you might expect it to do. It displays the month. To be precise it displays the numerical version of the month along with the year.
<input type="datetime" name="dt">
The HTML5 input type Datetime displays the UTC date and time code. User can change the the time steps forward or backward in one minute increments. If you wish to display the local date and time of the user you will need to use the next example datetime-local
<input type="datetime-local" name="dtl" step="7200">
Because datetime steps through one minute at a time, you may want to change the default increment by using the attribute "step". In the following example we will have it increment by two hours by setting the attribute step to 7200 (60seconds X 60 minutes X 2).
I know this is old, but I have to add this in here..
And while this is not a full answer, it is an 'IN ADDITION TO'
The address bar will not disappear if you're NOT using https.
ALSO
If you are using https and the address bar still won't hide, you might have some https errors in your webpage (such as certain images being served from a non-https location.)
Hope this helps..
select name, value
from( select name, value, ROW_NUMBER() OVER(PARTITION BY name ORDER BY value desc) as rn
from out_pumptable ) as a
where rn = 1
Swift 5.0, with generics:
func hideViewWithAnimation<T: UIView>(shouldHidden: Bool, objView: T) {
if shouldHidden == true {
UIView.animate(withDuration: 0.3, animations: {
objView.alpha = 0
}) { (finished) in
objView.isHidden = shouldHidden
}
} else {
objView.alpha = 0
objView.isHidden = shouldHidden
UIView.animate(withDuration: 0.3) {
objView.alpha = 1
}
}
}
Use:
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabelBGView)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabel)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountButton)
Here itemCountLabelBGView
is a UIView
, itemCountLabel
is a UILabel
& itemCountButton
is a UIButton
, So it will work for every view object whose parent class is UIView
.
You're so close it's crazy.
if($(this).attr("name"))
There's no hasAttr but hitting an attribute by name will just return undefined if it doesn't exist.
This is why the below works. If you remove the name attribute from #heading the second alert will fire.
Update: As per the comments, the below will ONLY work if the attribute is present AND is set to something not if the attribute is there but empty
<script type="text/javascript">
$(document).ready(function()
{
if ($("#heading").attr("name"))
alert('Look, this is showing because it\'s not undefined');
else
alert('This would be called if it were undefined or is there but empty');
});
</script>
<h1 id="heading" name="bob">Welcome!</h1>
You can use this simple code:
<embed src="audio.mp3" AutoPlay loop hidden>
for the result seen here: https://hataken.000webhostapp.com/list-anime.html
It depends exactly what you're defining as "ASCII", but I would suggest trying a variant of a query like this:
SELECT * FROM tableName WHERE columnToCheck NOT REGEXP '[A-Za-z0-9]';
That query will return all rows where columnToCheck contains any non-alphanumeric characters. If you have other characters that are acceptable, add them to the character class in the regular expression. For example, if periods, commas, and hyphens are OK, change the query to:
SELECT * FROM tableName WHERE columnToCheck NOT REGEXP '[A-Za-z0-9.,-]';
The most relevant page of the MySQL documentation is probably 12.5.2 Regular Expressions.
I was getting this problem and I'm using Spring's RestTemplate on the client and Spring Web on the server. Both APIs have very poor error reporting, making them extremely difficult to develop with.
After many hours of trying all sorts of experiments I figured out that the issue was being caused by passing in a null reference for the POST body instead of the expected List. I presume that RestTemplate cannot determine the content-type from a null object, but doesn't complain about it. After adding the correct headers, I started getting a different server-side exception in Spring before entering my service method.
The fix was to pass in an empty List from the client instead of null. No headers are required since the default content-type is used for non-null objects.
You could try this code which uses the System.Reflection.AssemblyTitleAttribute.Title
property:
((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false)).Title;
I personally prefer to see switch statements over too many nested if-elses because they can be much easier to read. Switches are also better in readability terms for showing a state.
See also the comment in this post regarding pacman ifs.
I had to combine several of the answers to get a working solution.
This solution will:
Not navigate to http://mySite/#
<a href="#" (click)="!!functionToCall()">Link</a>
In Internet Explorer 9 (and 8), the console
object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, the console
object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for the console
object to be exposed.
The console
object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit from Object
, nor its methods from Function
, like native ECMAScript functions and objects do. This is the reason apply
and call
are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM.
For what it's worth, you can still use some Function.prototype
methods on console
methods with a little bind()
magic:
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"
"-123.456e-789" -match "^\-?(\d+\.?\d*)(e\-?\d+)?$|^0x[0-9a-f]+$"
or
"0xab789" -match "^\-?(\d+\.?\d*)(e\-?\d+)?$|^0x[0-9a-f]+$"
will check for numbers (integers, floats and hex).
Please note that this does not cover the case of commas/dots being used as separators for thousands.
Well, if you are writing to a CSV file, then why do you use space as a delimiter? CSV files use commas or semicolons (in Excel) as cell delimiters, so if you use delimiter=' '
, you are not really producing a CSV file. You should simply construct csv.writer
with the default delimiter and dialect. If you want to read the CSV file later into Excel, you could specify the Excel dialect explicitly just to make your intention clear (although this dialect is the default anyway):
example = csv.writer(open("test.csv", "wb"), dialect="excel")
I prefer creating Visual Effects via Storyboard - no code used for creating or maintaining UI Elements. It gives me full landscape support, too. I have made a little demo of using UIVisualEffects with Blur and also Vibrancy.
Note: Commenting out bind_ip can make your system vulnerable to security flaws. Please see Security Checklist. It is a better idea to add more IP addresses than to open up your system to everything.
You need to edit your /etc/mongod.conf file's bind_ip variable to include the IP of the computer you're using, or eliminate it altogether.
I was able to connect using the following mongod.conf file. I commented out bind_ip and uncommented port.
# mongod.conf
# Where to store the data.
# Note: if you run MongoDB as a non-root user (recommended) you may
# need to create and set permissions for this directory manually.
# E.g., if the parent directory isn't mutable by the MongoDB user.
dbpath=/var/lib/mongodb
# Where to log
logpath=/var/log/mongodb/mongod.log
logappend=true
port = 27017
# Listen to local interface only. Comment out to listen on all
interfaces.
#bind_ip = 127.0.0.1
# Disables write-ahead journaling
# nojournal = true
# Enables periodic logging of CPU utilization and I/O wait
#cpu = true
# Turn on/off security. Off is currently the default
#noauth = true
#auth = true
# Verbose logging output.
#verbose = true
# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true
# Enable db quota management
#quota = true
# Set oplogging level where n is
# 0=off (default)
# 1=W
# 2=R
# 3=both
# 7=W+some reads
#diaglog = 0
# Ignore query hints
#nohints = true
# Enable the HTTP interface (Defaults to port 28017).
#httpinterface = true
# Turns off server-side scripting. This will result in greatly limited
# functionality
#noscripting = true
# Turns off table scans. Any query that would do a table scan fails.
#notablescan = true
# Disable data file preallocation.
#noprealloc = true
# Specify .ns file size for new databases.
# nssize = <size>
# Replication Options
# In replicated MongoDB databases, specify the replica set name here
#replSet=setname
# Maximum size in megabytes for replication operation log
#oplogSize=1024
# Path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile
Don't forget to restart the mongod service before trying to connect:
service mongod restart
From Robomongo, I used the following connection settings:
Connection Tab:
SSH Tab:
SSH Address: [VPS IP] : 22
SSH User Name: [Username for sudo enabled user]
SSH Auth Method: Password
User Password: Supersecret
The simplest way is to convert Date to POSIXlt format. Then perform the arithmetic operation as follows:
date_1m_fwd <- as.POSIXlt("2010-01-01")
date_1m_fwd$mon <- date_1m_fwd$mon +1
Moreover, incase you want to deal with Date columns in data.table, unfortunately, POSIXlt format is not supported.
Still you can perform the add month using basic R codes as follows:
library(data.table)
dt <- as.data.table(seq(as.Date("2010-01-01"), length.out=5, by="month"))
dt[,shifted_month:=tail(seq(V1[1], length.out=length(V1)+3, by="month"),length(V1))]
Hope it helps.
var message =/*[[${message}]]*/ 'defaultanyvalue';
There is a property of the built-in window.location
object that will provide that for the current window.
// If URL is http://www.somedomain.com/account/search?filter=a#top
window.location.pathname // /account/search
// For reference:
window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a
It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location
object and anchor elements implement the interface.
So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:
var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";
el.host // www.somedomain.com (includes port if there is one[1])
el.hostname // www.somedomain.com
el.hash // #top
el.href // http://www.somedomain.com/account/search?filter=a#top
el.pathname // /account/search
el.port // (port if there is one[1])
el.protocol // http:
el.search // ?filter=a
[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right
This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.
There's also a coming URL
object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.
There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.
public String GenerateRandom(Random oRandom, int iLongitudPin)
{
String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
int iLength = sCharacters.Length;
char cCharacter;
int iLongitudNuevaCadena = iLongitudPin;
String sRandomResult = "";
for (int i = 0; i < iLongitudNuevaCadena; i++)
{
cCharacter = sCharacters[oRandom.Next(iLength)];
sRandomResult += cCharacter.ToString();
}
return (sRandomResult);
}
Open ~/.bash_profile
and add:
export ANDROID_HOME=~/Library/Android/sdk/
export PATH=$PATH:~/android-sdks/platform-tools/
export PATH=$PATH:~/android-sdks/tools/
source ~/.bash_profile
Just use this API from celery FAQ
result = app.AsyncResult(task_id)
This works fine.
Simple answer: You can't. An array is fixed size in Java. You'll want to use a List<String>
.
Alternatively, you could create an array of fixed size and put things in it:
String[] array = new String[2];
array[0] = "Hello";
array[1] = "World!";
When we have to use inbuilt procedures or packages we have to use "EXECUTE" command then it will work.
EX:
EXECUTE exec DBMS_MVIEW.REFRESH('v_materialized_foo_tbl');
This is not a problem with XAML. The error message is saying that it tried to create an instance of DVRClientInterface.MainWindow
and your constructor threw an exception.
You will need to look at the "Inner Exception" property to determine the underlying cause. It could be quite literally anything, but should provide direction.
An example would be that if you are connecting to a database in the constructor for your window, and for some reason that database is unavailable, the inner exception may be a TimeoutException
or a SqlException
or any other exception thrown by your database code.
If you are throwing exceptions in static constructors, the exception could be generated from any class referenced by the MainWindow
. Class initializers are also run, if any MainWindow
fields are calling a method which may throw.
For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.
So when I ran
rails generate scaffold User name:string email:string
the console showed
Usage:
rails new APP_PATH [options]
So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed
rails generate scaffold User name:string email:string
and it worked
I had the same issue.
During the 1st development I used a .csv file (comma as separator) that I've modified a bit before saving it. After saving the commas became semicolon.
On Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.
When testing from a brand new file I encountered that issue.
I've removed the 'sep' argument in read_csv method before:
df1 = pd.read_csv('myfile.csv', sep=',');
after:
df1 = pd.read_csv('myfile.csv');
That way, the issue disappeared.
As many know, there is no need for a gem.
Steps to take:
Copy
bootstrap/dist/css/bootstrap.css
bootstrap/dist/css/bootstrap.min.css
to: app/assets/stylesheets
Copy
bootstrap/dist/js/bootstrap.js
bootstrap/dist/js/bootstrap.min.js
to: app/assets/javascripts
Append to: app/assets/stylesheets/application.css
*= require bootstrap
Append to: app/assets/javascripts/application.js
//= require bootstrap
That is all. You are ready to add a new cool Bootstrap template.
Why app/
instead of vendor/
?
It is important to add the files to app/assets, so in the future you'll be able to overwrite Bootstrap styles.
If later you want to add a custom.css.scss
file with custom styles. You'll have something similar to this in application.css
:
*= require bootstrap
*= require custom
If you placed the bootstrap files in app/assets, everything works as expected. But, if you placed them in vendor/assets, the Bootstrap files will be loaded last. Like this:
<link href="/assets/custom.css?body=1" media="screen" rel="stylesheet">
<link href="/assets/bootstrap.css?body=1" media="screen" rel="stylesheet">
So, some of your customizations won't be used as the Bootstrap styles will override them.
Reason behind this
Rails will search for assets in many locations; to get a list of this locations you can do this:
$ rails console
> Rails.application.config.assets.paths
In the output you'll see that app/assets takes precedence, thus loading it first.
Here's the exact definition of UsedRange
(MSDN reference) :
Every Worksheet object has a UsedRange property that returns a Range object representing the area of a worksheet that is being used. The UsedRange property represents the area described by the farthest upper-left and farthest lower-right nonempty cells in a worksheet and includes all cells in between.
So basically, what that line does is :
.UsedRange
-> "Draws" a box around the outer-most cells with content inside..Columns
-> Selects the entire columns of those cells.Count
-> Returns an integer corresponding to how many columns there are (in this selection)- 8
-> Subtracts 8 from the previous integer.I assume VBA calculates the UsedRange by finding the non-empty cells with lowest and highest index values.
Most likely, you're getting an error because the number of lines in your range is smaller than 3, and therefore the number returned is negative.
Of course, the accepted answer of Arrays.equal( byte[] first, byte[] second ) is correct. I like to work at a lower level, but I was unable to find a low level efficient function to perform equality test ranges. I had to whip up my own, if anyone needs it:
public static boolean ArraysAreEquals(
byte[] first,
int firstOffset,
int firstLength,
byte[] second,
int secondOffset,
int secondLength
) {
if( firstLength != secondLength ) {
return false;
}
for( int index = 0; index < firstLength; ++index ) {
if( first[firstOffset+index] != second[secondOffset+index]) {
return false;
}
}
return true;
}
var params= new Dictionary<string, string>();
var url ="Please enter URLhere";
params.Add("key1", "value1");
params.Add("key2", "value2");
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(dict)).Result;
var tokne= response.Content.ReadAsStringAsync().Result;
}
//Get response as expected
replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(string,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z','')*1 AS string
,
:)
Use "javascript.validate.enable": false
in your VS Code settings, It doesn't disable ESLINT. I use both ESLINT & Flow. Simply follow the instructions Flow For Vs Code Setup
Adding this line in settings.json. Helps
"javascript.validate.enable": false
To rebase the current local tracker branch moving local changes on top of the latest remote state:
$ git fetch && git rebase
More generally, to fast-forward and drop the local changes (hard reset)*:
$ git fetch && git checkout ${the_branch_name} && git reset --hard origin/${the_branch_name}
to fast-forward and keep the local changes (rebase):
$ git fetch && git checkout ${the_branch_name} && git rebase origin/${the_branch_name}
* - to undo the change caused by unintentional hard reset first do git reflog
, that displays the state of the HEAD in reverse order, find the hash the HEAD was pointing to before the reset operation (usually obvious) and hard reset the branch to that hash.
Lots of ways to do this. The most reliable is find.
Dim rLastCell As Range
Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
MsgBox ("The last used column is: " & rLastCell.Column)
If you want to find the last column used in a particular row you can use:
Dim lColumn As Long
lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
Using used range (less reliable):
Dim lColumn As Long
lColumn = ws.UsedRange.Columns.Count
Using used range wont work if you have no data in column A. See here for another issue with used range:
See Here regarding resetting used range.
There is some other program listening on port 80, usual suspects are
Way to correct it is either shutting down the program that's using the port 80 or configure it to use a different port or configure Apache to listen on a different port with the Listen directive in httpd.conf. In the case of antivirus configure the antivirus to allow Apache to bind on the port you have chosen.
Way to diagnose which app, if any, has bound to port 80 is run the netstat with those options, look for :80 next to the local IP address (second column) and find the PID (last column). Then, on the task manager you can find which process has the PID you got in the previous step. (You might need to add the PID column on the task manager)
C:\Users\vinko>netstat -ao -p tcp
Conexiones activas
Proto Dirección local Dirección remota Estado PID
TCP 127.0.0.1:1110 127.0.0.1:51373 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51379 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51381 ESTABLISHED 388
TCP 127.0.0.1:1110 127.0.0.1:51382 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51479 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51481 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51483 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51485 ESTABLISHED 388
TCP 127.0.0.1:1110 127.0.0.1:51487 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51489 ESTABLISHED 388
TCP 127.0.0.1:51381 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:51485 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:51489 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:59264 127.0.0.1:59265 ESTABLISHED 5168
TCP 127.0.0.1:59265 127.0.0.1:59264 ESTABLISHED 5168
TCP 127.0.0.1:59268 127.0.0.1:59269 ESTABLISHED 5168
TCP 127.0.0.1:59269 127.0.0.1:59268 ESTABLISHED 5168
TCP 192.168.1.34:51278 192.168.1.33:445 ESTABLISHED 4
TCP 192.168.1.34:51383 67.199.15.132:80 ESTABLISHED 388
TCP 192.168.1.34:51486 66.102.9.18:80 ESTABLISHED 388
TCP 192.168.1.34:51490 74.125.4.20:80 ESTABLISHED 388
If you want to Disable Skype from listening on port 80 and 443, you can follow the link http://www.mydigitallife.info/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/
Null is a special object type like:
>>>type(None)
<class 'NoneType'>
You can check if an object is in class 'NoneType':
>>>variable = None
>>>variable is None
True
More information is available at Python Docs
I am doing this way:
<div class="card-logo">
<img height="100%" width="100%" src="http://someimage.jpg">
</div>
and CSS:
.card-logo {
width: 20%;
}
I prefer this way, as if I need to upscale - I can use 150% as well
If it is not a typo, as pointed out earlier, it could be wrong compiler options like compiling 64 bit under 32 bit. It must not be a toolchain.
if you are adding multiple items to the list use this:
mAdapter.notifyItemRangeInserted(startPosition, itemcount);
This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount
existing item in the dataset still considered up to date.
If the file is small, you can read the whole data once:
File file = new File("a.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String str = new String(data, "UTF-8");
I had the same issue, i realized i had deleted the default image that was in the folder just update the media missing, on the specific file
Well, @Jon Skeet, if we're not worried about getting any more granular than days (and still rolling days into larger units rather than having a total day count), as per the OP, it's really not that difficult in C#. What makes date math so difficult is that the number of units in each composite unit often changes. Imagine if every 3rd gallon of gas was only 3 quarts, but each 12th was 7, except on Fridays, when...
Luckily, dates are just a long ride through the greatest integer function. These crazy exceptions are maddening, unless you've gone all the way through the wackily-comprised unit, when it's not a big deal any more. If you're born on 12/25/1900, you're still EXACTLY 100 on 12/25/2000, regardless of the leap years or seconds or daylight savings periods you've been through. As soon as you've slogged through the percentages that make up the last composite unit, you're back to unity. You've added one, and get to start over.
Which is just to say that if you're doing years to months to days, the only strangely comprised unit is the month (of days). If you need to borrow from the month value to handle a place where you're subtracting more days than you've got, you just need to know the number of days in the previous month. No other outliers matter.
And C# gives that to you in System.DateTime.DaysInMonth(intYear, intMonth).
(If your Now month is smaller than your Then month, there's no issue. Every year has 12 months.)
And the same deal if we go more granular... you just need to know how many (small units) are in the last (composite unit). Once you're past, you get another integer value more of (composite unit). Then subtract how many small units you missed starting where you did Then and add back how many of those you went past the composite unit break-off with your Now.
So here's what I've got from my first cut at subtracting two dates. It might work. Hopefully useful.
(EDIT: Changed NewMonth > OldMonth check to NewMonth >= OldMonth, as we don't need to borrow one if the Months are the same (ditto for days). That is, Nov 11 2011 minus Nov 9 2010 was giving -1 year, 12 months, 2 days (ie, 2 days, but the royal we borrowed when royalty didn't need to.)
(EDIT: Had to check for Month = Month when we needed to borrow days to subtract a dteThen.Day from dteNow.Day & dteNow.Day < dteThen.Day, as we had to subtract a year to get 11 months and the extra days. Okay, so there are a few outliers. ;^D I think I'm close now.)
private void Form1_Load(object sender, EventArgs e) {
DateTime dteThen = DateTime.Parse("3/31/2010");
DateTime dteNow = DateTime.Now;
int intDiffInYears = 0;
int intDiffInMonths = 0;
int intDiffInDays = 0;
if (dteNow.Month >= dteThen.Month)
{
if (dteNow.Day >= dteThen.Day)
{ // this is a best case, easy subtraction situation
intDiffInYears = dteNow.Year - dteThen.Year;
intDiffInMonths = dteNow.Month - dteThen.Month;
intDiffInDays = dteNow.Day - dteThen.Day;
}
else
{ // else we need to substract one from the month diff (borrow the one)
// and days get wacky.
// Watch for the outlier of Month = Month with DayNow < DayThen, as then we've
// got to subtract one from the year diff to borrow a month and have enough
// days to subtract Then from Now.
if (dteNow.Month == dteThen.Month)
{
intDiffInYears = dteNow.Year - dteThen.Year - 1;
intDiffInMonths = 11; // we borrowed a year and broke ONLY
// the LAST month into subtractable days
// Stay with me -- because we borrowed days from the year, not the month,
// this is much different than what appears to be a similar calculation below.
// We know we're a full intDiffInYears years apart PLUS eleven months.
// Now we need to know how many days occurred before dteThen was done with
// dteThen.Month. Then we add the number of days we've "earned" in the current
// month.
//
// So 12/25/2009 to 12/1/2011 gives us
// 11-9 = 2 years, minus one to borrow days = 1 year difference.
// 1 year 11 months - 12 months = 11 months difference
// (days from 12/25 to the End Of Month) + (Begin of Month to 12/1) =
// (31-25) + (0+1) =
// 6 + 1 =
// 7 days diff
//
// 12/25/2009 to 12/1/2011 is 1 year, 11 months, 7 days apart. QED.
int intDaysInSharedMonth = System.DateTime.DaysInMonth(dteThen.Year, dteThen.Month);
intDiffInDays = intDaysInSharedMonth - dteThen.Day + dteNow.Day;
}
else
{
intDiffInYears = dteNow.Year - dteThen.Year;
intDiffInMonths = dteNow.Month - dteThen.Month - 1;
// So now figure out how many more days we'd need to get from dteThen's
// intDiffInMonth-th month to get to the current month/day in dteNow.
// That is, if we're comparing 2/8/2011 to 11/7/2011, we've got (10/8-2/8) = 8
// full months between the two dates. But then we've got to go from 10/8 to
// 11/07. So that's the previous month's (October) number of days (31) minus
// the number of days into the month dteThen went (8), giving the number of days
// needed to get us to the end of the month previous to dteNow (23). Now we
// add back the number of days that we've gone into dteNow's current month (7)
// to get the total number of days we've gone since we ran the greatest integer
// function on the month difference (23 to the end of the month + 7 into the
// next month == 30 total days. You gotta make it through October before you
// get another month, G, and it's got 31 days).
int intDaysInPrevMonth = System.DateTime.DaysInMonth(dteNow.Year, (dteNow.Month - 1));
intDiffInDays = intDaysInPrevMonth - dteThen.Day + dteNow.Day;
}
}
}
else
{
// else dteThen.Month > dteNow.Month, and we've got to amend our year subtraction
// because we haven't earned our entire year yet, and don't want an obo error.
intDiffInYears = dteNow.Year - dteThen.Year - 1;
// So if the dates were THEN: 6/15/1999 and NOW: 2/20/2010...
// Diff in years is 2010-1999 = 11, but since we're not to 6/15 yet, it's only 10.
// Diff in months is (Months in year == 12) - (Months lost between 1/1/1999 and 6/15/1999
// when dteThen's clock wasn't yet rolling == 6) = 6 months, then you add the months we
// have made it into this year already. The clock's been rolling through 2/20, so two months.
// Note that if the 20 in 2/20 hadn't been bigger than the 15 in 6/15, we're back to the
// intDaysInPrevMonth trick from earlier. We'll do that below, too.
intDiffInMonths = 12 - dteThen.Month + dteNow.Month;
if (dteNow.Day >= dteThen.Day)
{
intDiffInDays = dteNow.Day - dteThen.Day;
}
else
{
intDiffInMonths--; // subtract the month from which we're borrowing days.
// Maybe we shoulda factored this out previous to the if (dteNow.Month > dteThen.Month)
// call, but I think this is more readable code.
int intDaysInPrevMonth = System.DateTime.DaysInMonth(dteNow.Year, (dteNow.Month - 1));
intDiffInDays = intDaysInPrevMonth - dteThen.Day + dteNow.Day;
}
}
this.addToBox("Years: " + intDiffInYears + " Months: " + intDiffInMonths + " Days: " + intDiffInDays); // adds results to a rich text box.
}
I know this question is pretty old, but figured I'd share some demo code this question helped me with.
Button
and a DataGridView
Click
event for button1CellClick
event for DataGridView1EditMode
to EditProgrammatically
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataTable m_dataTable;
DataTable table { get { return m_dataTable; } set { m_dataTable = value; } }
private const string m_nameCol = "Name";
private const string m_choiceCol = "Choice";
public Form1()
{
InitializeComponent();
}
class Options
{
public int m_Index { get; set; }
public string m_Text { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
table = new DataTable();
table.Columns.Add(m_nameCol);
table.Rows.Add(new object[] { "Foo" });
table.Rows.Add(new object[] { "Bob" });
table.Rows.Add(new object[] { "Timn" });
table.Rows.Add(new object[] { "Fred" });
dataGridView1.DataSource = table;
if (!dataGridView1.Columns.Contains(m_choiceCol))
{
DataGridViewTextBoxColumn txtCol = new DataGridViewTextBoxColumn();
txtCol.Name = m_choiceCol;
dataGridView1.Columns.Add(txtCol);
}
List<Options> oList = new List<Options>();
oList.Add(new Options() { m_Index = 0, m_Text = "None" });
for (int i = 1; i < 10; i++)
{
oList.Add(new Options() { m_Index = i, m_Text = "Op" + i });
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i += 2)
{
DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
//Setup A
c.DataSource = oList;
c.Value = oList[0].m_Text;
c.ValueMember = "m_Text";
c.DisplayMember = "m_Text";
c.ValueType = typeof(string);
////Setup B
//c.DataSource = oList;
//c.Value = 0;
//c.ValueMember = "m_Index";
//c.DisplayMember = "m_Text";
//c.ValueType = typeof(int);
//Result is the same A or B
dataGridView1[m_choiceCol, i] = c;
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.Columns.IndexOf(dataGridView1.Columns[m_choiceCol]))
{
DataGridViewCell cell = dataGridView1[m_choiceCol, e.RowIndex];
dataGridView1.CurrentCell = cell;
dataGridView1.BeginEdit(true);
}
}
}
}
}
Note that the column index numbers can change from multiple button presses of button one, so I always refer to the columns by name not index value. I needed to incorporate David Hall's answer into my demo that already had ComboBoxes so his answer worked really well.
In a nutshell :
-> Git Merge: It will simply merge your local changes and remote changes, and that will create another commit history record
-> Git Rebase: It will put your changes above all new remote changes, and rewrite commit history, so your commit history will be much cleaner than git merge. Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.
Easy and simple way:
select from_unixtime(column_name, '%Y-%m-%d') from table_name
The other response shows this, but essentially you just need to create a SqlParameter
, set the Direction
to Output
, and add it to the SqlCommand
's Parameters
collection. Then execute the stored procedure and get the value of the parameter.
Using your code sample:
// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
// Create parameter with Direction as Output (and correct name and type)
SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
// Some various ways to grab the output depending on how you would like to
// handle a null value returned from the query (shown in comment for each).
// Note: You can use either the SqlParameter variable declared
// above or access it through the Parameters collection by name:
// outputIdParam.Value == cmd.Parameters["@ID"].Value
// Throws FormatException
int idFromString = int.Parse(outputIdParam.Value.ToString());
// Throws InvalidCastException
int idFromCast = (int)outputIdParam.Value;
// idAsNullableInt remains null
int? idAsNullableInt = outputIdParam.Value as int?;
// idOrDefaultValue is 0 (or any other value specified to the ?? operator)
int idOrDefaultValue = outputIdParam.Value as int? ?? default(int);
conn.Close();
}
Be careful when getting the Parameters[].Value
, since the type needs to be cast from object
to what you're declaring it as. And the SqlDbType
used when you create the SqlParameter
needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["@Param"].Value.ToString()
(either explictly or implicitly via a Console.Write()
or String.Format()
call).
EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from @Walter Stabosz and @Stephen Kennedy and to match the update code edit in the question from @abatishchev.
og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"
console.log(og_date.split('-')); // => [ '2012', '10', '01' ]
og_date.value
would only work if the date were stored as a property on the og_date object.
Such as: var og_date = {}; og_date.value="2012-10-01";
In that case, your original console.log would work.
We found out that all the standard ways of getting the total memory of the current process have some issues.
Runtime.getRuntime().totalMemory()
: returns JVM memory onlyActivityManager.getMemoryInfo()
, Process.getFreeMemory()
and anything else based on /proc/meminfo
- returns memory info about all the processes combined (e.g. android_util_Process.cpp)Debug.getNativeHeapAllocatedSize()
- uses mallinfo()
which return information about memory allocations performed by malloc()
and related functions only (see android_os_Debug.cpp)Debug.getMemoryInfo()
- does the job but it's too slow. It takes about 200ms on Nexus 6 for a single call. The performance overhead makes this function useless for us as we call it regularly and every call is quite noticeable (see android_os_Debug.cpp)ActivityManager.getProcessMemoryInfo(int[])
- calls Debug.getMemoryInfo()
internally (see ActivityManagerService.java)Finally, we ended up using the following code:
const long pageSize = 4 * 1024; //`sysconf(_SC_PAGESIZE)`
string stats = File.ReadAllText("/proc/self/statm");
var statsArr = stats.Split(new [] {' ', '\t', '\n'}, 3);
if( statsArr.Length < 2 )
throw new Exception("Parsing error of /proc/self/statm: " + stats);
return long.Parse(statsArr[1]) * pageSize;
It returns VmRSS metric. You can find more details about it here: one, two and three.
P.S. I noticed that the theme still has a lack of an actual and simple code snippet of how to estimate the private memory usage of the process if the performance isn't a critical requirement:
Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
Debug.getMemoryInfo(memInfo);
long res = memInfo.getTotalPrivateDirty();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
res += memInfo.getTotalPrivateClean();
return res * 1024L;
"Actively refused it" means that the host sent a reset instead of an ack when you tried to connect. It is therefore not a problem in your code. Either there is a firewall blocking the connection or the process that is hosting the service is not listening on that port. This may be because it is not running at all or because it is listening on a different port.
Once you start the process hosting your service, try netstat -anb
(requires admin privileges) to verify that it is running and listening on the expected port.
update: On Linux you may need to do netstat -anp
instead.
Update for Docker: use the install-plugins.sh script. It takes a list of plugin names minus the '-plugin' extension. See the description here.
install-plugins.sh replaces the deprecated plugins.sh which now warns :
WARN: plugins.sh is deprecated, please switch to install-plugins.sh
To use a plugins.txt as per plugins.sh see this issue and this workaround:
RUN /usr/local/bin/install-plugins.sh $(cat /usr/share/jenkins/plugins.txt | tr '\n' ' ')
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.
I think this will work for you.
class A(object):
def __init__(self, a, b, c, sum, version='old'):
self.a = a
self.b = b
self.c = c
self.sum = 6
self.version = version
def __int__(self):
return self.sum + 9000
def __iter__(self):
return self.__dict__.iteritems()
a = A(1,2,3,4,5)
print dict(a)
{'a': 1, 'c': 3, 'b': 2, 'sum': 6, 'version': 5}
You need to use at least Gradle 3.4 or newer to be able to use implementation
. It is not recommended to keep using the deprecated compile
since this can result in slower build times. For more details see the official android developer guide:
When your module configures an implementation dependency, it's letting Gradle know that the module does not want to leak the dependency to other modules at compile time. That is, the dependency is available to other modules only at runtime. Using this dependency configuration instead of api or compile can result in significant build time improvements because it reduces the amount of projects that the build system needs to recompile. For example, if an implementation dependency changes its API, Gradle recompiles only that dependency and the modules that directly depend on it. Most app and test modules should use this configuration.
https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#new_configurations
Update: compile
will be removed by end of 2018, so make sure that you use only implementation
now:
Warning:Configuration 'compile' is obsolete and has been replaced with 'implementation'. It will be removed at the end of 2018
This error is due to mongo driver dropping the connection for any reason (server was down for example).
By default mongoose will try to reconnect for 30 seconds then stop retrying and throw errors forever until restarted.
You can change this by editing these 2 fields in the connection options
mongoose.connect(uri,
{ server: {
// sets how many times to try reconnecting
reconnectTries: Number.MAX_VALUE,
// sets the delay between every retry (milliseconds)
reconnectInterval: 1000
}
}
);
Updated for modern versions of .NET per @1c1cle's suggestion in a comment:
<%= Html.TextBoxFor(model => Model.SomeFieldName, new {{"readonly", "true"}}) %>
Do realize that this is not a "secure" way to do this as somebody can inject javascript to change this.
Something to be aware of is that if you set that readonly
value to false
, you actually won't see any change in behavior! So if you need to drive this based on a variable, you cannot simply plug that variable in there. Instead you need to use conditional logic to simply not pass that readonly
attribute in.
Here is an untested suggestion for how to do this (if there's a problem with this, you can always do an if/else):
<%= Html.TextBoxFor(model => Model.SomeFieldName, shouldBeReadOnlyBoolean ? new {{"readonly", "true"}} : null) %>
According to BOL:
Indexed views and indexes on computed columns store results in the database for later reference. The stored results are valid only if all connections referring to the indexed view or indexed computed column can generate the same result set as the connection that created the index.
In order to create a table with a persisted, computed column, the following connection settings must be enabled:
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET NUMERIC_ROUNDABORT ON
SET QUOTED_IDENTIFIER ON
These values are set on the database level and can be viewed using:
SELECT
is_ansi_nulls_on,
is_ansi_padding_on,
is_ansi_warnings_on,
is_arithabort_on,
is_concat_null_yields_null_on,
is_numeric_roundabort_on,
is_quoted_identifier_on
FROM sys.databases
However, the SET options can also be set by the client application connecting to SQL Server.
A perfect example is SQL Server Management Studio which has the default values for SET ANSI_NULLS and SET QUOTED_IDENTIFIER both to ON. This is one of the reasons why I could not initially duplicate the error you posted.
Anyway, to duplicate the error, try this (this will override the SSMS default settings):
SET ANSI_NULLS ON
SET ANSI_PADDING OFF
SET ANSI_WARNINGS OFF
SET ARITHABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET NUMERIC_ROUNDABORT OFF
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE T1 (
ID INT NOT NULL,
TypeVal AS ((1)) PERSISTED NOT NULL
)
You can fix the test case above by using:
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
I would recommend tweaking these two settings in your script before the creation of the table and related indexes.
Try this:
par(adj = 0)
plot(1, 1, main = "Title")
or equivalent:
plot(1, 1, main = "Title", adj = 0)
adj = 0
produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1]
is allowed.
However, the issue is that this will also change the position of the label of the x-axis and y-axis.
As I'm using a laravel/php backend I tend to go with something like this:
/resource?filters[status_id]=1&filters[city]=Sydney&page=2&include=relatedResource
PHP automatically turns []
params into an array, so in this example I'll end up with a $filter
variable that holds an array/object of filters, along with a page and any related resources I want eager loaded.
If you use another language, this might still be a good convention and you can create a parser to convert []
to an array.
Never ever use for
it may cause almost untraceable bugs.
Don't be fooled, this is not about idiomatic code or style issues. Ruby's implementation of for
has a serious flaw and should not be used.
Here is an example where for
introduces a bug,
class Library
def initialize
@ary = []
end
def method_with_block(&block)
@ary << block
end
def method_that_uses_these_blocks
@ary.map(&:call)
end
end
lib = Library.new
for n in %w{foo bar quz}
lib.method_with_block { n }
end
puts lib.method_that_uses_these_blocks
Prints
quz
quz
quz
Using %w{foo bar quz}.each { |n| ... }
prints
foo
bar
quz
Why?
In a for
loop the variable n
is defined once and only and then that one definition is use for all iterations. Hence each blocks refer to the same n
which has a value of quz
by the time the loop ends. Bug!
In an each
loop a fresh variable n
is defined for each iteration, for example above the variable n
is defined three separate times. Hence each block refer to a separate n
with the correct values.
remove_indices = [1,2,3]
somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
Example:
In [9]: remove_indices = [1,2,3]
In [10]: somelist = range(10)
In [11]: somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
In [12]: somelist
Out[12]: [0, 4, 5, 6, 7, 8, 9]
Most common reason for this error is that you don't have permission to create file in the current directory. Ensure you are in the right directory. try this on mac system to list the directory
ls, then cd right_folder_name
I was having the same problem and none if these worked for me. Here is what did work though...
app.factory('myService', function($http) {
var data = function (value) {
return $http.get(value);
}
return { data: data }
});
and then the function that uses it is...
vm.search = function(value) {
var recieved_data = myService.data(value);
recieved_data.then(
function(fulfillment){
vm.tags = fulfillment.data;
}, function(){
console.log("Server did not send tag data.");
});
};
The service isn't that necessary but I think its a good practise for extensibility. Most of what you will need for one will for any other, especially when using APIs. Anyway I hope this was helpful.
Change ng-disabled="!contractTypeValid"
to [disabled]="!contractTypeValid"
CodeXL has now superseded the End Of Line'd AMD Code Analyst and both are free, but not as advanced as VTune.
There's also Sleepy, which is very simple, but does the job in many cases.
Note: All three of the tools above are unmaintained since several years.
Most of the answers here are to do the obvious check, that the length of the column as defined in the database isn't smaller than the data you are trying to pass into it.
Several times I have been bitten by going to SQL Management Studio, doing a quick:
sp_help 'mytable'
and be confused for a few minutes until I realize the column in question is an nvarchar, which means the length reported by sp_help is really double the real length supported because it's a double byte (unicode) datatype.
i.e. if sp_help reports nvarchar Length 40, you can store 20 characters max.
You are consuming a line at, which is discarded
while((str=input.readLine())!=null && str.length()!=0)
and reading a bigint at
BigInteger n = new BigInteger(input.readLine());
so try getting the bigint from string which is read as
BigInteger n = new BigInteger(str);
Constructor used: BigInteger(String val)
Aslo change while((str=input.readLine())!=null && str.length()!=0)
to
while((str=input.readLine())!=null)
see related post string to bigint
readLine()
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
see javadocs
./main.go (in package main)
./a/a.go (in package a)
./a/b.go (in package a)
in this case:
main.go import "./a"
It can call the function in the a.go and b.go,that with first letter caps on.
In my case I had Java 7 and 8 (both x64) installed and I want to redirect to java 7 but everything is set to use Java 8. Java uses the PATH environment variable:
C:\ProgramData\Oracle\Java\javapath
as the first option to look for its folder runtime (is a hidden folder). This path contains 3 symlinks that can't be edited.
In my pc, the PATH environment variable looks like this:
C:\ProgramData\Oracle\Java\javapath;C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;
In my case, It should look like this:
C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;
I had to cut and paste the symlinks to somewhere else so java can't find them, and I can restore them later.
After setting the JAVA_HOME and JRE_HOME environment variables to the desired java folders' runtimes (in my case it is Java 7), the command java -version
should show your desired java runtime. I remark there's no need to mess with the registry.
Tested on Win7 x64.
try this:
AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.None);
or
AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.RemoveEmptyEntries);
For me the problem was that I was running the migration commands inside the wrong project. Running the commands inside the project that contained the Startup.cs rather than the project that contained the DbContext allowed me to move past this particular problem.
mvn eclipse:eclipse -DdownloadSources=true
or
mvn eclipse:eclipse -DdownloadJavadocs=true
or you can add both flags, as Spencer K points out.
Additionally, the =true
portion is not required, so you can use
mvn eclipse:eclipse -DdownloadSources -DdownloadJavadocs
These are Unicode property shortcuts (\p{L}
for Unicode letters, \p{N}
for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)
At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:
[\p{L}\p{N}_.-]*
Edit you AssemblyInfo.cs and #if !NETCOREAPP3_0 ... #endif
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
#if !NETCOREAPP3_0
[assembly: AssemblyTitle(".Net Core Testing")]
[assembly: AssemblyDescription(".Net Core")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct(".Net Core")]
[assembly: AssemblyCopyright("Copyright ©")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("000b119c-2445-4977-8604-d7a736003d34")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
#endif
Try this code:
isNaN(parseFloat("geoff"))
For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
**Custom checkbox with css** (WebKit browser solution only Chrome, Safari, Mobile browsers)
<input type="checkbox" id="cardAccptance" name="cardAccptance" value="Yes">
<label for="cardAccptance" class="bold"> Save Card for Future Use</label>
/* The checkbox-cu */
.checkbox-cu {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 0;
cursor: pointer;
font-size: 16px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default checkbox-cu */
.checkbox-cu input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
/* Create a custom checkbox-cu */
.checkmark {
position: absolute;
top: 4px;
left: 0;
height: 20px;
width: 20px;
background-color: #eee;
border: 1px solid #999;
border-radius: 0;
box-shadow: none;
}
/* On mouse-over, add a grey background color */
.checkbox-cu:hover input~.checkmark {
background-color: #ccc;
}
/* When the checkbox-cu is checked, add a blue background */
.checkbox-cu input:checked~.checkmark {
background-color: transparent;
}
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the checkmark when checked */
.checkbox-cu input:checked~.checkmark:after {
display: block;
}
/* Style the checkmark/indicator */
.checkbox-cu .checkmark::after {
left: 7px;
top: 3px;
width: 6px;
height: 9px;
border: solid #28a745;
border-width: 0 2px 2px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
z-index: 100;
}
maybe you want ifelse
:
a <- c(1,1,1,1,0,0,0,0,2,2)
ifelse(a>0,a/sum(a),1)
[1] 0.125 0.125 0.125 0.125 1.000 1.000 1.000 1.000
[9] 0.250 0.250
No.
First off, append
is a function, so you can't write append[i+1:i+4]
because you're trying to get a slice of a thing that isn't a sequence. (You can't get an element of it, either: append[i+1]
is wrong for the same reason.) When you call a function, the argument goes in parentheses, i.e. the round ones: ()
.
Second, what you're trying to do is "take a sequence, and put every element in it at the end of this other sequence, in the original order". That's spelled extend
. append
is "take this thing, and put it at the end of the list, as a single item, even if it's also a list". (Recall that a list is a kind of sequence.)
But then, you need to be aware that i+1:i+4
is a special construct that appears only inside square brackets (to get a slice from a sequence) and braces (to create a dict
object). You cannot pass it to a function. So you can't extend
with that. You need to make a sequence of those values, and the natural way to do this is with the range
function.
It does not need its own controller. You can use
@Html.Partial("../ControllerName/_Testimonials.cshtml")
This allows you to render the partial from any page. Just make sure the relative path is correct.
Besides escaping the character, you can also use the format %c
, and use the character literal for a quotation mark.
printf("And I quote, %cThis is a quote.%c\n", '"', '"');
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
Remove @ResponseBody annotation from your use parameters in method. Like this;
@Autowired
ProjectService projectService;
@RequestMapping(path = "/add", method = RequestMethod.POST)
public ResponseEntity<Project> createNewProject(Project newProject){
Project project = projectService.save(newProject);
return new ResponseEntity<Project>(project,HttpStatus.CREATED);
}
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
git checkout master -go to the master branch first
git checkout <your-branch> -- <your-file> --copy your file data from your branch.
git show <your-branch>:path/to/<your-file>
Hope this will help you. Please let me know If you have any query.
from lxml import etree
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('path of your localfile.html'),'html.parser')
dom = etree.HTML(str(soup))
print dom.xpath('//*[@id="BGINP01_S1"]/section/div/font/text()')
Above used the combination of Soup object with lxml and one can extract the value using xpath
Three flavors of my old SwissKnife library: relname_exists(anyThing)
, relname_normalized(anyThing)
and relnamechecked_to_array(anyThing)
. All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).
/**
* From my old SwissKnife Lib to your SwissKnife. License CC0.
* Check and normalize to array the free-parameter relation-name.
* Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
*/
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
SELECT array[n.nspname::text, c.relname::text]
FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
WHERE CASE
WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1] AND c.relname = x[2]
WHEN $2 IS NULL THEN n.nspname = 'public' AND c.relname = $1
ELSE n.nspname = $2 AND c.relname = $1
END
$f$ language SQL IMMUTABLE;
CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;
CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;
Of course it is possible to restart a Java application.
The following method shows a way to restart a Java application:
public void restartApplication()
{
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = new File(MyClassInTheJar.class.getProtectionDomain().getCodeSource().getLocation().toURI());
/* is it a jar file? */
if(!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
builder.start();
System.exit(0);
}
Basically it does the following:
MyClassInTheJar
class to find the jar location itself)The way to do this is near the top of the man page
grep -i -A 10 'error data'
I was able to solve it by running
git config --list --show-origin
and then seeing that I had a line:
file:c:/Users/user/.gitconfig http.sslversion=sslv3
I edited the file, c:/Users/user/.gitconfig, and deleted the line [http] and the line sslversion=sslv3 and that fixed it for me.
Nobody has explained the difference between ExceptionDispatchInfo.Capture( ex ).Throw()
and a plain throw
, so here it is. However, some people have noticed the problem with throw
.
The complete way to rethrow a caught exception is to use ExceptionDispatchInfo.Capture( ex ).Throw()
(only available from .Net 4.5).
Below there are the cases necessary to test this:
1.
void CallingMethod()
{
//try
{
throw new Exception( "TEST" );
}
//catch
{
// throw;
}
}
2.
void CallingMethod()
{
try
{
throw new Exception( "TEST" );
}
catch( Exception ex )
{
ExceptionDispatchInfo.Capture( ex ).Throw();
throw; // So the compiler doesn't complain about methods which don't either return or throw.
}
}
3.
void CallingMethod()
{
try
{
throw new Exception( "TEST" );
}
catch
{
throw;
}
}
4.
void CallingMethod()
{
try
{
throw new Exception( "TEST" );
}
catch( Exception ex )
{
throw new Exception( "RETHROW", ex );
}
}
Case 1 and case 2 will give you a stack trace where the source code line number for the CallingMethod
method is the line number of the throw new Exception( "TEST" )
line.
However, case 3 will give you a stack trace where the source code line number for the CallingMethod
method is the line number of the throw
call. This means that if the throw new Exception( "TEST" )
line is surrounded by other operations, you have no idea at which line number the exception was actually thrown.
Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception.
Short Answer:
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/{USER_NAME}/{REPOSITORY_NAME}.git
git push --set-upstream origin master
Ignore first three lines if it's not a new repository.
Longer description:
Just had the same problem, as non of the above answers helped me, I have decided to post this solution that worked for me.
Few Notes:
As the command line tool I used GitShell (for Windows, I use Terminal.app on Mac).
GitShell is official GitHub tool, can be downloaded from https://windows.github.com/
Hope this helps to anyone who has the same problem.
Another way to accomplish this is with the jq "--arg" flag. Using the original example:
#!/bin/sh
#this works ***
projectID=$(cat file.json | jq -r '.resource[] |
select(.username=="[email protected]") | .id')
echo "$projectID"
[email protected]
# Use --arg to pass the variable to jq. This should work:
projectID=$(cat file.json | jq --arg EMAILID $EMAILID -r '.resource[]
| select(.username=="$EMAILID") | .id')
echo "$projectID"
See here, which is where I found this solution: https://github.com/stedolan/jq/issues/626
Since no one mentioned, here is another one: Feign, which is used by Spring Cloud.
As Dave Webb mentions, the Android Developer Blog has an article that covers this. Their preferred solution is to track app installs rather than devices, and that will work well for most use cases. The blog post will show you the necessary code to make that work, and I recommend you check it out.
However, the blog post goes on to discuss solutions if you need a device identifier rather than an app installation identifier. I spoke with someone at Google to get some additional clarification on a few items in the event that you need to do so. Here's what I discovered about device identifiers that's NOT mentioned in the aforementioned blog post:
Based on Google's recommendations, I implemented a class that will generate a unique UUID for each device, using ANDROID_ID as the seed where appropriate, falling back on TelephonyManager.getDeviceId() as necessary, and if that fails, resorting to a randomly generated unique UUID that is persisted across app restarts (but not app re-installations).
Note that for devices that have to fallback on the device ID, the unique ID WILL persist across factory resets. This is something to be aware of. If you need to ensure that a factory reset will reset your unique ID, you may want to consider falling back directly to the random UUID instead of the device ID.
Again, this code is for a device ID, not an app installation ID. For most situations, an app installation ID is probably what you're looking for. But if you do need a device ID, then the following code will probably work for you.
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class DeviceUuidFactory {
protected static final String PREFS_FILE = "device_id.xml";
protected static final String PREFS_DEVICE_ID = "device_id";
protected static UUID uuid;
public DeviceUuidFactory(Context context) {
if( uuid ==null ) {
synchronized (DeviceUuidFactory.class) {
if( uuid == null) {
final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
final String id = prefs.getString(PREFS_DEVICE_ID, null );
if (id != null) {
// Use the ids previously computed and stored in the prefs file
uuid = UUID.fromString(id);
} else {
final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
// Use the Android ID unless it's broken, in which case fallback on deviceId,
// unless it's not available, then fallback on a random number which we store
// to a prefs file
try {
if (!"9774d56d682e549c".equals(androidId)) {
uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
} else {
final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// Write the value out to the prefs file
prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
}
}
}
}
}
/**
* Returns a unique UUID for the current android device. As with all UUIDs, this unique ID is "very highly likely"
* to be unique across all Android devices. Much more so than ANDROID_ID is.
*
* The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
* TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
* on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
* usable value.
*
* In some rare circumstances, this ID may change. In particular, if the device is factory reset a new device ID
* may be generated. In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
* to a newer, non-buggy version of Android, the device ID may change. Or, if a user uninstalls your app on
* a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
*
* Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
* change after a factory reset. Something to be aware of.
*
* Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
*
* @see http://code.google.com/p/android/issues/detail?id=10603
*
* @return a UUID that may be used to uniquely identify your device for most purposes.
*/
public UUID getDeviceUuid() {
return uuid;
}
}
The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let
, const
, and var
can all be used for this type of assignment.
let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false);
There are several other ways, besides using the in
operator (easiest):
index()
>>> try:
... "xxxxABCDyyyy".index("test")
... except ValueError:
... print "not found"
... else:
... print "found"
...
not found
find()
>>> if "xxxxABCDyyyy".find("ABCD") != -1:
... print "found"
...
found
re
>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
... print "found"
...
found
The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize queue
to null when you declare it.
Queue queue = null;
To include an external Javascript file you use the <script>
tag. The src
attribute points to the location of your Javascript file within your web project.
<script src="some.js" type="text/javascript"></script>
JQuery is simply a Javascript file, so if you download a copy of the file you can include it within your page using a script tag. You can also include Jquery from a content distribution network such as the one hosted by Google.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>