BorderLayout(int Gap, int Gap)
or GridLayout(int Gap, int Gap, int Gap, int Gap)
why paint Border() inside paintComponent( ...)
Border line, raisedbevel, loweredbevel, title, empty;
line = BorderFactory.createLineBorder(Color.black);
raisedbevel = BorderFactory.createRaisedBevelBorder();
loweredbevel = BorderFactory.createLoweredBevelBorder();
title = BorderFactory.createTitledBorder("");
empty = BorderFactory.createEmptyBorder(4, 4, 4, 4);
Border compound = BorderFactory.createCompoundBorder(empty, xxx);
Color crl = (Color.blue);
Border compound1 = BorderFactory.createCompoundBorder(empty, xxx);
Yield can be used as nameless block to return a value in the method. Consider the following code:
Def Up(anarg)
yield(anarg)
end
You can create a method "Up" which is assigned one argument. You can now assign this argument to yield which will call and execute an associated block. You can assign the block after the parameter list.
Up("Here is a string"){|x| x.reverse!; puts(x)}
When the Up method calls yield, with an argument, it is passed to the block variable to process the request.
Simple seven step to solve issue in case of WampServer:
Execute Statement
SET PASSWORD FOR root@localhost=PASSWORD('root');
open D:\wamp\apps\phpmyadmin4.1.14\config.inc.php file set value
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = '';
Restart All services
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];
What version of SQL Server are you using? In SQL Server 2008 you can use Table Parameters and Table Types.
An alternative approach is to return a table variable from a user defined function but I am not a big fan of this method.
You can find an example here
You can try Salar.Bois serializer which has a decent performance. Its focus is on payload size but it also offers good performance.
There are benchmarks in the Github page if you wish to see and compare the results by yourself.
When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:
Class.h
class DataManager
{
public:
bool hasData;
void getData();
bool dataAvailable();
};
Class.cpp
#include "DataManager.h"
void DataManager::getData()
{
// perform background data munging
hasData = true;
// be sure to notify on the main thread
}
bool DataManager::dataAvailable()
{
if (hasData)
{
return true;
}
else
{
std::thread t(&DataManager::getData, this);
t.detach(); // as opposed to .join, which runs on the current thread
}
}
Note that this example doesn't get into mutex or locking.
The format defined in RFC2617 is credentials = auth-scheme #auth-param
. So, in agreeing with fumanchu, I think the corrected authorization scheme would look like
Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg="
Where FIRE-TOKEN
is the scheme and the two key-value pairs are the auth parameters. Though I believe the quotes are optional (from Apendix B of p7-auth-19)...
auth-param = token BWS "=" BWS ( token / quoted-string )
I believe this fits the latest standards, is already in use (see below), and provides a key-value format for simple extension (if you need additional parameters).
Some examples of this auth-param syntax can be seen here...
http://tools.ietf.org/html/draft-ietf-httpbis-p7-auth-19#section-4.4
https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin
https://developers.google.com/accounts/docs/AuthSub#WorkingAuthSub
This works on Android Studio 1.x:
A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:
t = Guide.arel_table Guide.where(t[:title].matches('%attack'))
Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.
If you have it available, using curl is your best option.
You can see if it is enabled by doing phpinfo()
and searching the page for curl.
If it is enabled, try this:
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, SITE_PATH . 'cms/data.php');
$xml_file = curl_exec($curl_handle);
curl_close($curl_handle);
xml was not in the WEB-INF folder, thats why i was getting this error, make sure that web.xml and xxx-servlet.xml is inside WEB_INF folder and not in the webapp folder .
Method distinct is an intermediate operation that filters the stream and allows only distinct values (by default using the Object::equals method) to pass to the next operation.
I wrote an example below for your case,
// Create the list with duplicates.
List<String> listAll = Arrays.asList("CO2", "CH4", "SO2", "CO2", "CH4", "SO2", "CO2", "CH4", "SO2");
// Create a list with the distinct elements using stream.
List<String> listDistinct = listAll.stream().distinct().collect(Collectors.toList());
// Display them to terminal using stream::collect with a build in Collector.
String collectAll = listAll.stream().collect(Collectors.joining(", "));
System.out.println(collectAll); //=> CO2, CH4, SO2, CO2, CH4 etc..
String collectDistinct = listDistinct.stream().collect(Collectors.joining(", "));
System.out.println(collectDistinct); //=> CO2, CH4, SO2
You can use a function comparator without wrapping it like so:
bool comparator(const MyType &lhs, const MyType &rhs)
{
return [...];
}
std::set<MyType, bool(*)(const MyType&, const MyType&)> mySet(&comparator);
which is irritating to type out every time you need a set of that type, and can cause issues if you don't create all sets with the same comparator.
Go to Tools->Options->Text Editor->c#->Advanced and uncheck the first checkbox Enter outlining mode when files open.
This will solve this problem forever
If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!
int length = 0;
length += sprintf(Buffer+length, "Hello World");
length += sprintf(Buffer+length, "Good Morning");
length += sprintf(Buffer+length, "Good Afternoon");
Here is a version with some resistance to errors. It is useful if you do not care when errors happen so long as you can continue along your merry way when they do.
int bytes_added( int result_of_sprintf )
{
return (result_of_sprintf > 0) ? result_of_sprintf : 0;
}
int length = 0;
length += bytes_added(sprintf(Buffer+length, "Hello World"));
length += bytes_added(sprintf(Buffer+length, "Good Morning"));
length += bytes_added(sprintf(Buffer+length, "Good Afternoon"));
Struggled with the same problem: Many applications, BUT make at least this part "pleasant": The trick is called Batch-Uninstall
.
So use one of these three programs i can recommend:
Take no.2 in imho, 1 is nice but sometimes encounters some bugs :-)
Since you're using bash, the fastest way would be:
shopt -s extglob # Allow extended globbing
var=" lakdjsf lkadsjf "
echo "${var//+([[:space:]])/}"
It's fastest because it uses built-in functions instead of firing up extra processes.
However, if you want to do it in a POSIX-compliant way, use sed
:
var=" lakdjsf lkadsjf "
echo "$var" | sed 's/[[:space:]]//g'
The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.
This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.
As of September 2016 (VSCode 1.6), this is now officially supported.
Add the following to your settings.json
file:
"editor.formatOnSave": true
It can also be done with a positive assertion of removal, like this:
textContent = textContent.replace(/[\u{0080}-\u{FFFF}]/gu,"");
This uses unicode. In Javascript, when expressing unicode for a regular expression, the characters are specified with the escape sequence \u{xxxx}
but also the flag 'u'
must present; note the regex has flags 'gu'
.
I called this a "positive assertion of removal" in the sense that a "positive" assertion expresses which characters to remove, while a "negative" assertion expresses which letters to not remove. In many contexts, the negative assertion, as stated in the prior answers, might be more suggestive to the reader. The circumflex "^
" says "not" and the range \x00-\x7F
says "ascii," so the two together say "not ascii."
textContent = textContent.replace(/[^\x00-\x7F]/g,"");
That's a great solution for English language speakers who only care about the English language, and its also a fine answer for the original question. But in a more general context, one cannot always accept the cultural bias of assuming "all non-ascii is bad." For contexts where non-ascii is used, but occasionally needs to be stripped out, the positive assertion of Unicode is a better fit.
A good indication that zero-width, non printing characters are embedded in a string is when the string's "length" property is positive (nonzero), but looks like (i.e. prints as) an empty string. For example, I had this showing up in the Chrome debugger, for a variable named "textContent":
> textContent
""
> textContent.length
7
This prompted me to want to see what was in that string.
> encodeURI(textContent)
"%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B"
This sequence of bytes seems to be in the family of some Unicode characters that get inserted by word processors into documents, and then find their way into data fields. Most commonly, these symbols occur at the end of a document. The zero-width-space "%E2%80%8B"
might be inserted by CK-Editor (CKEditor).
encodeURI() UTF-8 Unicode html Meaning
----------- -------- ------- ------- -------------------
"%E2%80%8B" EC 80 8B U 200B ​ zero-width-space
"%E2%80%8E" EC 80 8E U 200E ‎ left-to-right-mark
"%E2%80%8F" EC 80 8F U 200F ‏ right-to-left-mark
Some references on those:
http://www.fileformat.info/info/unicode/char/200B/index.htm
https://en.wikipedia.org/wiki/Left-to-right_mark
Note that although the encoding of the embedded character is UTF-8, the encoding in the regular expression is not. Although the character is embedded in the string as three bytes (in my case) of UTF-8, the instructions in the regular expression must use the two-byte Unicode. In fact, UTF-8 can be up to four bytes long; it is less compact than Unicode because it uses the high bit (or bits) to escape the standard ascii encoding. That's explained here:
error MSB6006: "cmd.exe"
exited with code -Solved
I also face this problem . In my case it is due to output exe
already running .I solved my problem simply close the application instance before building.
Use StringBuilder
class. It is more efficient at what you are trying to do.
Assuming you want a field length of 2 with leading zeros you'd do this:
import Foundation
for myInt in 1 ... 3 {
print(String(format: "%02d", myInt))
}
output:
01 02 03
This requires import Foundation
so technically it is not a part of the Swift language but a capability provided by the Foundation
framework. Note that both import UIKit
and import Cocoa
include Foundation
so it isn't necessary to import it again if you've already imported Cocoa
or UIKit
.
The format string can specify the format of multiple items. For instance, if you are trying to format 3
hours, 15
minutes and 7
seconds into 03:15:07
you could do it like this:
let hours = 3
let minutes = 15
let seconds = 7
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))
output:
03:15:07
Refer the below link.
There are two important changes that you should make
driver name as "com.microsoft.sqlserver.jdbc.SQLServerDriver"
& in URL "jdbc:sqlserver://localhost:1433"+";databaseName=AdventureWorks2008R2"
I note you suggested this formula
=IF(ISNUMBER(FIND("RuhrP";F9));LOOKUP(A9;Ruhrpumpen!A$5:A$100;Ruhrpumpen!I$5:I$100);"")
.....but LOOKUP
isn't appropriate here because I assume you want an exact match (LOOKUP won't guarantee that and also data in lookup range has to be sorted), so VLOOKUP
or INDEX/MATCH
would be better....and you can also use IFERROR to avoid the IF function, i.e
=IFERROR(VLOOKUP(A9;Ruhrpumpen!A$5:Z$100;9;0);"")
Note: VLOOKUP always looks up the lookup value (A9) in the first column of the "table array" and returns a value from the nth column of the "table array" where n is defined by col_index_num, in this case 9
INDEX/MATCH is sometimes more flexible because you can explicitly define the lookup column and the return column (and return column can be to the left of the lookup column which can't be the case in VLOOKUP), so that would look like this:
=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH(A9;Ruhrpumpen!A$5:A$100;0));"")
INDEX/MATCH also allows you to more easily return multiple values from different columns, e.g. by using $ signs in front of A9 and the lookup range Ruhrpumpen!A$5:A$100, i.e.
=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH($A9;Ruhrpumpen!$A$5:$A$100;0));"")
this version can be dragged across to get successive values from column I, column J, column K etc.....
I'm pretty sure you only have to register MappingJacksonHttpMessageConverter
(the easiest way to do that is through <mvc:annotation-driven />
in XML or @EnableWebMvc
in Java)
See:
Here's a working example:
Maven POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version><name>json test</name>
<dependencies>
<dependency><!-- spring mvc -->
<groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
</dependency>
<dependency><!-- jackson -->
<groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
</dependency>
</dependencies>
<build><plugins>
<!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
<!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
<version>7.4.0.v20110414</version></plugin>
</plugins></build>
</project>
in folder src/main/webapp/WEB-INF
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet><servlet-name>json</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>json</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
json-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:mvc-context.xml" />
</beans>
in folder src/main/resources:
mvc-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="test.json" />
</beans>
In folder src/main/java/test/json
TestController.java
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(method = RequestMethod.POST, value = "math")
@ResponseBody
public Result math(@RequestBody final Request request) {
final Result result = new Result();
result.setAddition(request.getLeft() + request.getRight());
result.setSubtraction(request.getLeft() - request.getRight());
result.setMultiplication(request.getLeft() * request.getRight());
return result;
}
}
Request.java
public class Request implements Serializable {
private static final long serialVersionUID = 1513207428686438208L;
private int left;
private int right;
public int getLeft() {return left;}
public void setLeft(int left) {this.left = left;}
public int getRight() {return right;}
public void setRight(int right) {this.right = right;}
}
Result.java
public class Result implements Serializable {
private static final long serialVersionUID = -5054749880960511861L;
private int addition;
private int subtraction;
private int multiplication;
public int getAddition() { return addition; }
public void setAddition(int addition) { this.addition = addition; }
public int getSubtraction() { return subtraction; }
public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
public int getMultiplication() { return multiplication; }
public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}
You can test this setup by executing mvn jetty:run
on the command line, and then sending a POST request:
URL: http://localhost:8080/test/math
mime type: application/json
post body: { "left": 13 , "right" : 7 }
I used the Poster Firefox plugin to do this.
Here's what the response looks like:
{"addition":20,"subtraction":6,"multiplication":91}
Here is an example:
List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2
just want to add TFS MSBuild does not support special characters on folders i.e. "@"
i had experienced in the past where one of our project folders named as External@Project1
we created a TFS Build definition to run a custom msbuild file then the workspace folder is not getting any contents at the External@Project1 folder during workspace get latest. It seems that tfs get is failing but does not show any error.
after some trial and error and renaming the folder to _Project1. voila we got files on the the folder (_Project1).
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
you just need to divide the Date Time stamp by 1000 like:
var a = 1437203995000;
a = (a)/1000;
Or you could just use dynamic allocation, e.g.:
struct name {
char *first;
char *last;
};
struct name sara;
sara.first = "Sara";
sara.last = "Black";
printf("first: %s, last: %s\n", sara.first, sara.last);
In my case, I was using spring boot version 2.3.0. When I changed my maven dependency to use 2.1.3 it worked.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
</dependencies>
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
You can try with
.appBackground {
position: relative;
background-image: url(".../img/background.jpg");
background-repeat:no-repeat;
background-size:100% 100vh;
}
works for me :)
// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(GentEFONRFFConnection);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("your Procedure Name", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@orgid", SqlDbType.UniqueIdentifier).Value = orgid;
myCommand.Parameters.Add("@statid", SqlDbType.UniqueIdentifier).Value = statid;
myCommand.Parameters.Add("@read", SqlDbType.Bit).Value = read;
myCommand.Parameters.Add("@write", SqlDbType.Bit).Value = write;
// Mark the Command as a SPROC
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConnection.Close();
The easiest way is:
File.WriteAllText(path, string.Empty)
However, I recommend you use FileStream
because the first solution can throw UnauthorizedAccessException
using(FileStream fs = File.Open(path,FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
lock(fs)
{
fs.SetLength(0);
}
}
I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.
The .gitignore
file should be in your repository, so it should indeed be added and committed in, as git status
suggests. It has to be a part of the repository tree, so that changes to it can be merged and so on.
So, add it to your repository, it should not be gitignored.
If you really want you can add .gitignore
to the .gitignore
file if you don't want it to be committed. However, in that case it's probably better to add the ignores to .git/info/exclude
, a special checkout-local file that works just like .gitignore but does not show up in "git status" since it's in the .git
folder.
using System.IO;
...
Directory.CreateDirectory(@"C:\MP_Upload");
Directory.CreateDirectory does exactly what you want: It creates the directory if it does not exist yet. There's no need to do an explicit check first.
Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.
(This also means that all directories along the path are created if needed: CreateDirectory(@"C:\a\b\c\d")
suffices, even if C:\a
does not exist yet.)
Let me add a word of caution about your choice of directory, though: Creating a folder directly below the system partition root C:\
is frowned upon. Consider letting the user choose a folder or creating a folder in %APPDATA%
or %LOCALAPPDATA%
instead (use Environment.GetFolderPath for that). The MSDN page of the Environment.SpecialFolder enumeration contains a list of special operating system folders and their purposes.
In VS 2012, I was getting "SMB2 will not build: Error 1 error MSB8020: The builds tools for Visual Studio 2010 (Platform Toolset = 'v100') cannot be found. To build using the v100 build tools, either click the Project menu or right-click the solution, and then select "Update VC++ Projects...". Install Visual Studio 2010 to build using the Visual Studio 2010 build tools."
Throwing caution to the wind, I tried the suggestion: Selected the Solution in Solution Explorer, then clicked in the "Update VC++" menu item. This did some updateing and then started a build which succeeded.
The "Update VC++" menu item no longer appears in the solution menu.
I had a problem with implementing the code until I found some website (I can't find it again right now) that explained that you need to include the package name in the name of the intent.putExtra.
It would pull up the application, but it wouldn't recognize any barcodes, and when I changed it from.
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
to
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
It worked great. Just a tip for any other novice Android programmers.
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line\n")
or
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")
If you are working with numbers and f(A(i,j)) = f(A(j,i))
, you could use scipy.spatial.distance.cdist defining f as a distance between A(i)
and A(j)
.
Yes, you could use a transparent div positioned over the iframe area, with a loader gif as only background.
Then you can attach an onload
event to the iframe:
$(document).ready(function() {
$("iframe#id").load(function() {
$("#loader-id").hide();
});
});
You can proceed as follows to check whether a JToken Value is null
JToken token = jObject["key"];
if(token.Type == JTokenType.Null)
{
// Do your logic
}
Define what GetData is. At the moment it is not defined.
Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant
arc4random_uniform()
Usage:
arc4random_uniform(someNumber: UInt32) -> UInt32
This gives you random integers in the range 0
to someNumber - 1
.
The maximum value for UInt32
is 4,294,967,295 (that is, 2^32 - 1
).
Examples:
Coin flip
let flip = arc4random_uniform(2) // 0 or 1
Dice roll
let roll = arc4random_uniform(6) + 1 // 1...6
Random day in October
let day = arc4random_uniform(31) + 1 // 1...31
Random year in the 1990s
let year = 1990 + arc4random_uniform(10)
General form:
let number = min + arc4random_uniform(max - min + 1)
where number
, max
, and min
are UInt32
.
arc4random()
You can also get a random number by using arc4random()
, which produces a UInt32
between 0 and 2^32-1. Thus to get a random number between 0
and x-1
, you can divide it by x
and take the remainder. Or in other words, use the Remainder Operator (%):
let number = arc4random() % 5 // 0...4
However, this produces the slight modulo bias (see also here and here), so that is why arc4random_uniform()
is recommended.
Converting to and from Int
Normally it would be fine to do something like this in order to convert back and forth between Int
and UInt32
:
let number: Int = 10
let random = Int(arc4random_uniform(UInt32(number)))
The problem, though, is that Int
has a range of -2,147,483,648...2,147,483,647
on 32 bit systems and a range of -9,223,372,036,854,775,808...9,223,372,036,854,775,807
on 64 bit systems. Compare this to the UInt32
range of 0...4,294,967,295
. The U
of UInt32
means unsigned.
Consider the following errors:
UInt32(-1) // negative numbers cause integer overflow error
UInt32(4294967296) // numbers greater than 4,294,967,295 cause integer overflow error
So you just need to be sure that your input parameters are within the UInt32
range and that you don't need an output that is outside of that range either.
For future reference, I have to include the HTML5 way to do this.
<input name="Email" type="text" id="Email" value="[email protected]" placeholder="What's your programming question ? be specific." />
If you have a HTML5 doctype and a HTML5-compliant browser, this will work. However, many browsers do not currently support this, so at least Internet Explorer users will not be able to see your placeholder. However, see http://www.kamikazemusic.com/quick-tips/jquery-html5-placeholder-fix/ (archive.org version) for a solution. Using that, you'll be very modern and standards-compliant, while also providing the functionality to most users.
Also, the provided link is a well-tested and well-developed solution, which should work out of the box.
Django 1.11 delete all objects from a database table -
Entry.objects.all().delete() ## Entry being Model Name.
Refer the Official Django documentation here as quoted below - https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects
Note that delete() is the only QuerySet method that is not exposed on a Manager itself. This is a safety mechanism to prevent you from accidentally requesting Entry.objects.delete(), and deleting all the entries. If you do want to delete all the objects, then you have to explicitly request a complete query set:
I myself tried the code snippet seen below within my somefilename.py
# for deleting model objects
from django.db import connection
def del_model_4(self):
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(model_4)
and within my views.py
i have a view that simply renders a html page ...
def data_del_4(request):
obj = calc_2() ##
obj.del_model_4()
return render(request, 'dc_dash/data_del_4.html') ##
it ended deleting all entries from - model == model_4 , but now i get to see a Error screen within Admin console when i try to asceratin that all objects of model_4 have been deleted ...
ProgrammingError at /admin/dc_dash/model_4/
relation "dc_dash_model_4" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "dc_dash_model_4"
Do consider that - if we do not go to the ADMIN Console and try and see objects of the model - which have been already deleted - the Django app works just as intended.
We're planning to use FitNesse, with the RestFixture. We haven't started writing our tests yet, our newest tester got things up and running last week, however he has used FitNesse for this in his last company, so we know it's a reasonable setup for what we want to do.
More info available here: http://smartrics.blogspot.com/2008/08/get-fitnesse-with-some-rest.html
People, note that if you will use ~/.bash_profile
then it will edit not your user's bash profile, but global. Instead go to your users directory (/Users/username) and edit it directly:
vim .bash_profile
And insert following two lines with respect to your Username and SDK directory
export PATH=$PATH:/Users/<username>/Library/Android/sdk/tools
export PATH=$PATH:/Users/<username>/Library/Android/sdk/platform-tools
this:
element.setAttribute("onclick", alert("blabla"));
should be:
element.onclick = function () {
alert("blabla");
}
Because you call alert instead push alert as string in attribute
Actually even font-awesome
CSS has a similar strategy for setting their icon styles. If you want to get a quick hold of the icon
code, check the non-minified font-awesome.css
file and there they are....each font in its purity.
USE:
>>> a[[0,1,3]][:,[0,2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
OR:
>>> a[[0,1,3],::2]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
I also met the case to use both python2 and python3 on my Windows machine. Here's how i resolved it:
C:\Python35;C:\Python35\Scripts;C:\Python27;C:\Python27\Scripts
to environment variable PATH
.C:\Python35
to rename python.exe
to python3.exe
, also to C:\Python27
, rename python.exe
to python2.exe
.python2 scriptname.py
, or python3 scriptname.py
in command line to switch the version you like.If you are using nodejs
, in your package.json
under scripts
global (-g)
installations: "test": "mocha server-test"
or "test": "mocha server-test/**/*.js"
for subdocumentsproject
installations: "test": "node_modules/mocha/bin/mocha server-test"
or "test": "node_modules/mocha/bin/mocha server-test/**/*.js"
for subdocumentsThen just run your tests normally as npm test
change this line
for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){
to
for(int a = 0, b = 1; a<cards.length-1, b=a+1; a++){
I work with CentOS 7 servers on which I don't have root access, nor git, svn, etc (nor want to!) so made a python script to download any github folder: https://github.com/andrrrl/github-folder-downloader
Usage is simple, just copy the relevant part from a github project, let's say the project is https://github.com/MaxCDN/php-maxcdn/, and you want a folder where some source files are only, then you need to do something like:
$ python gdownload.py "/MaxCDN/php-maxcdn/tree/master/src" /my/target/dir/
(will create target folder if doesn't exist)
It requires lxml library, can be installed with easy_install lxml
If you don't have root access (like me) you can create a .pydistutils.py
file into your $HOME
dir with these contents:
[install]
user=1
And easy_install lxml
will just work (ref: https://stackoverflow.com/a/33464597/591257).
He're is simplier solution, works fine in my app.
public class MyActivity extends Acitivity {
TextView myTextView;
boolean someCondition=true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
myTextView = (TextView) findViewById(R.id.refreshing_field);
//starting our task which update textview every 1000 ms
new RefreshTask().execute();
}
//class which updates our textview every second
class RefreshTask extends AsyncTask {
@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
String text = String.valueOf(System.currentTimeMillis());
myTextView.setText(text);
}
@Override
protected Object doInBackground(Object... params) {
while(someCondition) {
try {
//sleep for 1s in background...
Thread.sleep(1000);
//and update textview in ui thread
publishProgress();
} catch (InterruptedException e) {
e.printStackTrace();
};
return null;
}
}
}
Most of the examples above show how to reuse an existing comparable object in the compareTo function. If you would like to implement your own compareTo when you want to compare two objects of the same class, say an AirlineTicket object that you would like to sort by price(less is ranked first), followed by number of stopover (again, less is ranked first), you would do the following:
class AirlineTicket implements Comparable<Cost>
{
public double cost;
public int stopovers;
public AirlineTicket(double cost, int stopovers)
{
this.cost = cost; this.stopovers = stopovers ;
}
public int compareTo(Cost o)
{
if(this.cost != o.cost)
return Double.compare(this.cost, o.cost); //sorting in ascending order.
if(this.stopovers != o.stopovers)
return this.stopovers - o.stopovers; //again, ascending but swap the two if you want descending
return 0;
}
}
In Python 3, print
became a function. This means that you need to include parenthesis now like mentioned below:
print("Hello World")
There is no way of checking of the contents of a variable are undefined or not. The best thing you can do is to assign a signal/sentinel value (for example in the constructor) to indicate that further initialization will need to be carried out.
Naming convention for collection
In order to name a collection few precautions to be taken :
Things to keep in mind while creating a database name are :
For more information. Please check the below link : http://www.tutorial-points.com/2016/03/schema-design-and-naming-conventions-in.html
Not seeing it mentioned here, but also possible to use the vue-property-decorator
pattern if you are extending your Vue
class.
import { Watch, Vue } from 'vue-property-decorator';
export default class SomeClass extends Vue {
...
@Watch('item.someOtherProp')
someOtherPropChange(newVal, oldVal) {
// do something
}
...
}
You can use "index" if you only want to find a single character, e.g.:
LIST="server1 server2 server3 server4 server5"
SOURCE="3"
if expr index "$LIST" "$SOURCE"; then
echo "match"
exit -1
else
echo "no match"
fi
Output is:
23
match
Just to contribute with my approach. As already answered, RetryPolicy
is the way to go. But if you need a policy different the than default for all your requests, you can set it in a base Request class, so you don't need to set the policy for all the instances of your requests.
Something like this:
public class BaseRequest<T> extends Request<T> {
public BaseRequest(int method, String url, Response.ErrorListener listener) {
super(method, url, listener);
setRetryPolicy(getMyOwnDefaultRetryPolicy());
}
}
In my case I have a GsonRequest which extends from this BaseRequest, so I don't run the risk of forgetting to set the policy for an specific request and you can still override it if some specific request requires to.
Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)\mssqllocaldb
as server name to connect to the LocalDB automatic instance, for example:
<connectionStrings>
<add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb;
...
The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some.
Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb
value instead of v12.0
and see if that corrects your issue.
This is what is working for me right now:
iPhone 6
@media only screen and (max-device-width: 667px)
and (-webkit-device-pixel-ratio: 2) {
iPhone 6+
@media screen and (min-device-width : 414px)
and (-webkit-device-pixel-ratio: 3)
Google now allows to hide the Badge, from the FAQ :
I'd like to hide the reCAPTCHA v3 badge. What is allowed?
You are allowed to hide the badge as long as you include the reCAPTCHA branding visibly in the user flow. Please include the following text: This site is protected by reCAPTCHA and the Google <a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply.
For example:
So you can simply hide it using the following CSS :
.grecaptcha-badge {
visibility: hidden;
}
Do not use display: none;
as it appears to disable the spam checking (thanks @Zade)
All of the answers posted so far are correct, an endpoint is simply one end of a communication channel. In the case of OAuth, there are three endpoints you need to be concerned with:
Hope that helps clear things up. Have fun learning about OAuth! Post more questions if you run into any difficulties implementing an OAuth client.
Have a look at the curses module documentation and the curses module HOWTO.
Really basic example:
import time
import curses
stdscr = curses.initscr()
stdscr.addstr(0, 0, "Hello")
stdscr.refresh()
time.sleep(1)
stdscr.addstr(0, 0, "World! (with curses)")
stdscr.refresh()
For example this will start XBMC:
adb shell am start -a android.intent.action.MAIN -n org.xbmc.xbmc/android.app.NativeActivity
(More general answers are already posted, but I missed a nice example here.)
You may use the class java.util.Random with method
char c = (char)(rnd.nextInt(128-32))+32
20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.
32 is the offset, from where the characters are printable in general.
This will work with bootstrap v3
$(document).ready(function() {_x000D_
if ($('.nav-tabs').length) {_x000D_
var hash = window.location.hash;_x000D_
var hashEl = $('ul.nav a[href="' + hash + '"]');_x000D_
hash && hashEl.tab('show');_x000D_
_x000D_
$('.nav-tabs a').click(function(e) {_x000D_
e.preventDefault();_x000D_
$(this).tab('show');_x000D_
window.location.hash = this.hash;_x000D_
});_x000D_
_x000D_
// Change tab on hashchange_x000D_
window.addEventListener('hashchange', function() {_x000D_
var changedHash = window.location.hash;_x000D_
changedHash && $('ul.nav a[href="' + changedHash + '"]').tab('show');_x000D_
}, false);_x000D_
}_x000D_
});
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
<div class="container">_x000D_
<ul class="nav nav-tabs">_x000D_
<li class="active"><a data-toggle="tab" href="#home">Home</a></li>_x000D_
<li><a data-toggle="tab" href="#menu1">Menu 1</a></li>_x000D_
</ul>_x000D_
_x000D_
<div class="tab-content">_x000D_
<div id="home" class="tab-pane fade in active">_x000D_
<h3>HOME</h3>_x000D_
<p>Some content.</p>_x000D_
</div>_x000D_
<div id="menu1" class="tab-pane fade">_x000D_
<h3>Menu 1</h3>_x000D_
<p>Some content in menu 1.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
If you're interested in making .xlsx (Office 2007 and beyond) files, you're in luck. Office 2007+ uses OpenXML which for lack of a more apt description is XML files inside of a zip named .xlsx
Take an excel file (2007+) and rename it to .zip, you can open it up and take a look. If you're using .NET 3.5 you can use the System.IO.Packaging library to manipulate the relationships & zipfile itself, and linq to xml to play with the xml (or just DOM if you're more comfortable).
Otherwise id reccomend DotNetZip, a powerfull library for manipulation of zipfiles.
OpenXMLDeveloper has lots of resources about OpenXML and you can find more there.
If you want .xls (2003 and below) you're going to have to look into 3rd party libraries or perhaps learn the file format yourself to achieve this without excel installed.
I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly/project. I came up with the following thanks to the source code of the DynamicJson project:
public XmlDocument JsonToXML(string json)
{
XmlDocument doc = new XmlDocument();
using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
{
XElement xml = XElement.Load(reader);
doc.LoadXml(xml.ToString());
}
return doc;
}
Note: I wanted an XmlDocument rather than an XElement for xPath purposes. Also, this code obviously only goes from JSON to XML, there are various ways to do the opposite.
In addition to other answers, I would like to add one image for it(pic makes easy to understand)
static
variables may be cached for individual threads. In multi-threaded environment if one thread modifies its cached data, that may not reflect for other threads as they have a copy of it.
volatile
declaration makes sure that threads won't cache the data and uses the shared copy only.
You can't get value when calling getJSON
, only after response.
var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
myjson = json;
});
Using Multiple Peoples help from multiple Threads..
I know this has been answered, but i would like to give a full encode & decode method for any others in my same situation..
Here's my Encoding & Decoding methods..
// Global Charset Encoding
public static Charset encodingType = StandardCharsets.UTF_8;
// Text To Hex
public static String textToHex(String text)
{
byte[] buf = null;
buf = text.getBytes(encodingType);
char[] HEX_CHARS = "0123456789abcdef".toCharArray();
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i)
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
// Hex To Text
public static String hexToText(String hex)
{
int l = hex.length();
byte[] data = new byte[l / 2];
for (int i = 0; i < l; i += 2)
{
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
String st = new String(data, encodingType);
return st;
}
For the people stumbling across this question and getting a similar error message in regards to an nvarchar instead of money:
The given value of type String from the data source cannot be converted to type nvarchar of the specified target column.
This could be caused by a too-short column.
For example, if your column is defined as nvarchar(20)
and you have a 40 character string, you may get this error.
Swift 3/4 with @IBDesignable
While almost all the above solutions work fine but I would suggest an @IBDesignable
custom class for this.
@IBDesignable
class CustomLabel: UILabel {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
@IBInspectable var borderColor: UIColor = UIColor.white {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var borderWidth: CGFloat = 2.0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}
Convert.ToInt32
has 19 overloads or 19 different ways that you can call it. Maybe more in 2010 versions.
It will attempt to convert from the following TYPES;
Object, Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, String, Date
and it also has a number of other methods; one to do with a number base and 2 methods involve a System.IFormatProvider
Parse on the other hand only has 4 overloads or 4 different ways you can call the method.
Integer.Parse( s As String)
Integer.Parse( s As String, style As System.Globalization.NumberStyles )
Integer.Parse( s As String, provider As System.IFormatProvider )
Integer.Parse( s As String, style As System.Globalization.NumberStyles, provider As System.IFormatProvider )
Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}
You can read about the changes in What's New In Python 3.0. You should read it thoroughly when you move from 2.x to 3.x since a lot has been changed.
The whole answer here are quotes from the documentation.
Views And Iterators Instead Of Lists
Some well-known APIs no longer return lists:
- [...]
map()
andfilter()
return iterators. If you really need a list, a quick fix is e.g.list(map(...))
, but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky ismap()
invoked for the side effects of the function; the correct transformation is to use a regularfor
loop (since creating a list would just be wasteful).- [...]
- [...]
- Removed
reduce()
. Usefunctools.reduce()
if you really need it; however, 99 percent of the time an explicitfor
loop is more readable.- [...]
Here are a couple of things to check:
For console.Write/WriteLine
, your app must be a console application. (right-click the project in Solution Explorer, choose Properties, and look at the "Output Type" combo in the Application Tab -- should be "Console Application" (note, if you really need a windows application or a class library, don't change this to Console App just to get the Console.WriteLine
).
You could use System.Diagnostics.Debug.WriteLine
to write to the output window (to show the output window in VS, got to View | Output) Note that these writes will only occur in a build where the DEBUG conditional is defined (by default, debug builds define this, and release builds do not)
You could use System.Diagnostics.Trace.Writeline
if you want to be able to write to configurable "listeners" in non-debug builds. (by default, this writes to the Output Window in Visual Studio, just like Debug.Writeline
)
I was helped by a method with a function check. This method works in IE8
if(typeof e.preventDefault == 'function'){
e.preventDefault();
} else {
e.returnValue = false;
}
its a block element, and you need to use none
document.getElementById("test").style.display="none"
hidden
is used for visibility
Create database link NAME connect to USERNAME identified by PASSWORD using 'SID';
Specify SHARED to use a single network connection to create a public database link that can be shared among multiple users. If you specify SHARED, you must also specify the dblink_authentication clause.
Specify PUBLIC to create a public database link available to all users. If you omit this clause, the database link is private and is available only to you.
If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:
float:left; display:inline; width: 49%;
on both of them.
#mainContent, #sideContent {float:left; display:inline; width: 49%;}
While it is true that you cannot change the type of the column after the DataTable
is filled, you can change it after you call FillSchema
, but before you call Fill
. For example, say the 3rd column is the one you want to convert from double
to Int32
, you could use:
adapter.FillSchema(table, SchemaType.Source);
table.Columns[2].DataType = typeof (Int32);
adapter.Fill(table);
I can recomend Ion library it use 3 dependences and you can find all three jar files at these two sites:
https://github.com/koush/ion#jars (ion and androidasync)
try {
Ion.with(this, "http://www.urlthatyouwant.com/post/page")
.setMultipartParameter("field1", "This is field number 1")
.setMultipartParameter("field2", "Field 2 is shorter")
.setMultipartFile("imagefile",
new File(Environment.getExternalStorageDirectory()+"/testfile.jpg"))
.asString()
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
System.out.println(result);
}});
} catch(Exception e) {
// Do something about exceptions
System.out.println("exception: " + e);
}
this will run async and the callback will be executed in the UI thread once a response is received I strongly recomned that you go to the https://github.com/koush/ion for futher information
For SQL Server 2012 onwards it could be easy:
SELECT id, SomeNumt, sum(SomeNumt) OVER (ORDER BY id) as CumSrome FROM @t
because ORDER BY
clause for SUM
by default means RANGE UNBOUNDED PRECEDING AND CURRENT ROW
for window frame ("General Remarks" at https://msdn.microsoft.com/en-us/library/ms189461.aspx)
Here's the XPath approach but with a minimum of XPath jargon.
Regular selection based on element attribute values (for comparison):
// for matching <element class="foo bar baz">...</element> by 'bar'
var things = document.querySelectorAll('[class*="bar"]');
for (var i = 0; i < things.length; i++) {
things[i].style.outline = '1px solid red';
}
XPath selection based on text within element.
// for matching <element>foo bar baz</element> by 'bar'
var things = document.evaluate('//*[contains(text(),"bar")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < things.snapshotLength; i++) {
things.snapshotItem(i).style.outline = '1px solid red';
}
And here's with case-insensitivity since text is more volatile:
// for matching <element>foo bar baz</element> by 'bar' case-insensitively
var things = document.evaluate('//*[contains(translate(text(),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"),"bar")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < things.snapshotLength; i++) {
things.snapshotItem(i).style.outline = '1px solid red';
}
Here is a complete jquery plugin that solves this problem:
https://github.com/bigspotteddog/ScrollToFixed
The description of this plugin is as follows:
This plugin is used to fix elements to the top of the page, if the element would have scrolled out of view, vertically; however, it does allow the element to continue to move left or right with the horizontal scroll.
Given an option marginTop, the element will stop moving vertically upward once the vertical scroll has reached the target position; but, the element will still move horizontally as the page is scrolled left or right. Once the page has been scrolled back down past the target position, the element will be restored to its original position on the page.
This plugin has been tested in Firefox 3/4, Google Chrome 10/11, Safari 5, and Internet Explorer 8/9.
Usage for your particular case:
<script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery-scrolltofixed-min.js" type="text/javascript"></script>
$(document).ready(function() {
$('#mydiv').scrollToFixed({ marginTop: 250 });
});
simple
COPY README.md package.json gulpfile.js __BUILD_NUMBER ./
from the doc
If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.
There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do
conda create -n python2 python=2.7 anaconda
This will create an environment named python2
that contains the Python 2.7 version of Anaconda. You can activate this environment with
source activate python2
This will put that environment (typically ~/anaconda/envs/python2
) in front in your PATH
, so that when you type python
at the terminal it will load the Python from that environment.
If you don't want all of Anaconda, you can replace anaconda
in the command above with whatever packages you want. You can use conda
to install packages in that environment later, either by using the -n python2
flag to conda
, or by activating the environment.
After reading Sime Vidas's answer, I searched more and found a very straight-forward and easy-to-understand explanation in the angular docs.
HTML attribute vs. DOM property
-------------------------------
Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).
A few HTML attributes have 1:1 mapping to properties.
id
is one example.Some HTML attributes don't have corresponding properties.
colspan
is one example.Some DOM properties don't have corresponding attributes.
textContent
is one example.Many HTML attributes appear to map to properties ... but not in the way you might think!
That last category is confusing until you grasp this general rule:
Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.
For example, when the browser renders
<input type="text" value="Bob">
, it creates a corresponding DOM node with avalue
property initialized to "Bob".When the user enters "Sally" into the input box, the DOM element
value
property becomes "Sally". But the HTMLvalue
attribute remains unchanged as you discover if you ask the input element about that attribute:input.getAttribute('value')
returns "Bob".The HTML attribute
value
specifies the initial value; the DOMvalue
property is the current value.
The
disabled
attribute is another peculiar example. A button'sdisabled
property isfalse
by default so the button is enabled. When you add thedisabled
attribute, its presence alone initializes the button'sdisabled
property totrue
so the button is disabled.Adding and removing the
disabled
attribute disables and enables the button. The value of the attribute is irrelevant, which is why you cannot enable a button by writing<button disabled="false">Still Disabled</button>.
Setting the button's
disabled
property disables or enables the button. The value of the property matters.The HTML attribute and the DOM property are not the same thing, even when they have the same name.
You want a multiple attribute selector
$("input[type='checkbox'][name='ProductCode']").each(function(){ ...
or
$("input:checkbox[name='ProductCode']").each(function(){ ...
It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName
method which will be used to select elements and be much faster than selecting by the name
attribute
A pem
file contains the certificate and the private key. It depends on the format your certificate/key are in, but probably it's as simple as this:
cat server.crt server.key > server.pem
If you check the docs for EditText
, you'll find a setText()
method. It takes in a String
and a TextView.BufferType
. For example:
EditText editText = (EditText)findViewById(R.id.edit_text);
editText.setText("This sets the text.", TextView.BufferType.EDITABLE);
It also inherits TextView
's setText(CharSequence)
and setText(int)
methods, so you can set it just like a regular TextView
:
editText.setText("Hello world!");
editText.setText(R.string.hello_world);
There is at least one situation where using single quotes will not work and that is if you are creating the markup "on the fly" from JavaScript. You use single quotes to contain the string and then any property in the markup can have double quotes for its value.
This is a simple way to create a progressbar
import time,sys
toolbar_width = 50
# setting up toolbar [-------------------------------------]
sys.stdout.write("[%s]"%(("-")*toolbar_width))
sys.stdout.flush()
# each hash represents 2 % of the progress
for i in range(toolbar_width):
sys.stdout.write("\r") # return to start of line
sys.stdout.flush()
sys.stdout.write("[")#Overwrite over the existing text from the start
sys.stdout.write("#"*(i+1))# number of # denotes the progress completed
sys.stdout.flush()
time.sleep(0.1)
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
As simple as that.
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
dataObj = JSON.parse(str);
Workaround is to hide the backdrop entirely if you don't need one like this: data-backdrop=""
<div class="modal fade preview-modal" data-backdrop="" id="preview-modal" role="dialog" aria-labelledby="preview-modal" aria-hidden="true">
if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.
Just use substring: "apple".substring(3);
will return le
If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.
$('#mydiv').click(function(e) {
// maniplate #mydiv ...
$('#mydiv').trigger('mydiv-manipulated');
});
$('#mydiv').bind('mydiv-manipulated', function(e) {
// do more stuff now that #mydiv has been manipulated
return;
});
Something like that at least.
public enum Modes {
MODE1("Mode1"),
MODE2("Mode2"),
MODE3("Mode3");
private String value;
public String getValue() {
return value;
}
private Modes(String value) {
this.value = value;
}
}
you can make a call like below wherever you want to get the value as a string from the enum.
Modes.MODE1.getvalue();
This will return "Mode1" as a String.
You could look into this: http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx It's not completely free, but it looks very nice.
Alex
just Add:
<button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
Below Kotlin code will help
Bottom to Top or Slide to Up
private fun slideUp() {
isMapInfoShown = true
views!!.layoutMapInfo.visible()
val animate = TranslateAnimation(
0f, // fromXDelta
0f, // toXDelta
views!!.layoutMapInfo.height.toFloat(), // fromYDelta
0f // toYDelta
)
animate.duration = 500
animate.fillAfter = true
views!!.layoutMapInfo.startAnimation(animate)
}
Top to Bottom or Slide to Down
private fun slideDown() {
if (isMapInfoShown) {
isMapInfoShown = false
val animate = TranslateAnimation(
0f, // fromXDelta
0f, // toXDelta
0f, // fromYDelta
views!!.layoutMapInfo.height.toFloat() // toYDelta
)
animate.duration = 500
animate.fillAfter = true
views!!.layoutMapInfo.startAnimation(animate)
views!!.layoutMapInfo.gone()
}
}
Kotlin Extensions for Visible and Gone
fun View.visible() {
this.visibility = View.VISIBLE
}
fun View.gone() {
this.visibility = View.GONE
}
>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True
So it doesn't matter, they are all the same value.
The only reason all three modules provide a pi
value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.
en api level 14
marker.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.miubicacion, null));
td
height to less than the natural height of its contentSince table cells want to be at least big enough to encase their content, if the content has no apparent height, the cells can be arbitrarily resized.
By resizing the cells, we can control the row height.
One way to do this, is to set the content with an absolute
position within the relative
cell, and set the height
of the cell, and the left
and top
of the content.
table {_x000D_
width: 100%;_x000D_
}_x000D_
td {_x000D_
border: 1px solid #999;_x000D_
}_x000D_
.set-height td {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
height: 3em;_x000D_
}_x000D_
.set-height p {_x000D_
position: absolute;_x000D_
margin: 0;_x000D_
top: 0;_x000D_
}_x000D_
/* table layout fixed */_x000D_
.layout-fixed {_x000D_
table-layout: fixed;_x000D_
}_x000D_
/* td width */_x000D_
.td-width td:first-child {_x000D_
width: 33%;_x000D_
}
_x000D_
<table><tbody>_x000D_
<tr class="set-height">_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
<td>Foo</td></tr><tr><td>Bar</td><td>Baz</td></tr><tr><td>Qux</td>_x000D_
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td>_x000D_
</tr>_x000D_
</tbody></table>_x000D_
<h3>With <code>table-layout: fixed</code> applied:</h3>_x000D_
<table class="layout-fixed"><tbody>_x000D_
<tr class="set-height">_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
<td>Foo</td></tr><tr><td>Bar</td><td>Baz</td></tr><tr><td>Qux</td>_x000D_
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td>_x000D_
</tr>_x000D_
</tbody></table>_x000D_
<h3>With <code><td> width</code> applied:</h3>_x000D_
<table class="td-width"><tbody>_x000D_
<tr class="set-height">_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
<td>Foo</td></tr><tr><td>Bar</td><td>Baz</td></tr><tr><td>Qux</td>_x000D_
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td>_x000D_
</tr>_x000D_
</tbody></table>
_x000D_
The table-layout
property
The second table in the snippet above has table-layout: fixed
applied, which causes cells to be given equal width, regardless of their content, within the parent.
According to caniuse.com, there are no significant compatibility issues regarding the use of table-layout
as of Sept 12, 2019.
Or simply apply width
to specific cells as in the third table.
These methods allow the cell containing the effectively sizeless content created by applying position: absolute
to be given some arbitrary girth.
I really should have thought of this from the start; we can manipulate block level table cell content in all the usual ways, and without completely destroying the content's natural size with position: absolute
, we can leave the table to figure out what the width should be.
table {_x000D_
width: 100%;_x000D_
}_x000D_
td {_x000D_
border: 1px solid #999;_x000D_
}_x000D_
table p {_x000D_
margin: 0;_x000D_
}_x000D_
.cap-height p {_x000D_
max-height: 3em;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<table><tbody>_x000D_
<tr class="cap-height">_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
<td>Foo</td>_x000D_
</tr>_x000D_
<tr class="cap-height">_x000D_
<td><p>Bar</p></td>_x000D_
<td>Baz</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Qux</td>_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
</tr>_x000D_
</tbody></table>
_x000D_
This is a late answer to an old question, but all other answers are missing the point, which is that .NET did not have generics until .NET 2.0 in 2005.
String
is a reference type instead of a value type because it was of crucial importance for Microsoft to ensure that strings could be stored in the most efficient way in non-generic collections, such as System.Collections.ArrayList
.
Storing a value-type in a non-generic collection requires a special conversion to the type object
which is called boxing. When the CLR boxes a value type, it wraps the value inside a System.Object
and stores it on the managed heap.
Reading the value from the collection requires the inverse operation which is called unboxing.
Both boxing and unboxing have non-negligible cost: boxing requires an additional allocation, unboxing requires type checking.
Some answers claim incorrectly that string
could never have been implemented as a value type because its size is variable. Actually it is easy to implement string as a fixed-length data structure containing two fields: an integer for the length of the string, and a pointer to a char array. You can also use a Small String Optimization strategy on top of that.
If generics had existed from day one I guess having string as a value type would probably have been a better solution, with simpler semantics, better memory usage and better cache locality. A List<string>
containing only small strings could have been a single contiguous block of memory.
“CURL ERROR 7 Failed to connect to Permission denied” error is caused, when for any reason curl request is blocked by some firewall or similar thing.
you will face this issue when ever the curl request is not with standard ports.
for example if you do curl to some URL which is on port 1234, you will face this issue where as URL with port 80 will give you results easily.
Most commonly this error has been seen on CentOS and any other OS with ‘SElinux’.
you need to either disable or change ’SElinux’ to permissive
have a look on this one
http://www.akashif.co.uk/php/curl-error-7-failed-to-connect-to-permission-denied
Hope this helps
If you have more than one enviroment, you may add the following way in the angular.json
:
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your_project:build"
},
"configurations": {
"production": {
"browserTarget": "your_project:build:production"
},
"es5": {
"browserTarget": "your_project:build:es5"
},
"local": {
"browserTarget": "your_project:build:local",
"port": 4201
},
"uat": {
"browserTarget": "your_project:build:uat"
}
}
},
This way only the local points to another port.
For those who are learning node/express (just like me): do not use wildcard routing if possible!
I also wanted to implement the routing for GET /users/:id/whatever using wildcard routing. This is how I got here.
More info: https://blog.praveen.science/wildcard-routing-is-an-anti-pattern/
<%
try{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
if(con == null) System.out.print("not connected");
Statement st = con.createStatement();
String myStatement = "select count(*) as total from locations";
ResultSet rs = st.executeQuery(myStatement);
int num = 0;
while(rs.next()){
num = (rs.getInt(1));
}
}
catch(Exception e){
System.out.println(e);
}
%>
Try Like this.
For Inserting into DB
$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";
$qry = mysqli_query($db, $query);
For Accessing image From Blob
$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';
Hope It will help you.
Thanks.
Note that even if the DLL is in your path. If that DLL relies on other DLLs that are NOT in your path, you can get the same error. Windows could not find a dependency in this case. Windows is not real good at telling you what it could not find, only that it did not find something. It is up to you to figure that out. The Windows dll search path can be found here: http://msdn.microsoft.com/en-us/library/7d83bc18.aspx
In my case, being sure all needed dlls were in the same directory and doing a os.chdir() to that directory solved the problem.
Try iterating through each element of the list, then splitting it at the tab character and adding it to a new list.
for i in list:
newList.append(i.split('\t')[0])
by XML:
<EditText
android:id="@+id/search_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/search"
android:imeOptions="actionSearch"
android:inputType="text" />
By Java:
editText.clearFocus();
InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
I also had the same issue, but the problem was with the Target framework of the assembly.
The referenced assembly was in .NET Framework 4.6 where the project has set to .NET framework 4.5.
Hope this will help to someone who messed up with frameworks.
JDK includes the JRE plus command-line development tools such as compilers and debuggers that are necessary or useful for developing applets and applications.
JRE is basically the Java Virtual Machine where your Java programs run on. It also includes browser plugins for Applet execution.
JDK is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
So, Basically JVM < JRE < JDK as per @Jaimin Patel said.
MySQL's utf8
permits only the Unicode characters that can be represented with 3 bytes in UTF-8. Here you have a character that needs 4 bytes: \xF0\x90\x8D\x83 (U+10343 GOTHIC LETTER SAUIL).
If you have MySQL 5.5 or later you can change the column encoding from utf8
to utf8mb4
. This encoding allows storage of characters that occupy 4 bytes in UTF-8.
You may also have to set the server property character_set_server
to utf8mb4
in the MySQL configuration file. It seems that Connector/J defaults to 3-byte Unicode otherwise:
For example, to use 4-byte UTF-8 character sets with Connector/J, configure the MySQL server with
character_set_server=utf8mb4
, and leavecharacterEncoding
out of the Connector/J connection string. Connector/J will then autodetect the UTF-8 setting.
jquery.min is compress version. It's removed comments, new lines, ...
No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:
Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng
is producing the same result as Joe's code.
If you need to switch sheets for some reasons, use Application.ScreenUpdating = False
at the beginning of your macro (and Application.ScreenUpdating=True
at the end). This will remove the screenflickering - and speed up the execution.
Use this:
window.open('', '_self');
This only works in chrome; it is a bug. It will be fixed in the future, so use this hacky solution with this in mind.
If you don't know how many columns you are going to have, the declaration
table-layout: fixed
along with not setting any column widths, would imply that browsers divide the total width evenly - no matter what.
That can also be the problem with this approach, if you use this, you should also consider how overflow is to be handled.
I recently found a really good tutorial on Objective-C Strings:
http://ios-blog.co.uk/tutorials/objective-c-strings-a-guide-for-beginners/
And I thought that this might be of interest:
If you want to split the string into an array use a method called componentsSeparatedByString to achieve this:
NSString *yourString = @"This is a test string";
NSArray *yourWords = [myString componentsSeparatedByString:@" "];
// yourWords is now: [@"This", @"is", @"a", @"test", @"string"]
if you need to split on a set of several different characters, use NSString’s componentsSeparatedByCharactersInSet:
NSString *yourString = @"Foo-bar/iOS-Blog";
NSArray *yourWords = [myString componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@"-/"]
];
// yourWords is now: [@"Foo", @"bar", @"iOS", @"Blog"]
Note however that the separator string can’t be blank. If you need to separate a string into its individual characters, just loop through the length of the string and convert each char into a new string:
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
echo `date +%s`/86400 | bc
Sorry for comment in an old post but if you want to use an else if statement this will help you
{% if title == source %}
Do This
{% elif title == value %}
Do This
{% else %}
Do This
{% endif %}
For more info see Django Documentation
Output from subprocess.call()
should only be redirected to files.
You should use subprocess.Popen()
instead. Then you can pass subprocess.PIPE
for the stderr, stdout, and/or stdin parameters and read from the pipes by using the communicate()
method:
from subprocess import Popen, PIPE
p = Popen(['program', 'arg1'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode
The reasoning is that the file-like object used by subprocess.call()
must have a real file descriptor, and thus implement the fileno()
method. Just using any file-like object won't do the trick.
See here for more info.
Are you sure the Full Legal Name will always include First, Middle and Last? I know people that have only one name as Full Legal Name, and honestly I am not sure if that's their First or Last Name. :-) I also know people that have more than one Fisrt names in their legal name, but don't have a Middle name. And there are some people that have multiple Middle names.
Then there's also the order of the names in the Full Legal Name. As far as I know, in some Asian cultures the Last Name comes first in the Full Legal Name.
On a more practical note, you could split the Full Name on whitespace and threat the first token as First name and the last token (or the only token in case of only one name) as Last name. Though this assumes that the order will be always the same.
If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:
var items = (from x in parameters
join y in myStrings on x.Source equals y
select x)
.ToList();
$.each(data,function(index,itemData){
$('#dropListBuilding').append($("<option></option>")
.attr("value",key)
.text(value));
});
You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.
e.g.
filenames = "first second third fourth fifth"
plot for [file in filenames] file."dat" using 1:2 with lines
and
filename(n) = sprintf("file_%d", n)
plot for [i=1:10] filename(i) using 1:2 with lines
public class searchingFile
{
static String path;//defining(not initializing) these variables outside main
static String filename;//so that recursive function can access them
static int counter=0;//adding static so that can be accessed by static methods
public static void main(String[] args) //main methods begins
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the path : ");
path=sc.nextLine(); //storing path in path variable
System.out.println("Enter file name : ");
filename=sc.nextLine(); //storing filename in filename variable
searchfile(path);//calling our recursive function and passing path as argument
System.out.println("Number of locations file found at : "+counter);//Printing occurences
}
public static String searchfile(String path)//declaring recursive function having return
//type and argument both strings
{
File file=new File(path);//denoting the path
File[] filelist=file.listFiles();//storing all the files and directories in array
for (int i = 0; i < filelist.length; i++) //for loop for accessing all resources
{
if(filelist[i].getName().equals(filename))//if loop is true if resource name=filename
{
System.out.println("File is present at : "+filelist[i].getAbsolutePath());
//if loop is true,this will print it's location
counter++;//counter increments if file found
}
if(filelist[i].isDirectory())// if resource is a directory,we want to inside that folder
{
path=filelist[i].getAbsolutePath();//this is the path of the subfolder
searchfile(path);//this path is again passed into the searchfile function
//and this countinues untill we reach a file which has
//no sub directories
}
}
return path;// returning path variable as it is the return type and also
// because function needs path as argument.
}
}
targetList = sourceList.stream().flatmap(List::stream).collect(Collectors.toList());
Added content of pg_env.sh to my .bashrc:
cat /opt/PostgreSQL/10/pg_env.sh
#!/bin/sh
# The script sets environment variables helpful for PostgreSQL
export PATH=/opt/PostgreSQL/10/bin:$PATH
export PGDATA=/opt/PostgreSQL/10/data
export PGDATABASE=postgres
export PGUSER=postgres
export PGPORT=5433
export PGLOCALEDIR=/opt/PostgreSQL/10/share/locale
export MANPATH=$MANPATH:/opt/PostgreSQL/10/share/man
with addition of (as per user4653174 suggestion)
export PGPASSWORD='password'
Although the accepted answer is still correct about needing to match directories with package names, you really need to migrate to using Go modules instead of using GOPATH. New users who encounter this problem may be confused about the mentions of using GOPATH (as was I), which are now outdated. So, I will try to clear up this issue and provide guidance associated with preventing this issue when using Go modules.
If you're already familiar with Go modules and are experiencing this issue, skip down to my more specific sections below that cover some of the Go conventions that are easy to overlook or forget.
This guide teaches about Go modules: https://golang.org/doc/code.html
Project organization with Go modules
Once you migrate to Go modules, as mentioned in that article, organize the project code as described:
A repository contains one or more modules. A module is a collection of related Go packages that are released together. A Go repository typically contains only one module, located at the root of the repository. A file named go.mod there declares the module path: the import path prefix for all packages within the module. The module contains the packages in the directory containing its go.mod file as well as subdirectories of that directory, up to the next subdirectory containing another go.mod file (if any).
Each module's path not only serves as an import path prefix for its packages, but also indicates where the go command should look to download it. For example, in order to download the module golang.org/x/tools, the go command would consult the repository indicated by https://golang.org/x/tools (described more here).
An import path is a string used to import a package. A package's import path is its module path joined with its subdirectory within the module. For example, the module github.com/google/go-cmp contains a package in the directory cmp/. That package's import path is github.com/google/go-cmp/cmp. Packages in the standard library do not have a module path prefix.
You can initialize your module like this:
$ go mod init github.com/mitchell/foo-app
Your code doesn't need to be located on github.com for it to build. However, it's a best practice to structure your modules as if they will eventually be published.
Understanding what happens when trying to get a package
There's a great article here that talks about what happens when you try to get a package or module: https://medium.com/rungo/anatomy-of-modules-in-go-c8274d215c16 It discusses where the package is stored and will help you understand why you might be getting this error if you're already using Go modules.
Ensure the imported function has been exported
Note that if you're having trouble accessing a function from another file, you need to ensure that you've exported your function. As described in the first link I provided, a function must begin with an upper-case letter to be exported and made available for importing into other packages.
Names of directories
Another critical detail (as was mentioned in the accepted answer) is that names of directories are what define the names of your packages. (Your package names need to match their directory names.) You can see examples of this here: https://medium.com/rungo/everything-you-need-to-know-about-packages-in-go-b8bac62b74cc
With that said, the file containing your main
method (i.e., the entry point of your application) is sort of exempt from this requirement.
As an example, I had problems with my imports when using a structure like this:
/my-app
+-- go.mod
+-- /src
+-- main.go
+-- /utils
+-- utils.go
I was unable to import the code in utils
into my main
package.
However, once I put main.go
into its own subdirectory, as shown below, my imports worked just fine:
/my-app
+-- go.mod
+-- /src
+-- /app
| +-- main.go
+-- /utils
+-- utils.go
In that example, my go.mod file looks like this:
module git.mydomain.com/path/to/repo/my-app
go 1.14
When I saved main.go after adding a reference to utils.MyFunction()
, my IDE automatically pulled in the reference to my package like this:
import "git.mydomain.com/path/to/repo/my-app/src/my-app"
(I'm using VS Code with the Golang extension.)
Notice that the import path included the subdirectory to the package.
Dealing with a private repo
If the code is part of a private repo, you need to run a git command to enable access. Otherwise, you can encounter other errors This article mentions how to do that for private Github, BitBucket, and GitLab repos: https://medium.com/cloud-native-the-gathering/go-modules-with-private-git-repositories-dfe795068db4 This issue is also discussed here: What's the proper way to "go get" a private repository?
You need the line
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Because the default behaviour for the JFrame when you press the X button is the equivalent to
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
So almost all the times you'll need to add that line manually when creating your JFrame
I am currently referring to constants in WindowConstants
like WindowConstants.EXIT_ON_CLOSE
instead of the same constants declared directly in JFrame
as the prior reflect better the intent.
Even better
#include <stdio.h>
int
main(void)
{
char *line = NULL;
size_t count;
char *dup_line;
getline(&line,&count, stdin);
dup_line=strdup(line);
puts(dup_line);
free(dup_line);
free(line);
return 0;
}
Try this:
public static boolean jsonsEqual(Object obj1, Object obj2) throws JSONException
{
if (!obj1.getClass().equals(obj2.getClass()))
{
return false;
}
if (obj1 instanceof JSONObject)
{
JSONObject jsonObj1 = (JSONObject) obj1;
JSONObject jsonObj2 = (JSONObject) obj2;
String[] names = JSONObject.getNames(jsonObj1);
String[] names2 = JSONObject.getNames(jsonObj1);
if (names.length != names2.length)
{
return false;
}
for (String fieldName:names)
{
Object obj1FieldValue = jsonObj1.get(fieldName);
Object obj2FieldValue = jsonObj2.get(fieldName);
if (!jsonsEqual(obj1FieldValue, obj2FieldValue))
{
return false;
}
}
}
else if (obj1 instanceof JSONArray)
{
JSONArray obj1Array = (JSONArray) obj1;
JSONArray obj2Array = (JSONArray) obj2;
if (obj1Array.length() != obj2Array.length())
{
return false;
}
for (int i = 0; i < obj1Array.length(); i++)
{
boolean matchFound = false;
for (int j = 0; j < obj2Array.length(); j++)
{
if (jsonsEqual(obj1Array.get(i), obj2Array.get(j)))
{
matchFound = true;
break;
}
}
if (!matchFound)
{
return false;
}
}
}
else
{
if (!obj1.equals(obj2))
{
return false;
}
}
return true;
}
If you want to bind to the redis port from your nodejs
container you will have to expose that port in the redis
container:
version: '2'
services:
nodejs:
build:
context: .
dockerfile: DockerFile
ports:
- "4000:4000"
links:
- redis
redis:
build:
context: .
dockerfile: Dockerfile-redis
expose:
- "6379"
The expose
tag will let you expose ports without publishing them to the host machine, but they will be exposed to the containers networks.
https://docs.docker.com/compose/compose-file/#expose
The ports
tag will be mapping the host port with the container port HOST:CONTAINER
For Windows, apparently the JDK has to be under C:\Program Files.
This does not work:
C:\dev\Java\jdk1.8.0_191
This works:
C:\Program Files\Java\jdk1.8.0_191
(I'm using IntelliJ IDEA Ultimate 2018.2.4.)
This will do:
path.join(...process.argv[1].split(/\/|\\/).slice(0, -1))
Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import random
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# instead of ax.hold(False)
self.figure.clear()
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
# ax.hold(False) # deprecated, see above
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
You could do something like this
class ExampleClass:
def __init__(self, **kwargs):
arguments = {'val':1, 'val2':2}
arguments.update(kwargs)
self.val = arguments['val']
self.val2 = arguments['val2']
var List = @Html.Raw(Json.Encode(Model));
$.ajax({
type: 'post',
url: '/Controller/action',
data:JSON.stringify({ 'item': List}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//do your actions
},
error: function (response) {
alert("error occured");
}
});
I don't believe this is possible, easily. The only way I believe to get around this is to make your own back button arrow image to place up there. It was frustrating for me at first but I see why, for consistency's sake, it was left out.
You can get close (without the arrow) by creating a regular button and hiding the default back button:
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Servers" style:UIBarButtonItemStyleDone target:nil action:nil] autorelease];
self.navigationItem.hidesBackButton = YES;
In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by()
on distinct("field_name")
queries. This is, however, a Postgres only feature!
If you are using Postgres and if you define a field name that the query should be distinct for, then order_by()
needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).
Note
When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.
For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.
If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:
# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.
I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.
Thanks to all above though.
Since I have used this many times already and didn't see it listed here, I'll add my piece :
$var = @{$true="this is true";$false="this is false"}[1 -eq 1]
ugliest of all !
try this following snippet, its working fine.
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openfile1 = new OpenFileDialog();
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = openfile1.FileName;
}
{
string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
OleDbConnection conn = new OleDbConnection(pathconn);
OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
DataTable dt = new DataTable();
MyDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch { }
}
Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.
Now if you know that once assigned, the value will never reassigned a value of null, you can use:
if (box != null) {
box.removeFromCanvas();
}
(and that also avoids a possible NullPointerException
) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:
if (box != null) {
box.removeFromCanvas();
// Forget about the box - we don't want to try to remove it again
box = null;
}
The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):
// Won't compile
String x;
System.out.println(x);
// Will compile, prints null
String y = null;
System.out.println(y);
With library fpp
, you can easily create time series with date format:
time_ser=ts(data,frequency=4,start=c(1954,2))
here we start at the 2nd quarter of 1954 with quarter fequency.
catch (ReflectionTypeLoadException ex)
{
foreach (var item in ex.LoaderExceptions)
{
MessageBox.Show(item.Message);
}
}
I'm sorry for resurrecting an old thread, but wanted to post a different solution to pull the loader exception (Using the actual ReflectionTypeLoadException) for anybody else to come across this.
Comparison expressions should each be in their own brackets:
{% if (a == 'foo') or (b == 'bar') %}
...
{% endif %}
Alternative if you are inspecting a single variable and a number of possible values:
{% if a in ['foo', 'bar', 'qux'] %}
...
{% endif %}
Another alternative might be to use Flask-APScheduler which plays nicely with Flask, e.g.:
More information here:
Here is the simplest and most practical answer to getting a name:
var actionName = RouteData.Values["action"];
var controllerName = RouteData.Values["controller"];
Or
string actionName = RouteData.Values["action"].ToString();
string controllerName = RouteData.Values["controller"].ToString();
Code above tests with asp.net mvc 5.
You can listen to the dragend
event, and if the map is dragged outside the allowed bounds, move it back inside. You can define your allowed bounds in a LatLngBounds
object and then use the contains()
method to check if the new lat/lng center is within the bounds.
You can also limit the zoom level very easily.
Consider the following example: Fiddle Demo
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Limit Panning and Zoom</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
// This is the minimum zoom level that we'll allow
var minZoomLevel = 5;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(28.70, -127.50),
new google.maps.LatLng(48.85, -55.90)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function() {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
</script>
</body>
</html>
Screenshot from the above example. The user will not be able to drag further south or far east in this case:
Solution1 - set global config, by running this command:
git config --system core.longpaths true
Solution2 - or you can edit directly your specific git config file like below:
YourRepoFolder -> .git -> config:
[core]
repositoryformatversion = 0
filemode = false
...
longpaths = true <-- (add this line under core section)
Solution3 - when cloning a new repository: here.
Normally you want to perform this check atomically with using the result, so stat()
is useless. Instead, open()
the file read-only first and use fstat()
. If it's a directory, you can then use fdopendir()
to read it. Or you can try opening it for writing to begin with, and the open will fail if it's a directory. Some systems (POSIX 2008, Linux) also have an O_DIRECTORY
extension to open
which makes the call fail if the name is not a directory.
Your method with opendir()
is also good if you want a directory, but you should not close it afterwards; you should go ahead and use it.
I tried sudo apt install nginx-full. You will get all the required packages.
A "Collapse All" command exists in recent builds (e.g. 3.2 M6) and is bound to Ctrl+Shift+NUM_KEYPAD_DIVIDE by default.
You can also configure it in Preferences->Editor->Keys.
This helped in my case:
cmdkey.exe /add:<targetname> /user:<username> /pass:<password>
psexec.exe \\<targetname> <remote_command>
You can use the maven.javadoc.skip
property to skip execution of the plugin, going by the Mojo's javadoc. You can specify the value as a Maven property:
<properties>
<maven.javadoc.skip>true</maven.javadoc.skip>
</properties>
or as a command-line argument: -Dmaven.javadoc.skip=true
, to skip generation of the Javadocs.
document.getElementById('TextBoxID').readOnly = true; //to enable readonly
document.getElementById('TextBoxID').readOnly = false; //to disable readonly
Me, I'd do it something like this:
HTML:
onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"
JS:
function myfunction(params)
{
var path = params.path;
/* do stuff */
// on ok condition
params.ok(params.okArgs);
// on cancel condition
params.cancel(params.cancelArgs);
}
But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.
After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC"
) you should loop over the table using the DefaultView not the DataTable instance itself
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
Console.WriteLine(r["Town"].ToString());
}
Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable
DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
Console.WriteLine(r["Town"].ToString());
}
try to align inner element like this:
top: 0;
bottom: 0;
margin: auto;
display: table;
and of course:
position: absolute;
It depends on the Test Construct around the operator. Your options are double parentheses, double brackets, single brackets, or test
.
If you use ((
…))
, you are testing arithmetic equality with ==
as in C:
$ (( 1==1 )); echo $?
0
$ (( 1==2 )); echo $?
1
(Note: 0
means true
in the Unix sense and a failed test results in a non-zero number.)
Using -eq
inside of double parentheses is a syntax error.
If you are using [
…]
(or single brackets) or [[
…]]
(or double brackets), or test
you can use one of -eq
, -ne
, -lt
, -le
, -gt
, or -ge
as an arithmetic comparison.
$ [ 1 -eq 1 ]; echo $?
0
$ [ 1 -eq 2 ]; echo $?
1
$ test 1 -eq 1; echo $?
0
The ==
inside of single or double brackets (or the test
command) is one of the string comparison operators:
$ [[ "abc" == "abc" ]]; echo $?
0
$ [[ "abc" == "ABC" ]]; echo $?
1
As a string operator, =
is equivalent to ==
. Also, note the whitespace around =
or ==
: it’s required.
While you can do [[ 1 == 1 ]]
or [[ $(( 1+1 )) == 2 ]]
it is testing the string equality — not the arithmetic equality.
So -eq
produces the result probably expected that the integer value of 1+1
is equal to 2
even though the right-hand side is a string and has a trailing space:
$ [[ $(( 1+1 )) -eq "2 " ]]; echo $?
0
While a string comparison of the same picks up the trailing space and therefore the string comparison fails:
$ [[ $(( 1+1 )) == "2 " ]]; echo $?
1
And a mistaken string comparison can produce a completely wrong answer. 10
is lexicographically less than 2
, so a string comparison returns true
or 0
. So many are bitten by this bug:
$ [[ 10 < 2 ]]; echo $?
0
The correct test for 10
being arithmetically less than 2
is this:
$ [[ 10 -lt 2 ]]; echo $?
1
In comments, there is a question about the technical reason why using the integer -eq
on strings returns true for strings that are not the same:
$ [[ "yes" -eq "no" ]]; echo $?
0
The reason is that Bash is untyped. The -eq
causes the strings to be interpreted as integers if possible including base conversion:
$ [[ "0x10" -eq 16 ]]; echo $?
0
$ [[ "010" -eq 8 ]]; echo $?
0
$ [[ "100" -eq 100 ]]; echo $?
0
And 0
if Bash thinks it is just a string:
$ [[ "yes" -eq 0 ]]; echo $?
0
$ [[ "yes" -eq 1 ]]; echo $?
1
So [[ "yes" -eq "no" ]]
is equivalent to [[ 0 -eq 0 ]]
Last note: Many of the Bash specific extensions to the Test Constructs are not POSIX and therefore may fail in other shells. Other shells generally do not support [[...]]
and ((...))
or ==
.
Hello I realize this post is old, but here is my opinion anyway. This error arises when you close the console output window using the close icon instead of pressing "any key to continue"
Excel 2007 has a feature for doing this under the "Data" tab that works pretty nicely.
I found a solution for this problem try to run this command in terminal
ps -ef | grep postgres
kill process by this command
sudo kill -9 PID
Rookie, if you want to write a file to server by socket, how about using fileoutputstream instead of dataoutputstream? dataoutputstream is more fit for protocol-level read-write. it is not very reasonable for your code in bytes reading and writing. loop to read and write is necessary in java io. and also, you use a buffer way. flush is necessary. here is a code sample: http://www.rgagnon.com/javadetails/java-0542.html
My fourpenneth: my SSH keys were set up in Cygwin, at C:\cygwin\home\<user>.ssh, so I pointed SSH to this folder instead of the default (Win7) C:\Users\<user>\ssh, as per these instructions: http://wiki.eclipse.org/EGit/User_Guide/Remote#Eclipse_SSH_Configuration
and used the ssh protocol, and it works fine. Trying to use the git protocol still gives "User not supported on the git protocol", though.
The correct approach is to use preprocessing
For example
th:field="*{__${myVar}__}"
Using explicit parameters, it would be:
$msbuild = 'C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe'
start-Process -FilePath $msbuild -ArgumentList '/v:q','/nologo'
EDIT: quotes.
In addition to the nested scrolling NestedScrollView
added one major functionality, which could even make it interesting outside of nested contexts: It has build in support for OnScrollChangeListener
. Adding a OnScrollChangeListener
to the original ScrollView
below API 23 required subclassing ScrollView
or messing around with the ViewTreeObserver
of the ScrollView
which often means even more work than subclassing. With NestedScrollView
it can be done using the build-in setter.
I found this maven
repo where you could download from directly a zip
file containing all the jars you need.
The solution I prefer is using Maven
, it is easy and you don't have to download each jar
alone. You can do it with the following steps:
Create an empty folder anywhere with any name you prefer, for example spring-source
Create a new file named pom.xml
Copy the xml below into this file
Open the spring-source
folder in your console
Run mvn install
After download finished, you'll find spring jars in /spring-source/target/dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-source-download</groupId>
<artifactId>SpringDependencies</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>download-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Also, if you need to download any other spring project, just copy the dependency
configuration from its corresponding web page.
For example, if you want to download Spring Web Flow
jars, go to its web page, and add its dependency
configuration to the pom.xml
dependencies
, then run mvn install
again.
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can set the width in pixels via inline styling:
<input type="text" name="text" style="width: 195px;">
You can also set the width with a visible character length:
<input type="text" name="text" size="35">
I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.
<div class="form-group">
<div class="col-sm-12">
<label for="user_login">Username</label>
<input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
</div>
</div>
Check out this demo.
Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.
<form action="#" method="post" class="form-horizontal">
Check out this demo.
When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.
To answer your question and on all variable substitutions
echo "$\{var}"
echo "Substitute the value of var."
echo "$\{var:-word}"
echo "If var is null or unset, word is substituted for var. The value of var does not change."
echo "$\{var:=word}"
echo "If var is null or unset, var is set to the value of word."
echo "$\{var:?message}"
echo "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."
echo "$\{var:+word}"
echo "If var is set, word is substituted for var. The value of var does not change."
You have to add extra parameter -g, which generates source level debug information. It will look like:
gcc -g prog.c
After that you can use gdb in common way.
Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.
So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title
attribute).
There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.
On the other hand, in HTML 5 you have two options:
input of type number
:
<input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
– only validates the range – if user enters a non-number, an empty value is submitted
– the field visual is enhanced with increment / decrement controls (browser dependent)
the pattern
attribute:
<input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
<input type="text" pattern="\d{3}" title="Format: 3 digits" />
– this gives you a full contorl over the format (anything you can specify by regular expression)
– no visual difference / enhancement
But here you still rely on browser capabilities, so do a server-side validation in either case.
the -v option for curl is too verbose in the error output which contains the leading *
(status line) or >
(request head field) or <
(response head field). to get only the request head field:
curl -v -sS www.stackoverflow.com 2>&1 >/dev/null | grep '>' | cut -c1-2 --complement
to get only the request head field:
curl -v -sS www.stackoverflow.com 2>&1 >/dev/null | grep '<' | cut -c1-2 --complement
or to dump it into /tmp/test.txt
file with the -D option
curl -D /tmp/test.txt -sS www.stackoverflow.com > /dev/null
in order to filter the -v
output, you should direct the error output to terminal and the std output to /dev/null, the -s option is to forbid the progress metering
I'd suggest avoiding in-line JavaScript:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
var check = confirm("Are you sure you want to leave?");
if (check == true) {
return true;
}
else {
return false;
}
};
}?
The above updated to reduce space, though maintaining clarity/function:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
return confirm("Are you sure you want to leave?");
};
}
A somewhat belated update, to use addEventListener()
(as suggested, by bažmegakapa, in the comments below):
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].addEventListener('click', reallySure);
}
The above binds a function to the event of each individual link; which is potentially quite wasteful, when you could bind the event-handling (using delegation) to an ancestor element, such as the following:
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
function actionToFunction (event) {
switch (event.target.tagName.toLowerCase()) {
case 'a' :
reallySure(event);
break;
default:
break;
}
}
document.body.addEventListener('click', actionToFunction);
Because the event-handling is attached to the body
element, which normally contains a host of other, clickable, elements I've used an interim function (actionToFunction
) to determine what to do with that click. If the clicked element is a link, and therefore has a tagName
of a
, the click-handling is passed to the reallySure()
function.
References: