If you are here to just convert Timestamp into DateTime,
Timestamp timestamp = widget.firebaseDocument[timeStampfield];
DateTime date = Timestamp.fromMillisecondsSinceEpoch(
timestamp.millisecondsSinceEpoch).toDate();
Is this issue resolved.
I am getting this error: ERROR in node_modules/ngx-restangular/lib/ngx-restangular-http.d.ts(3,27): error TS2307: Cannot find module '@angular/common/http/src/response'.
After updating my angular to version=8
If a bean is in the same package in which it is @Autowired, then it will never cause such an issue. However, beans are not accessible from different packages by default. To fix this issue follow these steps :
@ComponentScan(basePackages = {"your.company.domain.package"})
public class SpringExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringExampleApplication.class, args);
}
}
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
In Centos 7
Error : publickey,gssapi-keyex,gssapi-with-mic
Ans : Root access to vi /etc/ssh/sshd_config and change the PasswordAuthentication ( no ) to yes.
2 . Restart the sshd services
root> systemctl restart sshd.service
You can get selected value also with help of click() by passing the selected value through the function
<md-select placeholder="Select Categorie"
name="Select Categorie" >
<md-option *ngFor="let list of categ" [value]="list.value" (click)="sub_cat(list.category_id)" >
{{ list.category }}
</md-option>
</md-select>
If you're like me, and would rather not make this security hole system or user-wide, then you can add a config option to any git repos that need this by running this command in those repos. (note only works with git version >= 2.10, released 2016-09-04)
git config core.sshCommand 'ssh -oHostKeyAlgorithms=+ssh-dss'
This only works after the repo is setup however. If you're not comfortable adding a remote manually (and just want to clone) then you can run the clone like this:
GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss' git clone ssh://user@host/path-to-repository
then run the first command to make it permanent.
If you don't have the latest, and still would like to keep the hole as local as possible I recommend putting
export GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss'
in a file somewhere, say git_ssh_allow_dsa_keys.sh
, and source
ing it when needed.
I landed this question in 2019. MY problem was updating table1 with table2 ignoring the variables with different name in both tables. I was getting the same error as mentioned in question: Error Code: 1364. Field 'id' doesn't have a default value in mysql. Here is how solved it:
Table 1 Schema : id ( unique & auto increment)| name | profile | Age Table 2 Schema: motherage| father| name| profile
This solved my error: INSERT IGNORE INTO table2 (name,profile) SELECT name, profile FROM table1
Swift 5: In the main view controller, or main navigation controller if you have,
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override var prefersStatusBarHidden: Bool {
return false
}
And "View controller-based status bar appearance" in plist must be YES, otherwise the above code will not be called.
If you want to hide status bar when launching app, "Status bar is initially hidden" in plist must be YES. This can prevent launch image from being distorted when extra blue bar showing on screen top.
for i,j in enumerate(words): # i---index of word----j
#now you got index of your words (present in i)
print(i)
You don't need to close the project and go to command line to invoke grade:clean. Go to Build-> Rebuild Project
public class SecureSocket {
static {
// System.setProperty("javax.net.debug", "all");
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
}
public static void main(String[] args) {
String GhitHubSSLFile = "https://raw.githubusercontent.com/Yash-777/SeleniumWebDrivers/master/pom.xml";
try {
String str = readCloudFileAsString(GhitHubSSLFile);
// new String(Files.readAllBytes(Paths.get( "D:/Sample.file" )));
System.out.println("Cloud File Data : "+ str);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readCloudFileAsString( String urlStr ) throws java.io.IOException {
if( urlStr != null && urlStr != "" ) {
java.io.InputStream s = null;
String content = null;
try {
URL url = new URL( urlStr );
s = (java.io.InputStream) url.getContent();
content = IOUtils.toString(s, "UTF-8");
}
}
return content.toString();
}
return null;
}
Do it like this:
SSLSocket socket = (SSLSocket) sslFactory.createSocket(host, port);
socket.setEnabledProtocols(new String[]{"SSLv3", "TLSv1"});
I got this error with this ... unfortunate... package I have to use and I don't have source for. After much digging (thank you, Stack Overflow) and trying endless combinations, I finally got things running by:
Creating the JKS with the entire certificate chain.
Making sure the key in the JKS had the alias of the FQDN of the machine.
Renaming the alias of the certificate for my machine ${FQDN}.cert
This took endless experimentation with the java command line options:
-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager
-Djava.security.debug=access:stack
My key and CSR were produced in OpenSSL so I had to import the key with:
openssl pkcs12 -export -in cert.pem -inkey cert.key -CAfile fullChain.pem -name ${FQDN} -out cert.p12
keytool -importkeystore -destkeystore cert.jks -srckeystore cert.p12 -srcstoretype PKCS12
keytool complains about the format so I converted the format followed by adding my cert chain:
keytool -importkeystore -srckeystore cert.jks -destkeystore cert_p12.jks -deststoretype pkcs12
keytool -import -trustcacerts -alias 'DigiCert Global Root G2 IntermediateCA' -keystore cert_p12.jks -file cert2.pem -storepass "$STOREPASS" -keypass "$KEYPASS"
keytool -import -trustcacerts -alias 'DigiCert Global Root G2' -keystore cert_p12.jks -file cert3.pem -storepass "$STOREPASS" -keypass "$KEYPASS"
(where cert2.pem and cert3.pem were downloaded from the DigiCert web site and converted to PEM format.)
When I restarted the application with the resulting jks
file, things started to work.
Something else I figured out as part of this. You can check the certificate chain by using:
openssl x509 -in cert2.pem -noout -text
for all your certificates and studying the output, paying attention to the X509v3 Authority Key Identifier:
and X509v3 Authority Key Identifier:
lines. The X509v3 Authority Key Identifier:
of one level matches the X509v3 Subject Key Identifier:
of the next higher level. You found the top of chain when the Issuer:
string matches the Subject:
string.
I hope this can save somebody some of the time it took me.
Use onkeypress
. Check if the pressed key is enter (keyCode = 13). if yes, call the searching()
function.
HTML
<input name="keywords" type="text" id="keywords" size="50" onkeypress="handleKeyPress(event)">
JAVASCRIPT
function handleKeyPress(e){
var key=e.keyCode || e.which;
if (key==13){
searching();
}
}
Here is a snippet showing it in action:
document.getElementById("msg1").innerHTML = "Default";_x000D_
function handle(e){_x000D_
document.getElementById("msg1").innerHTML = "Trigger";_x000D_
var key=e.keyCode || e.which;_x000D_
if (key==13){_x000D_
document.getElementById("msg1").innerHTML = "HELLO!";_x000D_
}_x000D_
}
_x000D_
<input type="text" name="box22" value="please" onkeypress="handle(event)"/>_x000D_
<div id="msg1"></div>
_x000D_
You can also do it without negative look ahead. You just need to add parentheses to that part of expression which you want to extract. This construction with parentheses is named group
.
Let's write python code:
string = """OK SYS 10 LEN 20 12 43
1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt
.
"""
search_result = re.search(r"^OK.*\n((.|\s)*).", string)
if search_result:
print(search_result.group(1))
Output is:
1233a.fdads.txt,23 /data/a11134/a.txt
3232b.ddsss.txt,32 /data/d13f11/b.txt
3452d.dsasa.txt,1234 /data/c13af4/f.txt
^OK.*\n
will find first line with OK statement, but we don't want to extract it so leave it without parentheses. Next is part which we want to capture: ((.|\s)*)
, so put it inside parentheses. And in the end of regexp we look for a dot .
, but we also don't want to capture it.
P.S: I find this answer is super helpful to understand power of groups. https://stackoverflow.com/a/3513858/4333811
neater:
function BlockID() {
return {
"s":"Images/Block_01.png",
"g":"Images/Block_02.png",
"C":"Images/Block_03.png",
"d":"Images/Block_04.png"
}
}
or just
var images = {
"s":"Images/Block_01.png",
"g":"Images/Block_02.png",
"C":"Images/Block_03.png",
"d":"Images/Block_04.png"
}
A SimpleDateFormat
, as its name indicates, formats Date
s. Not a Calendar
. So, if you want to format a GregorianCalendar
using a SimpleDateFormat
, you must convert the Calendar
to a Date
first:
dateFormat.format(calendar.getTime());
And what you see printed is the toString()
representation of the calendar. It's intended usage is debugging. It's not intended to be used to display a date in a GUI. For that, use a (Simple
)DateFormat
.
Finally, to convert from a String
to a Date
, you should also use a (Simple
)DateFormat
(its parse()
method), rather than splitting the String
as you're doing. This will give you a Date
object, and you can create a Calendar
from the Date
by instanciating it (Calendar.getInstance()
) and setting its time (calendar.setTime()
).
My advice would be: Googling is not the solution here. Reading the API documentation is what you need to do.
If you use the string literal exactly as you have shown us, the problem is the ;
character at the end. You may not include that in the query string in the JDBC calls.
As you are inserting only a single row, a regular INSERT
should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL
. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):
String query1 = "select substr(to_char(max_data),1,4) as year, " +
"substr(to_char(max_data),5,6) as month, max_data " +
"from dss_fin_user.acq_dashboard_src_load_success " +
"where source = 'CHQ PeopleSoft FS'";
String query2 = ".....";
String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();
reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();
pstmt.executeBatch();
con.commit();
Try put this before send e-mail
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; };
Remenber to add the using libs!
In my case, it was not worknig even after passing the proxy credentails.
Mistake was - forgot to remove the comment line.
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>345325</username>
<password>dfgasdfg</password>
<host>proxy.abc.com</host>
<port>8080</port>
<nonProxyHosts>proxy.abc.com</nonProxyHosts>
</proxy>
|--> ----------REMOVE THIS LINE AND CLOSE It above <proxy> tag
From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.
‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.
So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.
I had this same problem just a minute ago. which lead me here, which wasn't of any help. But I figured out what was the problem and fixed it. the problem was that in my header file i had declare one instance of the struct class named trig_node[SIZE]
my header...
struct TrigNode
{
float msin;
float mcos;
float mtan;
}trig_node[SIZE];
and in my .cpp file i have a function that access this instance and return the answer.
float cos_table_(float deg)
{
uint n = ((SIZE/DEGRE)*deg);
return trig_node[n % DEGRE].mcos;
}
which is what as causing my linking error. So, to fix that i place the instance of the trig table class "trig_node[SIZE]" in the .cpp file which cleared the error. so now the new fix looked something like this
my header...
struct TrigNode
{
float msin;
float mcos;
float mtan;
};
my .cpp file trig_node[SIZE]
float cos_table_(float deg)
{
uint n = ((SIZE/DEGRE)*deg);
return trig_node[n % DEGRE].mcos;
}
Why are you grouping by? Do you mean order by?
SELECT player_name, player_salary, player_salary * 1.1 AS NewSalary
FROM players
ORDER BY player_salary, player_name;
The server first tries to authenticate you by public key. That doesn't work (I guess you haven't set one up), so it then falls back to 'keyboard-interactive'. It should then ask you for a password, which presumably you're not getting right. Did you see a password prompt?
In my cases, I solved the problem when using the labs()
instead of abs()
.
In C# 8.0 you can get the last item with ^ operator full explanation
List<char> list = ...;
var value = list[^1];
// Gets translated to
var value = list[list.Count - 1];
You can also restrict keys to permissible commands (in the authorized_keys file).
I.e. the user would not log in via ssh and then have a restricted set of commands but rather would only be allowed to execute those commands via ssh (e.g. "ssh somehost bin/showlogfile")
If you want to match an expression starting with [
and ending with ]
, use \[[^\]]*\]
.
I have had a similar issue in iOS 8, 9 and 10 and the info above couldn't fix it, however I did discover a solution after a day of working on this. Granted it won't work for everyone but in my case my items were stacked in a column and had 0 height when it should have been content height. Switching the css to be row and wrap fixed the issue. This only works if you have a single item and they are stacked but since it took me a day to find this out I thought I should share my fix!
.wrapper {
flex-direction: column; // <-- Remove this line
flex-direction: row; // <-- replace it with
flex-wrap: wrap; // <-- Add wrapping
}
.item {
width: 100%;
}
I agree that having to query the SecurityContext for the current user stinks, it seems a very un-Spring way to handle this problem.
I wrote a static "helper" class to deal with this problem; it's dirty in that it's a global and static method, but I figured this way if we change anything related to Security, at least I only have to change the details in one place:
/**
* Returns the domain User object for the currently logged in user, or null
* if no User is logged in.
*
* @return User object for the currently logged in user, or null if no User
* is logged in.
*/
public static User getCurrentUser() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal()
if (principal instanceof MyUserDetails) return ((MyUserDetails) principal).getUser();
// principal object is either null or represents anonymous user -
// neither of which our domain User object can represent - so return null
return null;
}
/**
* Utility method to determine if the current user is logged in /
* authenticated.
* <p>
* Equivalent of calling:
* <p>
* <code>getCurrentUser() != null</code>
*
* @return if user is logged in
*/
public static boolean isLoggedIn() {
return getCurrentUser() != null;
}
You can use from bellow code for date and time :
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println("Add one day to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
System.out.println("Add one month to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 1);
System.out.println("Add one year to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.HOUR, 1);
System.out.println("Add one hour to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 1);
System.out.println("Add one minute to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 1);
System.out.println("Add one second to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println("Subtract one day from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println("Subtract one month from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
System.out.println("Subtract one year from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);
System.out.println("Subtract one hour from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -1);
System.out.println("Subtract one minute from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.SECOND, -1);
System.out.println("Subtract one second from current date : " + dateFormat.format(cal.getTime()));
Output :
Current Date Time : 2008/12/28 10:24:53
Add one day to current date : 2008/12/29 10:24:53
Add one month to current date : 2009/01/28 10:24:53
Add one year to current date : 2009/12/28 10:24:53
Add one hour to current date : 2008/12/28 11:24:53
Add one minute to current date : 2008/12/28 10:25:53
Add one second to current date : 2008/12/28 10:24:54
Subtract one day from current date : 2008/12/27 10:24:53
Subtract one month from current date : 2008/11/28 10:24:53
Subtract one year from current date : 2007/12/28 10:24:53
Subtract one hour from current date : 2008/12/28 09:24:53
Subtract one minute from current date : 2008/12/28 10:23:53
Subtract one second from current date : 2008/12/28 10:24:52
This link is good : See here
And see : See too
And : Here
And : Here
And : Here
If you need just time :
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Example with tables A and B:
A (parent) B (child)
============ =============
id | name pid | name
------------ -------------
1 | Alex 1 | Kate
2 | Bill 1 | Lia
3 | Cath 3 | Mary
4 | Dale NULL | Pan
5 | Evan
If you want to find parents and their kids, you do an INNER JOIN
:
SELECT id, parent.name AS parent
, pid, child.name AS child
FROM
parent INNER JOIN child
ON parent.id = child.pid
Result is that every match of a parent
's id
from the left table and a child
's pid
from the second table will show as a row in the result:
+----+--------+------+-------+
| id | parent | pid | child |
+----+--------+------+-------+
| 1 | Alex | 1 | Kate |
| 1 | Alex | 1 | Lia |
| 3 | Cath | 3 | Mary |
+----+--------+------+-------+
Now, the above does not show parents without kids (because their ids do not have a match in child's ids, so what do you do? You do an outer join instead. There are three types of outer joins, the left, the right and the full outer join. We need the left one as we want the "extra" rows from the left table (parent):
SELECT id, parent.name AS parent
, pid, child.name AS child
FROM
parent LEFT JOIN child
ON parent.id = child.pid
Result is that besides previous matches, all parents that do not have a match (read: do not have a kid) are shown too:
+----+--------+------+-------+
| id | parent | pid | child |
+----+--------+------+-------+
| 1 | Alex | 1 | Kate |
| 1 | Alex | 1 | Lia |
| 3 | Cath | 3 | Mary |
| 2 | Bill | NULL | NULL |
| 4 | Dale | NULL | NULL |
| 5 | Evan | NULL | NULL |
+----+--------+------+-------+
Where did all those NULL
come from? Well, MySQL (or any other RDBMS you may use) will not know what to put there as these parents have no match (kid), so there is no pid
nor child.name
to match with those parents. So, it puts this special non-value called NULL
.
My point is that these NULLs
are created (in the result set) during the LEFT OUTER JOIN
.
So, if we want to show only the parents that do NOT have a kid, we can add a WHERE child.pid IS NULL
to the LEFT JOIN
above. The WHERE
clause is evaluated (checked) after the JOIN
is done. So, it's clear from the above result that only the last three rows where the pid
is NULL will be shown:
SELECT id, parent.name AS parent
, pid, child.name AS child
FROM
parent LEFT JOIN child
ON parent.id = child.pid
WHERE child.pid IS NULL
Result:
+----+--------+------+-------+
| id | parent | pid | child |
+----+--------+------+-------+
| 2 | Bill | NULL | NULL |
| 4 | Dale | NULL | NULL |
| 5 | Evan | NULL | NULL |
+----+--------+------+-------+
Now, what happens if we move that IS NULL
check from the WHERE
to the joining ON
clause?
SELECT id, parent.name AS parent
, pid, child.name AS child
FROM
parent LEFT JOIN child
ON parent.id = child.pid
AND child.pid IS NULL
In this case the database tries to find rows from the two tables that match these conditions. That is, rows where parent.id = child.pid
AND child.pid IN NULL
. But it can find no such match because no child.pid
can be equal to something (1, 2, 3, 4 or 5) and be NULL at the same time!
So, the condition:
ON parent.id = child.pid
AND child.pid IS NULL
is equivalent to:
ON 1 = 0
which is always False
.
So, why does it return ALL rows from the left table? Because it's a LEFT JOIN! And left joins return rows that match (none in this case) and also rows from the left table that do not match the check (all in this case):
+----+--------+------+-------+
| id | parent | pid | child |
+----+--------+------+-------+
| 1 | Alex | NULL | NULL |
| 2 | Bill | NULL | NULL |
| 3 | Cath | NULL | NULL |
| 4 | Dale | NULL | NULL |
| 5 | Evan | NULL | NULL |
+----+--------+------+-------+
I hope the above explanation is clear.
Sidenote (not directly related to your question): Why on earth doesn't Pan
show up in none of our JOINs? Because his pid
is NULL
and NULL in the (not common) logic of SQL is not equal to anything so it can't match with any of the parent ids (which are 1,2,3,4 and 5). Even if there was a NULL there, it still wouldn't match because NULL
does not equal anything, not even NULL
itself (it's a very strange logic, indeed!). That's why we use the special check IS NULL
and not a = NULL
check.
So, will Pan
show up if we do a RIGHT JOIN
? Yes, it will! Because a RIGHT JOIN will show all results that match (the first INNER JOIN we did) plus all rows from the RIGHT table that don't match (which in our case is one, the (NULL, 'Pan')
row.
SELECT id, parent.name AS parent
, pid, child.name AS child
FROM
parent RIGHT JOIN child
ON parent.id = child.pid
Result:
+------+--------+------+-------+
| id | parent | pid | child |
+---------------+------+-------+
| 1 | Alex | 1 | Kate |
| 1 | Alex | 1 | Lia |
| 3 | Cath | 3 | Mary |
| NULL | NULL | NULL | Pan |
+------+--------+------+-------+
Unfortunately, MySQL does not have FULL JOIN
. You can try it in other RDBMSs, and it will show:
+------+--------+------+-------+
| id | parent | pid | child |
+------+--------+------+-------+
| 1 | Alex | 1 | Kate |
| 1 | Alex | 1 | Lia |
| 3 | Cath | 3 | Mary |
| 2 | Bill | NULL | NULL |
| 4 | Dale | NULL | NULL |
| 5 | Evan | NULL | NULL |
| NULL | NULL | NULL | Pan |
+------+--------+------+-------+
I fix the problem with under statement ; send data with url same GET methode
$.ajax({
url: 'includes/get_ajax_function.php?value=jack&id='+id,
type: 'post',
data: $('#b-info1').serializeArray(),
and get value with $_REQUEST['value']
OR $_GET['id']
In case you have to replace multiple values and if you don't mind "refactoring" your variable with as.factor(as.character(...)) you could try the following:
replace.values <- function(search, replace, x){
stopifnot(length(search) == length(replace))
xnew <- replace[ match(x, search) ]
takeOld <- is.na(xnew) & !is.na(x)
xnew[takeOld] <- x[takeOld]
return(xnew)
}
iris$Species <- as.factor(search=c("oldValue1","oldValue2"),
replace=c("newValue1","newValue2"),
x=as.character(iris$Species))
<mvc:annotation-driven />
means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository
to tell spring that a class is a Dao without having to extend JpaDaoSupport
or some other subclass of DaoSupport. Similarly @Controller
tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.
When spring starts up it reads its XML configuration file and looks for <bean
elements within it if it sees something like <bean class="com.example.Foo" />
and Foo was marked up with @Controller
it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.
Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" />
is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller
, or @Repository
, or @Service
, or @Component
and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." />
in the XML configuration files.
In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.
Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.
Hope this helps.
1st: If you know that your code isn't right, you should fix it before do anything!
You could do something like this:
function validateForm() {
var radios = document.getElementsByName("yesno");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Must check some option!");
return formValid;
}?
See it in action: http://jsfiddle.net/FhgQS/
Both answers look correct to me.
The first arr[i] = temp;
should be removed
You should do a second loop to print all elements, not just half the array. The loop that does the reverse doesn't need to print it.
I know it's late, although there is a much more convenient way to solve this kind of problem! The other solutions are quite messy; this is how I would do it:
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === 0 ? 'https://' : 'http://';
...or even without condition if you prefer:
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,strpos( $_SERVER["SERVER_PROTOCOL"],'/'))).'://';
Have a look at $_SERVER["SERVER_PROTOCOL"]
$ git submodule status --recursive
Is also a life saver in this situation. You can use it and gitk --all
to keep track of your sha1's and verify your sub-modules are pointing at what you think they are.
If you have .Net installed, a tool to generate XSD schemas and classes is already included by default.
For me, the XSD tool is installed under the following structure. This may differ depending on your installation directory.
C:\Program Files\Microsoft Visual Studio 8\VC>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
xsd.exe -
Utility to generate schema or class files from given source.
xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/s] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]
Normally the classes and schemas that this tool generates work rather well, especially if you're going to be consuming them in a .Net language
I typically take the XML document that I'm after, push it through the XSD tool with the /o:<your path>
flag to generate a schema (xsd) and then push the xsd file back through the tool using the /classes /L:VB (or CS) /o:<your path>
flags to get classes that I can import and use in my day to day .Net projects
you can simply use onBackPressed();
or if you are using fragment you can use getActivity().onBackPressed()
Push down the whole button. I suggest this it is looking nice in button.
#button:active {
position: relative;
top: 1px;
}
if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.
You can use inline styling to limit the height:
<img src="" class="img-responsive" alt="" style="max-height: 400px;">
I think "disabled" excludes the input from being sent on the POST
You can also use lib-auto
xmlns:app="http://schemas.android.com/apk/lib-auto"
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
Another option if you want greater control over how rows are deemed to be invalid is
final <- final[!(is.na(final$rnor)) | !(is.na(rawdata$cfam)),]
Using the above, this:
gene hsap mmul mmus rnor cfam
1 ENSG00000208234 0 NA NA NA 2
2 ENSG00000199674 0 2 2 2 2
3 ENSG00000221622 0 NA NA 2 NA
4 ENSG00000207604 0 NA NA 1 2
5 ENSG00000207431 0 NA NA NA NA
6 ENSG00000221312 0 1 2 3 2
Becomes:
gene hsap mmul mmus rnor cfam
1 ENSG00000208234 0 NA NA NA 2
2 ENSG00000199674 0 2 2 2 2
3 ENSG00000221622 0 NA NA 2 NA
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
...where only row 5 is removed since it is the only row containing NAs for both rnor
AND cfam
. The boolean logic can then be changed to fit specific requirements.
by the way, the zoo package, if it is loaded, overrides the base as.Date() with its own which, by default, provides origin="1970-01-01".
(i mention this in case you find that sometimes you need to add the origin, and sometimes you don't.)
I am also faced the same issue
use this code:
// notice string() call
String resStr = response.body().string();
JSONObject json = new JSONObject(resStr);
it definitely works
I recommend Dowser. It is very easy to setup, and you need zero changes to your code. You can view counts of objects of each type through time, view list of live objects, view references to live objects, all from the simple web interface.
# memdebug.py
import cherrypy
import dowser
def start(port):
cherrypy.tree.mount(dowser.Root())
cherrypy.config.update({
'environment': 'embedded',
'server.socket_port': port
})
cherrypy.server.quickstart()
cherrypy.engine.start(blocking=False)
You import memdebug, and call memdebug.start. That's all.
I haven't tried PySizer or Heapy. I would appreciate others' reviews.
UPDATE
The above code is for CherryPy 2.X
, CherryPy 3.X
the server.quickstart
method has been removed and engine.start
does not take the blocking
flag. So if you are using CherryPy 3.X
# memdebug.py
import cherrypy
import dowser
def start(port):
cherrypy.tree.mount(dowser.Root())
cherrypy.config.update({
'environment': 'embedded',
'server.socket_port': port
})
cherrypy.engine.start()
I always use this code, which print the year to second in a tuple
import datetime
now = datetime.datetime.now()
time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)
print(time_now)
How about using a JavaScript trick?
var Avals = ss.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
I borrowed this idea from this answer. The Array.filter()
method is operating on the Avals
array, which contains all the cells in column A. By filtering on a native function's constructor, we get back only non-null elements.
This works for a single column only; if the range contains multiple columns,then the outcome of filter()
will include cells from all columns, and thus be outside the populated dimensions of the range.
Update The currently suggested way to start a Task is simply using Task.Run()
Task.Run(() => foo());
Note that this method is described as the best way to start a task see here
Previous answer
I like the Task Factory from System.Threading.Tasks. You can do something like this:
Task.Factory.StartNew(() =>
{
// Whatever code you want in your thread
});
Note that the task factory gives you additional convenience options like ContinueWith:
Task.Factory.StartNew(() => {}).ContinueWith((result) =>
{
// Whatever code should be executed after the newly started thread.
});
Also note that a task is a slightly different concept than threads. They nicely fit with the async/await keywords, see here.
Accoriding to EF6 (4,5 also) documentation: https://msdn.microsoft.com/en-us/data/hh949853#9
9.3 Context per request
Entity Framework’s contexts are meant to be used as short-lived instances in order to provide the most optimal performance experience. Contexts are expected to be short lived and discarded, and as such have been implemented to be very lightweight and reutilize metadata whenever possible. In web scenarios it’s important to keep this in mind and not have a context for more than the duration of a single request. Similarly, in non-web scenarios, context should be discarded based on your understanding of the different levels of caching in the Entity Framework. Generally speaking, one should avoid having a context instance throughout the life of the application, as well as contexts per thread and static contexts.
I had similar requirements but I didn't want to use v-model
to have the state in the parent component. Then I got this to work:
<input
type="checkbox"
:checked="checked"
@input="checked = $event.target.checked"
/>
To pass down the value from the parent, I made a small change on this and it works.
<input
type="checkbox"
:checked="aPropFrom"
@input="$emit('update:aPropFrom', $event.target.checked)"
/>
Are you trying to submit a form?
Listen to the submit
event instead.
This will handle click
and enter
.
If you must use enter key...
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
One gotcha is that the following is implementation dependent (according to the ANSI standard):
char x = -1;
x >> 1;
x can now be 127 (01111111) or still -1 (11111111).
In practice, it's usually the latter.
git branch branch_name --set-upstream-to your_new_remote/branch_name
-u
switchgit branch branch_name -u your_new_remote/branch_name
git branch --set-upstream branch_name your_new_remote/branch_name
You could try:
UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:@"firstView" owner:self options:nil] firstObject];
[self.view.containerView addSubview:firstViewUIView];
Unfortunately none of the above worked for me, so instead I added a label on top of the comboxbox that says "Please select". I used the following code to show and hide it:
When I initialise my combobox, if there is no selected value I bring it to the front and set the text:
PleaseSelectValueLabel.BringToFront();
PleaseSelectValueLabel.Text = Constants.AssessmentValuePrompt;
If there is a value selected I send it to the back:
PleaseSelectValueLabel.SendToBack();
I then use the following events to move the label to the front or back depending on whether the user has selected a value:
private void PleaseSelectValueLabel_Click(object sender, EventArgs e)
{
PleaseSelectValueLabel.SendToBack();
AssessmentValue.Focus();
}
private void AssessmentValue_Click(object sender, EventArgs e)
{
PleaseSelectValueLabel.SendToBack();
}
//if the user hasnt selected an item, make the please select label visible again
private void AssessmentValue_Leave(object sender, EventArgs e)
{
if (AssessmentValue.SelectedIndex < 0)
{
PleaseSelectValueLabel.BringToFront();
}
}
You can make a hard distinction instead of linear gradient by putting the second color to 0%
For instance,
Gradient - background: linear-gradient(80deg, #ff0000 20%, #0000ff 80%);
Hard distinction - background: linear-gradient(80deg, #ff0000 20%, #0000ff 0%);
Choose one from, where :my_date
is a string input parameter of yyyy-MM-dd
format:
SELECT EXTRACT(YEAR FROM CAST(:my_date AS DATE));
or
SELECT DATE_PART('year', CAST(:my_date AS DATE));
Better use CAST
than ::
as there may be conflicts with input parameters.
Use a DateFormat
. In an internationalized application, use the format provide by getInstance
. If you want to explicitly control the format, create a new SimpleDateFormat
yourself.
Not true for the OP, but this error can be caused by using single quotation marks ('
) instead of double ("
) for strings.
The JSON spec requires double quotation marks for strings.
E.g:
JSON.parse(`{"myparam": 'myString'}`)
gives the error, whereas
JSON.parse(`{"myparam": "myString"}`)
does not. Note the quotation marks around myString
.
Pythonic way to get text from Span tags:
driver.find_element_by_xpath("//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel clear')]").text
Select last_name, round (sysdate-hire_date)/7,0) as tuner
from employees
Where department_id = 90
order by last_name;
Sometimes, the minimal installation of Linux in Docker doesn't define the path and therefore it is necessary to call ping using ....
cd /usr/sbin
ping <ip>
You need to follow these steps before the token authentication
Create a Cluster Admin service account
kubectl create serviceaccount dashboard -n default
Add the cluster binding rules to your dashboard account
kubectl create clusterrolebinding dashboard-admin -n default --clusterrole=cluster-admin --serviceaccount=default:dashboard
Get the secret token with this command
kubectl get secret $(kubectl get serviceaccount dashboard -o jsonpath="{.secrets[0].name}") -o jsonpath="{.data.token}" | base64 --decode
Choose token authentication in the Kubernetes dashboard login page
Now you can able to login
@RobW's answer is correct, but this is more performant ! Because it uses a hashmap/set:
const customStringify = function (v) {
const cache = new Set();
return JSON.stringify(v, function (key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.has(value)) {
// Circular reference found
try {
// If this value does not reference a parent it can be deduped
return JSON.parse(JSON.stringify(value));
}
catch (err) {
// discard key if value cannot be deduped
return;
}
}
// Store value in our set
cache.add(value);
}
return value;
});
};
@ is a shortcut option for v-on. Use @ only when you want to execute some Vue methods. As you are not executing Vue methods, instead you are calling javascript function, you need to use onchange attribute to call javascript function
<select name="LeaveType" onchange="onChange(this.value)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
function onChange(value) {
console.log(value);
}
If you want to call Vue methods, do it like this-
<select name="LeaveType" @change="onChange($event)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
new Vue({
...
...
methods:{
onChange:function(event){
console.log(event.target.value);
}
}
})
You can use v-model data attribute on the select element to bind the value.
<select v-model="selectedValue" name="LeaveType" onchange="onChange(this.value)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
new Vue({
data:{
selectedValue : 1, // First option will be selected by default
},
...
...
methods:{
onChange:function(event){
console.log(this.selectedValue);
}
}
})
Hope this Helps :-)
Azure Data Studio - free and from Microsoft - offers automatic formatting (ctrl + shift + p while editing -> format document). More information about Azure Data Studio here.
While this is not SSMS, it's great for writing queries, free and an official product from Microsoft. It's even cross-platform. Short story: Just switch to Azure Data Studio to write your queries!
Update: Actually Azure Data Studio is in some way the recommended tool for writing queries (source)
Use Azure Data Studio if you: [..] Are mostly editing or executing queries.
I had the same problem and this is my solution. I had the following code:
se.GiftDescription = rs.getString(1);
se.GiftAmount = rs.getInt(2);
And I changed it to:
se.GiftDescription = rs.getString("DESCRIPTION");
se.GiftAmount = rs.getInt("AMOUNT");
And the problem was, after I restarted my PC, the column positions changed. That's why I got this error.
C99 way, also supported by VC++ compiler.
#define FOO(fmt, ...) printf(fmt, ##__VA_ARGS__)
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
I got the same issue and it was resolved by changing the Application pool identity of the application pool under which the web application is running to NetworkService
MSDN has an outline of the purpose of the global.asax file.
Effectively, global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.
You can use it by by choosing Add > New Item > Global Application Class in Visual Studio. Once you've added the file, you can add code under any of the events that are listed (and created by default, at least in Visual Studio 2008):
There are other events that you can also hook into, such as "LogRequest".
The documentation says (also here):
If npm was invoked with root privileges, then it will change the uid to the user account or uid specified by the
user
config, which defaults tonobody
. Set theunsafe-perm
flag to run scripts with root privileges.
Your options are:
Run npm install
with the --unsafe-perm
flag:
[sudo] npm install --unsafe-perm
Add the unsafe-perm
flag to your package.json
:
"config": {
"unsafe-perm":true
}
Don't use the preinstall
script to install global modules, install them separately and then run the regular npm install
without root privileges:
sudo npm install -g coffee-script node-gyp
npm install
Related:
Use int
function with second parameter 16, to convert a hex string to an integer. Finally, use hex
function to convert it back to a hexadecimal number.
print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4
Instead you could directly do
print hex(int("0xAD4", 16) + 0x200) # 0xcd4
Below are two methods that are superior to looping. Both handle a "no-find" case.
VLOOKUP
with error-handling if the variable doesn't exist (INDEX/MATCH
may be a better route than VLOOKUP
, ie if your two columns A and B were in reverse order, or were far apart)VBAs FIND
method (matching a whole string in column A given I use the xlWhole
argument)
Sub Method1()
Dim strSearch As String
Dim strOut As String
Dim bFailed As Boolean
strSearch = "trees"
On Error Resume Next
strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
If Err.Number <> 0 Then bFailed = True
On Error GoTo 0
If Not bFailed Then
MsgBox "corresponding value is " & vbNewLine & strOut
Else
MsgBox strSearch & " not found"
End If
End Sub
Sub Method2()
Dim rng1 As Range
Dim strSearch As String
strSearch = "trees"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
Else
MsgBox strSearch & " not found"
End If
End Sub
Open multiple instances of Toad and execute.
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
Use your developer's tool of choice and check if the tr
, td
or img
has any padding or margins.
You must have a server-side script to handle your request, it can't be done using javascript.
To send raw data without URIencoding or escaping special characters to the php and save it as new txt
file you can send ajax request using post
method and FormData
like:
JS:
var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);
PHP:
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
Edit:
As Florian mentioned below, the XHR fallback is not required since FormData
is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:
var xhr = new XMLHttpRequest();
Also please note that this works only for browsers that support FormData
such as IE +10.
You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
or as I did it,
os.system('cp '+ rawfile + ' rawdata.dat')
where rawfile
is the name that I had generated inside the program.
This is a Linux only solution
It is in visual studio. In the designer page, it is on in the menu bar, there is XTRAREPORTS field. You can show up panels using it
Here is some code that will return the installed .NET details:
<%@ Page Language="VB" Debug="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<%
Dim cmnNETver, cmnNETdiv, aspNETver, aspNETdiv As Object
Dim winOSver, cmnNETfix, aspNETfil(2), aspNETtxt(2), aspNETpth(2), aspNETfix(2) As String
winOSver = Environment.OSVersion.ToString
cmnNETver = Environment.Version.ToString
cmnNETdiv = cmnNETver.Split(".")
cmnNETfix = "v" & cmnNETdiv(0) & "." & cmnNETdiv(1) & "." & cmnNETdiv(2)
For filndx As Integer = 0 To 2
aspNETfil(0) = "ngen.exe"
aspNETfil(1) = "clr.dll"
aspNETfil(2) = "KernelBase.dll"
If filndx = 2
aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), aspNETfil(filndx))
Else
aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64", cmnNETfix, aspNETfil(filndx))
End If
If File.Exists(aspNETpth(filndx)) Then
aspNETver = Diagnostics.FileVersionInfo.GetVersionInfo(aspNETpth(filndx))
aspNETtxt(filndx) = aspNETver.FileVersion.ToString
aspNETdiv = aspNETtxt(filndx).Split(" ")
aspNETfix(filndx) = aspNETdiv(0)
Else
aspNETfix(filndx) = "Path not found... No version found..."
End If
Next
Response.Write("Common MS.NET Version (raw): " & cmnNETver & "<br>")
Response.Write("Common MS.NET path: " & cmnNETfix & "<br>")
Response.Write("Microsoft.NET full path: " & aspNETpth(0) & "<br>")
Response.Write("Microsoft.NET Version (raw): " & aspNETtxt(0) & "<br>")
Response.Write("<b>Microsoft.NET Version: " & aspNETfix(0) & "</b><br>")
Response.Write("ASP.NET full path: " & aspNETpth(1) & "<br>")
Response.Write("ASP.NET Version (raw): " & aspNETtxt(1) & "<br>")
Response.Write("<b>ASP.NET Version: " & aspNETfix(1) & "</b><br>")
Response.Write("OS Version (system): " & winOSver & "<br>")
Response.Write("OS Version full path: " & aspNETpth(2) & "<br>")
Response.Write("OS Version (raw): " & aspNETtxt(2) & "<br>")
Response.Write("<b>OS Version: " & aspNETfix(2) & "</b><br>")
%>
Here is the new output, cleaner code, more output:
Common MS.NET Version (raw): 4.0.30319.42000
Common MS.NET path: v4.0.30319
Microsoft.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe
Microsoft.NET Version (raw): 4.6.1586.0 built by: NETFXREL2
Microsoft.NET Version: 4.6.1586.0
ASP.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
ASP.NET Version (raw): 4.7.2110.0 built by: NET47REL1LAST
ASP.NET Version: 4.7.2110.0
OS Version (system): Microsoft Windows NT 10.0.14393.0
OS Version full path: C:\Windows\system32\KernelBase.dll
OS Version (raw): 10.0.14393.1715 (rs1_release_inmarket.170906-1810)
OS Version: 10.0.14393.1715
Try this:
body {
background-image:url(img/background.jpg);
background-repeat: no-repeat;
min-height: 679px;
background-size: cover;
}
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
Paste here in ~/.tmux.conf
set -g mouse on
and run on terminal
tmux source-file ~/.tmux.conf
The closest to Eclipse will be Ctrl+Button2 Click (Scroll click)
It's called Quick Doc in IntelliJ, I wish guys from JetBrains one day add quick doc like Eclipse with Ctrl+Mouse Move it's so much better.
In my case only with only mouse move is a bit annoying, so if you search in Preferences/Settings --> Keymap for "quick documentation" you will find:
You have to add a CSP meta tag in the head section of your app's index.html
As per https://github.com/apache/cordova-plugin-whitelist#content-security-policy
Content Security Policy
Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly).
On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g.
<video>
& WebSockets are not blocked). So, in addition to the whitelist, you should use a Content Security Policy<meta>
tag on all of your pages.On Android, support for CSP within the system webview starts with KitKat (but is available on all versions using Crosswalk WebView).
Here are some example CSP declarations for your
.html
pages:<!-- Good default declaration: * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: * Enable inline JS: add 'unsafe-inline' to default-src * Enable eval(): add 'unsafe-eval' to default-src --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *"> <!-- Allow requests to foo.com --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com"> <!-- Enable all requests, inline styles, and eval() --> <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"> <!-- Allow XHRs via https only --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' https:"> <!-- Allow iframe to https://cordova.apache.org/ --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org">
Update: there are two possible scenarios here:
You are determining if an object is a collection;
You are determining if a class is a collection.
The solutions are slightly different but the principles are the same. You also need to define what exactly constitutes a "collection". Implementing either Collection
or Map
will cover the Java Collections.
Solution 1:
public static boolean isCollection(Object ob) {
return ob instanceof Collection || ob instanceof Map;
}
Solution 2:
public static boolean isClassCollection(Class c) {
return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c);
}
(1) can also be implemented in terms of (2):
public static boolean isCollection(Object ob) {
return ob != null && isClassCollection(ob.getClass());
}
I don't think the efficiency of either method will be greatly different from the other.
This Perl code removes commas at the end of the line:
perl -pe 's/,$//' file > file.nocomma
This variation still works if there is whitespace after the comma:
perl -lpe 's/,\s*$//' file > file.nocomma
This variation edits the file in-place:
perl -i -lpe 's/,\s*$//' file
This variation edits the file in-place, and makes a backup file.bak
:
perl -i.bak -lpe 's/,\s*$//' file
You can put iframe inside a <div>
<div>
<iframe></iframe>
</div>
It works because it is now inside a block element.
According to the Git repo of the BFG tool, it "removes large or troublesome blobs as git-filter-branch does, but faster - and is written in Scala".
There is no solution to this problem. As of IE11 on Windows 8, Microsoft no longer allows ActiveX plugins to run in its browser space. There is absolutely nothing that a third party developer can do about it.
A similar thing has recently happened with the Chrome browser which no longer supports NPAPI plugins. Instead Chrome only supports PPAPI plugins which are useless for system level tasks once performed by NPAPI plugins.
So developers needing browser support for system interactive plugins can only recommend either the Firefox browser or the ASPS web browser.
This isn't a very beautiful answer, but it's what I use to create zero-length vectors:
0[-1] # numeric
""[-1] # character
TRUE[-1] # logical
0L[-1] # integer
A literal is a vector of length 1, and [-1]
removes the first element (the only element in this case) from the vector, leaving a vector with zero elements.
As a bonus, if you want a single NA
of the respective type:
0[NA] # numeric
""[NA] # character
TRUE[NA] # logical
0L[NA] # integer
The simple way of doing this would be (assuming your list is in 'l'):
>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]
Complete sample:
>>> l = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
...
>>> counter
{'and': 3, '': 1, 'merry': 1, 'rise.': 1, 'small;': 1, 'Moon': 1, 'cheerful': 1, 'bright': 1, 'Cats': 5, 'are': 3, 'have': 2, 'bright,': 1, 'for': 1, 'their': 1, 'rather': 1, 'when': 1, 'to': 3, 'airs': 1, 'black': 2, 'They': 1, 'practise': 1, 'caterwaul.': 1, 'pleasant': 1, 'hear': 1, 'they': 1, 'white,': 1, 'wait': 1, 'And': 2, 'like': 1, 'Jellicle': 6, 'eyes;': 1, 'the': 1, 'faces,': 1, 'graces': 1}
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]
With simple I mean working in nearly every version of python.
if you don't understand some of the functions used in this sample, you can always do this in the interpreter (after pasting the code above):
>>> help(counter.get)
>>> help(sorted)
Dim P As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
P = New Uri(P).LocalPath
"We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."
from http://api.jquery.com/jquery.each/
Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:
function findXX(word) {_x000D_
$.each(someArray, function(index, value) {_x000D_
$('body').append('-> ' + index + ":" + value + '<br />');_x000D_
return !(value == word);_x000D_
});_x000D_
}_x000D_
$(function() {_x000D_
someArray = new Array();_x000D_
someArray[0] = 't5';_x000D_
someArray[1] = 'z12';_x000D_
someArray[2] = 'b88';_x000D_
someArray[3] = 's55';_x000D_
someArray[4] = 'e51';_x000D_
someArray[5] = 'o322';_x000D_
someArray[6] = 'i22';_x000D_
someArray[7] = 'k954';_x000D_
findXX('o322');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
A bit more with comments:
function findXX(myA, word) {_x000D_
let br = '<br />';//create once_x000D_
let myHolder = $("<div />");//get a holder to not hit DOM a lot_x000D_
let found = false;//default return_x000D_
$.each(myA, function(index, value) {_x000D_
found = (value == word);_x000D_
myHolder.append('-> ' + index + ":" + value + br);_x000D_
return !found;_x000D_
});_x000D_
$('body').append(myHolder.html());// hit DOM once_x000D_
return found;_x000D_
}_x000D_
$(function() {_x000D_
// no horrid global array, easier array setup;_x000D_
let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];_x000D_
// pass the array and the value we want to find, return back a value_x000D_
let test = findXX(someArray, 'o322');_x000D_
$('body').append("<div>Found:" + test + "</div>");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
NOTE: array .includes()
may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
Or just .find()
to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
.text()
will give you the actual text in between HTML tags. For example, the paragraph text in between p
tags. What is interesting to note is that it will give you all the text in the element you are targeting with with your $
selector plus all the text in the children elements of that selected element. So If you have multiple p
tags with text inside the body element and you do a $(body).text()
, you will get all the text from all the paragraphs. (Text only, not the p
tags themselves.)
.html()
will give you the text and the tags. So $(body).html()
will basically give you your entire page HTML page
.val()
works for elements that have a value
attribute, such as input
.
An input
does not have contained text or HTML and thus .text()
and .html()
will both be null
for input
elements.
To complete the answer from Sotorios Delimanolis.
It's true that ResponseEntity
gives you more flexibility but in most cases you won't need it and you'll end up with these ResponseEntity
everywhere in your controller thus making it difficult to read and understand.
If you want to handle special cases like errors (Not Found, Conflict, etc.), you can add a HandlerExceptionResolver
to your Spring configuration. So in your code, you just throw a specific exception (NotFoundException
for instance) and decide what to do in your Handler (setting the HTTP status to 404), making the Controller code more clear.
Ugly but works:
>>> s
'aaa12333bb445bb54b5b52'
>>> a = ''.join(filter(lambda x : x.isdigit(), s))
>>> a
'1233344554552'
>>>
:goto 21490
will take you to the 21490th byte in the buffer.
The question is LeetCode #148, and there are plenty of solutions offered in all major languages. Mine is as follows, but I'm wondering about the time complexity. In order to find the middle element, we traverse the complete list each time. First time n
elements are iterated over, second time 2 * n/2
elements are iterated over, so on and so forth. It seems to be O(n^2)
time.
def sort(linked_list: LinkedList[int]) -> LinkedList[int]:
# Return n // 2 element
def middle(head: LinkedList[int]) -> LinkedList[int]:
if not head or not head.next:
return head
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def merge(head1: LinkedList[int], head2: LinkedList[int]) -> LinkedList[int]:
p1 = head1
p2 = head2
prev = head = None
while p1 and p2:
smaller = p1 if p1.val < p2.val else p2
if not head:
head = smaller
if prev:
prev.next = smaller
prev = smaller
if smaller == p1:
p1 = p1.next
else:
p2 = p2.next
if prev:
prev.next = p1 or p2
else:
head = p1 or p2
return head
def merge_sort(head: LinkedList[int]) -> LinkedList[int]:
if head and head.next:
mid = middle(head)
mid_next = mid.next
# Makes it easier to stop
mid.next = None
return merge(merge_sort(head), merge_sort(mid_next))
else:
return head
return merge_sort(linked_list)
Use this:
document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
In my case, after installing the Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019 (both x86 and x64 version), the issue is solved.
But wait! Why did I know this? I will tell you my experience.
When your program meets a bug, the first thing you need to do is finding the log to debug. But where is the log file that records all the events of the Android emulator? Click Help?Show log in Explorer. And then a new window is oepned, where a file called idea.log is located, and that log file is what we are looking for.
But this file may has recorded too much verbose info, so let's do following processes to get a more simple one:
·Exit Android Studio
·Delete the idea.log
·Open Android Studio
·Click Tools? AVD Manerger
·Start one of emulators you have created, and needless to say, the error will occur again. But the idea.log will be created and the error is recorded into the log file now!
·Exit Android Studio.
·Open the idea.log and begin to analyze it.
·Search "emulator", and in my case there are 2 messages catching my eyes:
INFO - manager.EmulatorProcessHandler - Emulator: E:\cache\SDK\emulator\emulator.exe -netdelay none -netspeed full -avd Nexus_5_API_22
INFO - manager.EmulatorProcessHandler - Emulator: Process finished with exit code -1073741515 (0xC0000135)
Obviously, the "exit code 1073741515" is something important, and actually many people have asked what it means in StackOverFlow, but unfortunately, I can't find any useful info about it. So let's pass it and focus on the first message.
Open the command line (Press "Win"+"R" ? Enter "CMD" ? Click "OK"), copy the above message E:\cache\SDK\emulator\emulator.exe -netdelay none -netspeed full -avd Nexus_5_API_22
and paste it to the command line. Press Enter.
I totally didn't know what this command meaned, but it's reasonable to deduce that Android Studio ran this command and resulted in the error, so I will try to reproduce the issue.
After that, an error window pop up, saying "...VCRUNTIME140_1.dll is missing...". I know I have been close to the answer. So I serch "VCRUNTIME140_1.dll Missing" on google, and people said that "downloading and installing both the x86 and x64 versions of the Microsoft Visual C++ 2015 - 2019 Redistributable will resolve this problem".
So I download both the x86 and x64 version and install them. After doing this, I run the emulator again, and everything goes well.
x.times do |i|
something(i+1)
end
If you have User scoped settings you may also have a user.config file somewhere in the [Userfolder]\AppData\Local\[ProjectName]
folder.
If you later remove the User scoped settings the user.config will not automatically be removed, and it's presence may cause the same error message. Deleting the folder did the trick for me.
I just had this problem, and this was my solution:
#floatingMenu + * {
margin-top: 35px;
}
Adjust for the height of your floatingMenu. If you don't know for sure that it's a div following then you can use *
rather than div
. This is all valid CSS2.
Here's a straight forward implementation of the md5sum
command that computes and displays the MD5 of the file specified on the command-line. It needs to be linked against the OpenSSL library (gcc md5.c -o md5 -lssl
) to work. It's pure C, but you should be able to adapt it to your C++ application easily enough.
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
unsigned char result[MD5_DIGEST_LENGTH];
// Print the MD5 sum as hex-digits.
void print_md5_sum(unsigned char* md) {
int i;
for(i=0; i <MD5_DIGEST_LENGTH; i++) {
printf("%02x",md[i]);
}
}
// Get the size of the file by its file descriptor
unsigned long get_size_by_fd(int fd) {
struct stat statbuf;
if(fstat(fd, &statbuf) < 0) exit(-1);
return statbuf.st_size;
}
int main(int argc, char *argv[]) {
int file_descript;
unsigned long file_size;
char* file_buffer;
if(argc != 2) {
printf("Must specify the file\n");
exit(-1);
}
printf("using file:\t%s\n", argv[1]);
file_descript = open(argv[1], O_RDONLY);
if(file_descript < 0) exit(-1);
file_size = get_size_by_fd(file_descript);
printf("file size:\t%lu\n", file_size);
file_buffer = mmap(0, file_size, PROT_READ, MAP_SHARED, file_descript, 0);
MD5((unsigned char*) file_buffer, file_size, result);
munmap(file_buffer, file_size);
print_md5_sum(result);
printf(" %s\n", argv[1]);
return 0;
}
If you use numpy
, this is easy:
slice = arr[:2,:2]
or if you want the 0's,
slice = arr[0:2,0:2]
You'll get the same result.
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
What I did here is that I take each desired row 1 at a time (arr[i]
). I then slice the columns I want out of that row and add it to the list that I'm building.
If you naively try: arr[0:2]
You get the first 2 rows which if you then slice again arr[0:2][0:2]
, you're just slicing the first two rows over again.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
Why not use a list comprehension?
In Python 2
ran_floats = [random.uniform(low,high) for _ in xrange(size)]
In Python 3, range
works like xrange
(ref)
ran_floats = [random.uniform(low,high) for _ in range(size)]
try
total.Text = DateTime.Now.ToString()
or
Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()
You declare Start
as an Integer
, while you are trying to put a DateTime
in it, which is not possible.
This problem occures when you use your service via other application.If application has config file just add your service config information to this file. In my situation there wasn't any config file so I use this technique and it worked fine.Just store url address in application,read it and using BasicHttpBinding() method send it to service application as parameter.This is simple demonstration how I did it:
Configuration config = new Configuration(dataRowSet[0]["ServiceUrl"].ToString());
var remoteAddress = new System.ServiceModel.EndpointAddress(config.Url);
SimpleService.PayPointSoapClient client =
new SimpleService.PayPointSoapClient(new System.ServiceModel.BasicHttpBinding(),
remoteAddress);
SimpleService.AccountcredResponse response = client.AccountCred(request);
Just add like this in case 1: like this
case 0:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).lastModifiedDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
and put this method at end of the your class
static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
Date d1 = null;
Date d2 = null;
try {
d1 = sdf.parse(ord1.lastModifiedDate);
d2 = sdf.parse(ord2.lastModifiedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); //descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
If you get this sort of thing appearing suddenly, it usually means the project is missing some frameworks it needs. Libraries and dependent projects can require frameworks, so if you've added one recently then that can cause this error.
To add frameworks, right click on the project name in the project view, select Add
, then select Existing frameworks...
from the list. Then find the framework with the symbols you're missing.
As to how you find which frameworks you need, I've found using google the easiest, though you could probably use the Xcode help search too. Search for one of the symbols, doing your best to work out the unmangled name (e.g., SCNetworkReachabilityGetFlags
), and then the first documentation link you find at developer.apple.com is often the right one. You usually don't have to hunt very far. In this case, that's this page:
https://developer.apple.com/documentation/systemconfiguration/scnetworkreachability-g7d
Then at the top of the page, it tells you which framework to use, SystemConfiguration
in this case. So add that to the project, and compile again.
Then just keep doing this until it works...
Edit: I've never used the simulator, but this is what you do on the device - I assume it's the same...
You can also use the filter function from the dplyr package which returns rows with matching conditions.
> library(dplyr)
> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
HTMLEntities can do it:
: jmglov@laurana; sudo gem install htmlentities
Successfully installed htmlentities-4.2.4
: jmglov@laurana; irb
irb(main):001:0> require 'htmlentities'
=> []
irb(main):002:0> HTMLEntities.new.decode "¡I'm highly annoyed with character references!"
=> "¡I'm highly annoyed with character references!"
Download the file of website and start it with the commandline switch "/layout" (see msdn to download visual studio 2015 installer for offline installation). So C:\vs_community.exe /layout
for example. It asks for a location and the download begins.
EDIT: With the ISO version you still need internet connection to be able to install ALL the features. As pointed out by Augusto Barreto.
Finding all possible paths is a hard problem, since there are exponential number of simple paths. Even finding the kth shortest path [or longest path] are NP-Hard.
One possible solution to find all paths [or all paths up to a certain length] from s
to t
is BFS, without keeping a visited
set, or for the weighted version - you might want to use uniform cost search
Note that also in every graph which has cycles [it is not a DAG] there might be infinite number of paths between s
to t
.
You can also use the customized link as:
https://example.com/wp-login.php?redirect_to=https://example.com/news.php
AF_INET
is an address family that is used to designate the type of addresses that your socket can communicate with (in this case, Internet Protocol v4 addresses). When you create a socket, you have to specify its address family, and then you can only use addresses of that type with the socket. The Linux kernel, for example, supports 29 other address families such as UNIX (AF_UNIX
) sockets and IPX (AF_IPX
), and also communications with IRDA and Bluetooth (AF_IRDA
and AF_BLUETOOTH
, but it is doubtful you'll use these at such a low level).
For the most part, sticking with AF_INET
for socket programming over a network is the safest option. There is also AF_INET6
for Internet Protocol v6 addresses.
Hope this helps,
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
After a lot of search and testing I got this solution which is simple to implement and easier to customize. In this solution:
Simple put the flowing CSS at the top of your page and all checkboxes style will change like this:
input[type=checkbox] {
transform: scale(1.5);
}
input[type=checkbox] {
width: 30px;
height: 30px;
margin-right: 8px;
cursor: pointer;
font-size: 17px;
visibility: hidden;
}
input[type=checkbox]:after {
content: " ";
background-color: #fff;
display: inline-block;
margin-left: 10px;
padding-bottom: 5px;
color: #00BFF0;
width: 22px;
height: 25px;
visibility: visible;
border: 1px solid #00BFF0;
padding-left: 3px;
border-radius: 5px;
}
input[type=checkbox]:checked:after {
content: "\2714";
padding: -5px;
font-weight: bold;
}
_x000D_
<input type="checkbox" id="checkbox1" />
<label for="checkbox1">Checkbox</label>
_x000D_
var month = mydate.getMonth(); // month (in integer 0-11)
var year = mydate.getFullYear(); // year
Then all you would need to have is an array of months:
var months = ['Jan', 'Feb', 'Mar', ...];
And then to show it:
alert(months[month] + " " + year);
From the documentation:
Paths associated with the default
provider
are generally interoperable with thejava.io.File
class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented byjava.io.File
. ThetoPath
method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as thejava.io.File
object. In addition, thetoFile
method is useful to construct aFile
from theString
representation of aPath
.
(emphasis mine)
So, for toFile
:
Returns a
File
object representing this path.
And toPath
:
Returns a
java.nio.file.Path
object constructed from the this abstract path.
try http://code.google.com/p/swinghtmltemplate/
this will allow you to create gui with html-like syntax
I typically have a secrets.py
that is stored separately from my other python scripts and is not under version control. Then whenever required, you can do from secrets import <required_pwd_var>
. This way you can rely on the operating systems in-built file security system without re-inventing your own.
Using Base64
encoding/decoding is also another way to obfuscate the password though not completely secure
More here - Hiding a password in a python script (insecure obfuscation only)
With Eclipse and Windows:
you have to copy 2 files - xxxPROJECTxxx.properties - log4j.properties here : C:\Eclipse\CONTENER\TOMCAT\apache-tomcat-7\lib
String name = "admin";
char[] ch = name.toString().toCharArray(); //it will read and store each character of String and store into char[].
for(int i=0; i<ch.length; i++)
{
System.out.println(ch[i]+
"-->"+
(int)ch[i]); //this will print both character and its value
}
for me I was still getting
'adb' is not recognized as an internal or external command,
operable program or batch file.
even after setting the path in environment variables...... restarting Android Studio solved the problem.
In my case, my Dockerfile contained an installation step, which produced the vendor
directory (the PHP equivalent of node_modules
). I then COPY
this directory over to the final application image. Therefore, I could not put vendor
in my .dockerignore
. My solution was simply to delete the directory before performing composer install
(the PHP equivalent of npm install
).
FROM composer AS composer
WORKDIR /app
COPY . .
RUN rm -rf vendor \
&& composer install
FROM richarvey/nginx-php-fpm
WORKDIR /var/www/html
COPY --from=composer /app .
This solution works and does not bloat the final image, but it is not ideal, because the vendor
directory on the host is copied into the Docker context during the build process, which adds time.
In my case, none of the above helped. Only upgrade of Intellij from 2017.3 to 2018.2 helped.
Do not try 2018.1 as it had a bug wherein the Find files popup would not come up.
Use the CREATE SCHEMA syntax or, in SSMS, drill down through Databases -> YourDatabaseName -> Security -> Schemas. Right-click on the Schemas folder and select "New Schema..."
The string is basically bounded from the place where it is pointed to (char *ptrChar;
), to the null character (\0
).
The char *ptrChar;
actually points to the beginning of the string (char array), and thus that is the pointer to that string,
so when you do like ptrChar[x]
for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).
From http://vyaskn.tripod.com/programming_faq.htm#q17:
Oracle has a rownum to access rows of a table using row number or row id. Is there any equivalent for that in SQL Server? Or how to generate output with row number in SQL Server?
There is no direct equivalent to Oracle's rownum or row id in SQL Server. Strictly speaking, in a relational database, rows within a table are not ordered and a row id won't really make sense. But if you need that functionality, consider the following three alternatives:
Add an
IDENTITY
column to your table.Use the following query to generate a row number for each row. The following query generates a row number for each row in the authors table of pubs database. For this query to work, the table must have a unique key.
SELECT (SELECT COUNT(i.au_id) FROM pubs..authors i WHERE i.au_id >= o.au_id ) AS RowID, au_fname + ' ' + au_lname AS 'Author name' FROM pubs..authors o ORDER BY RowID
Use a temporary table approach, to store the entire resultset into a temporary table, along with a row id generated by the
IDENTITY()
function. Creating a temporary table will be costly, especially when you are working with large tables. Go for this approach, if you don't have a unique key in your table.
You may be able to use the built-in function dir()
to produce similar behavior to PHP's isset()
, something like:
if 'foo' in dir(): # returns False, foo is not defined yet.
pass
foo = 'b'
if 'foo' in dir(): # returns True, foo is now defined and in scope.
pass
dir()
returns a list of the names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir.
This is the command that you need to execute on the mirror:
git remote update
This is a common issue when working with deep or complex json object, so I try to avoid try/catch or embedding multiple checks which would make the code unreadable, I usually use this little piece of code in all my procect to do the job.
/* ex: getProperty(myObj,'aze.xyz',0) // return myObj.aze.xyz safely
* accepts array for property names:
* getProperty(myObj,['aze','xyz'],{value: null})
*/
function getProperty(obj, props, defaultValue) {
var res, isvoid = function(x){return typeof x === "undefined" || x === null;}
if(!isvoid(obj)){
if(isvoid(props)) props = [];
if(typeof props === "string") props = props.trim().split(".");
if(props.constructor === Array){
res = props.length>1 ? getProperty(obj[props.shift()],props,defaultValue) : obj[props[0]];
}
}
return typeof res === "undefined" ? defaultValue: res;
}
Both versions using sets didn't work for me (tested with MySQL 5.5). The function ELT() returns the whole set. Considering the WHILE statement is only avaible in PROCEDURE context i added it to my solution:
DROP PROCEDURE IF EXISTS __main__;
DELIMITER $
CREATE PROCEDURE __main__()
BEGIN
SET @myArrayOfValue = '2,5,2,23,6,';
WHILE (LOCATE(',', @myArrayOfValue) > 0)
DO
SET @value = LEFT(@myArrayOfValue, LOCATE(',',@myArrayOfValue) - 1);
SET @myArrayOfValue = SUBSTRING(@myArrayOfValue, LOCATE(',',@myArrayOfValue) + 1);
END WHILE;
END;
$
DELIMITER ;
CALL __main__;
To be honest, i don't think this is a good practice. Even if its realy necessary, this is barely readable and quite slow.
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.
Assuming you're using a std::ofstream
to write to file, the following snippet will write a std::string
to file in human readable form:
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
I couldn't do it on a Galaxy S3 (non rooted).
For me it would hang saying...
restaring in tcp mode
So i found this series of commands quite useful.
First disconnect your device, start from scratch (cmd in admin mode and all the stuff).
connect your device and write in CMD/Terminal:
adb kill-server
control should return as normal. Now type and enter
adb tcpip 5555
you will see..
- daemon not running. starting it now on port 5037 *
- daemon started successfully * restarting in TCP mode port: 5555
and then connect device with
adb connect <IP>
That's how it worked for me after a lot of hassle!
UPDATE FOR ANDROID STUDIO
I noticed this doesn't work sometimes, even after correctly repeating steps a number of times. Catch was; sometimes ADB is yet not initialized by Studio unless, Android Tab at the bottom is opened and you see "Initializing Android Studio".
You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets. The proper method is for brackets to contain spacing within, and operators to contain spacing around. In some instances different combinations work; however, the following is intended to be a universal example.
if [ "$1" == "something" ]; then ## GOOD
if [ "$1" = "something" ]; then ## GOOD
if [ "$1"="something" ]; then ## BAD (operator spacing)
if ["$1" == "something"]; then ## BAD (bracket spacing)
Also, note double brackets are handled slightly differently compared to single brackets ...
if [[ $a == z* ]]; then # True if $a starts with a "z" (pattern matching).
if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching).
if [ $a == z* ]; then # File globbing and word splitting take place.
if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching).
I hope that helps!
null=True
sets NULL
(versus NOT NULL
) on the column in your DB. Blank values for Django field types such as DateTimeField
or ForeignKey
will be stored as NULL
in the DB.
blank
determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True
then the field will not be required, whereas if it's False
the field cannot be blank.
The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow NULL
values for that field. The exception is CharField
s and TextField
s, which in Django are never saved as NULL
. Blank values are stored in the DB as an empty string (''
).
A few examples:
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
Obviously, Those two options don't make logical sense to use (though there might be a use case for null=True, blank=False
if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR
and TEXT
types are never saved as NULL
by Django, so null=True
is unnecessary. However, you can manually set one of these fields to None
to force set it as NULL
. If you have a scenario where that might be necessary, you should still include null=True
.
Use PHP error handling functions to handle errors. How you do it depends on your needs. This system will intercept all errors and forward it however you want it Or supress it if you ask it to do so
Since this is one of the top search results for questions related to this I felt it was worth mentioning how you can make this work with Kendo().DropDownListFor() as well.
Everything is the same as with OnaBai's post except for how you select the item based off of its text and your selector.
To do that you would swap out dataItem.symbol for dataItem.[DataTextFieldName]. Whatever model field you used for .DataTextField() is what you will be comparing against.
@(Html.Kendo().DropDownListFor(model => model.Status.StatusId)
.Name("Status.StatusId")
.DataTextField("StatusName")
.DataValueField("StatusId")
.BindTo(...)
)
//So that your ViewModel gets bound properly on the post, naming is a bit
//different and as such you need to replace the periods with underscores
var ddl = $('#Status_StatusId').data('kendoDropDownList');
ddl.select(function(dataItem) {
return dataItem.StatusName === "Active";
});
Maybe declaring a range might workout better for you.
// fill in the starting and ending range programmatically this is just an example.
string startRange = "A1";
string endRange = "A1";
Excel.Range currentRange = (Excel.Range)excelWorksheet.get_Range(startRange , endRange );
currentRange.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.
You can however drop this web.config in the root of the folder or site where you want to set it:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>
</system.webServer>
</configuration>
That will inform the client to cache content for 7 days in that folder and all subfolders.
You can also do this by editing the IIS7 metabase via appcmd.exe
, like so:
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"7.00:00:00"
I had this same issue, and solved it with a solution similar to what Cheeso provided, above.
"doesn't work, says password is srequire, tried it a couple different ways "
Yep, that's because FTP sessions via a command file don't require the username to be prefaced with the string "user". Drop that, and try it.
Or, you could be seeing this because your FTP command file is not properly encoded (that bit me, too). That's the crappy part about generating a FTP command file at runtime. Powershell's out-file cmdlet does not have an encoding option that Windows FTP will accept (at least not one that I could find).
Regardless, as doing a WebClient.DownloadFile is the way to go.
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
yes it's possible to print a string to the console.
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string strMytestString("hello world");
cout << strMytestString;
return 0;
}
stdafx.h isn't pertinent to the solution, everything else is.
As an alternative, you can use an on-screen logging tool like ticker-log to view logs without having (convenient) access to the console.
Below is the method that worked for me on API 23-25 emulators. The explanation is provided for API 24 but works almost identically for other versions.
Credits: Jon Doe, zaidorx, pjl.
Warm advice for readers: please just go over the steps before following them, as some are automated via provided scripts.
In the AVD manager of Android studio (tested on v2.2.3), create a new emulator with the "Android 7.0 (Google APIs)" target:
Download the latest Open GApps package for the emulator's architecture (CPU/ABI). In my case it was x86_64
, but it can be something else depending on your choice of image during the device creation wizard. Interestingly, the architecture seems more important than the correct Android version (i.e. gapps for 6.0 also work on a 7.0 emulator).
Extract the .apk
files using from the following paths (relative to open_gapps-x86_64-7.0-pico-201#####.zip
):
.zip\Core\gmscore-x86_64.tar.lz\gmscore-x86_64\nodpi\priv-app\PrebuiltGmsCore\
.zip\Core\gsfcore-all.tar.lz\gsfcore-all\nodpi\priv-app\GoogleServicesFramework\
.zip\Core\gsflogin-all.tar.lz\gsflogin-all\nodpi\priv-app\GoogleLoginService\
.zip\Core\vending-all.tar.lz\vending-all\nodpi\priv-app\Phonesky\
Note that Open GApps use the Lzip compression, which can be opened using either the tool found on the Lzip website1,2, or on Mac using homebrew: brew install lzip
. Then e.g. lzip -d gmscore-x86_64.tar.lz
.
I'm providing a batch file that utilizes 7z.exe
and lzip.exe
to extract all required .apk
s automatically (on Windows):
@echo off
echo.
echo #################################
echo Extracting Gapps...
echo #################################
7z x -y open_gapps-*.zip -oGAPPS
echo Extracting Lzips...
lzip -d GAPPS\Core\gmscore-x86_64.tar.lz
lzip -d GAPPS\Core\gsfcore-all.tar.lz
lzip -d GAPPS\Core\gsflogin-all.tar.lz
lzip -d GAPPS\Core\vending-all.tar.lz
move GAPPS\Core\*.tar
echo.
echo #################################
echo Extracting tars...
echo #################################
7z e -y -r *.tar *.apk
echo.
echo #################################
echo Cleaning up...
echo #################################
rmdir /S /Q GAPPS
del *.tar
echo.
echo #################################
echo All done! Press any key to close.
echo #################################
pause>nul
To use this, save the script in a file (e.g. unzip_gapps.bat
) and put everything relevant in one folder, as demonstrated below:
Update the su
binary to be able to modify the permissions of the files we will later upload. A new su
binary can be found in the SuperSU by Chainfire package "Recovery flashable" zip
. Get the zip, extract it somewhere, create the a batch file with the following contents in the same folder, and finally run it:
adb root
adb remount
adb push eu.chainfire.supersu_2.78.apk /system/app/
adb push x64/su /system/xbin/su
adb shell chmod 755 /system/xbin/su
adb shell ln -s /system/xbin/su /system/bin/su
adb shell "su --daemon &"
adb shell rm /system/app/SdkSetup.apk
Put all .apk
files in one folder and create a batch file with these contents3:
START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24 -no-boot-anim -writable-system
adb wait-for-device
adb root
adb shell stop
adb remount
adb push PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore
adb push GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework
adb push GoogleLoginService.apk /system/priv-app/GoogleLoginService
adb push Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
adb shell su root "chmod 777 /system/priv-app/**"
adb shell su root "chmod 777 /system/priv-app/PrebuiltGmsCore/*"
adb shell su root "chmod 777 /system/priv-app/GoogleServicesFramework/*"
adb shell su root "chmod 777 /system/priv-app/GoogleLoginService/*"
adb shell su root "chmod 777 /system/priv-app/Phonesky/*"
adb shell start
Notice that the path E:\...\android-sdk\tools\emulator.exe
should be modified according to the location of the Android SDK on your system.
Execute the above batch file (the console should look like this afterwards):
O:\123>START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24 -no-boot-anim -writable-system
O:\123>adb wait-for-device
Hax is enabled
Hax ram_size 0x60000000
HAX is working and emulator runs in fast virt mode.
emulator: Listening for console connections on port: 5554
emulator: Serial number of this emulator (for ADB): emulator-5554
O:\123>adb root
O:\123>adb shell stop
O:\123>adb remount
remount succeeded
O:\123>adb push PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore/
[100%] /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk
O:\123>adb push GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework/
[100%] /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk
O:\123>adb push GoogleLoginService.apk /system/priv-app/GoogleLoginService/
[100%] /system/priv-app/GoogleLoginService/GoogleLoginService.apk
O:\123>adb push Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
[100%] /system/priv-app/Phonesky/Phonesky.apk
O:\123>adb shell su root "chmod 777 /system/priv-app/**"
O:\123>adb shell su root "chmod 777 /system/priv-app/PrebuiltGmsCore/*"
O:\123>adb shell su root "chmod 777 /system/priv-app/GoogleServicesFramework/*"
O:\123>adb shell su root "chmod 777 /system/priv-app/GoogleLoginService/*"
O:\123>adb shell su root "chmod 777 /system/priv-app/Phonesky/*"
O:\123>adb shell start
When the emulator loads - close it, delete the Virtual Device and then create another one using the same system image. This fixes the unresponsive Play Store app, "Google Play Services has stopped" and similar problems. It works because in the earlier steps we have actually modified the system image itself (take a look at the Date modified on android-sdk\system-images\android-24\google_apis\x86_64\system.img
). This means that every device created from now on with the system image will have gapps installed!
Start the new AVD. If it takes unusually long to load, close it and instead start it using:
START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24
adb wait-for-device
adb shell "su --daemon &"
After the AVD starts you will see the image below - notice the Play Store icon in the corner!
3 - I'm not sure all of these commands are needed, and perhaps some of them are overkill... it seems to work - which is what counts. :)
Try this instead:
$journalName = preg_replace('/\s+/', '_', $journalName);
Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).
Setting the underlying socket ReceiveTimeout
property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout
. You can read the docs for more information.
Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.
I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
There are two options:
Option 1: Using Template Literals.
const Message = 'This is a message';
<Text>
{`
Hi~
${Message}
`}
</Text>
Result:
Hi~
This is a message
Option 2: Use {'\n'} as line breaks.
<Text>
Hello {'\n'}
World!
</Text>
Result:
Hello
World!
First - do not edit anything in your gem path! It will influence all projects, and you will have a lot problems later...
In your project edit script/rails
this way:
#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__)
# THIS IS NEW:
require "rails/commands/server"
module Rails
class Server
def default_options
super.merge({
:Port => 10524,
:environment => (ENV['RAILS_ENV'] || "development").dup,
:daemonize => false,
:debugger => false,
:pid => File.expand_path("tmp/pids/server.pid"),
:config => File.expand_path("config.ru")
})
end
end
end
# END OF CHANGE
require 'rails/commands'
The principle is simple - you are monkey-patching the server runner - so it will influence just one project.
UPDATE: Yes, I know that the there is simpler solution with bash script containing:
#!/bin/bash
rails server -p 10524
but this solution has a serious drawback - it is boring as hell.
Note that events may be attached to the document itself rather than the element in question. In that case, you'll want to use:
$._data( $(document)[0], "events" );
And find the event with the correct selector:
And then look at the handler > [[FunctionLocation]]
Assuming you mean UNIX shell commands, just run
echo >> file.txt
echo
prints a newline, and the >>
tells the shell to append that newline to the file, creating if it doesn't already exist.
In order to properly answer the question, though, I'd need to know what you would want to happen if the file already does exist. If you wanted to replace its current contents with the newline, for example, you would use
echo > file.txt
EDIT: and in response to Justin's comment, if you want to add the newline only if the file didn't already exist, you can do
test -e file.txt || echo > file.txt
At least that works in Bash, I'm not sure if it also does in other shells.
If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ()
.
case
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore
But it'll be better if you show your full query to get context of what you actually need.
this is a select command
FROM
user
WHERE
application_key = 'dsfdsfdjsfdsf'
AND email NOT LIKE '%applozic.com'
AND email NOT LIKE '%gmail.com'
AND email NOT LIKE '%kommunicate.io';
this update command
UPDATE user
SET email = null
WHERE application_key='dsfdsfdjsfdsf' and email not like '%applozic.com'
and email not like '%gmail.com' and email not like '%kommunicate.io';
In my case I have a sequence called PS_LOG_SEQ
which had a LAST_NUMBER = 3920
.
I then imported some data from PROD
to my local machine and inserted into the PS_LOG
table. Production data had more than 20000
rows with the latest LOG_ID (primary key) being 20070. After importing I tried to insert new rows in this table but when saving I got an exception like this one:
ORA-00001: unique constraint (LOG.PS_LOG_PK) violated
Surely this has to do with the Sequence PS_LOG_SEQ
associated with the PS_LOG
table. The LAST_NUMBER
was colliding with data I imported which had already used the next ID value from the PS_LOG_SEQ
.
To solve that I used this command to update the sequence to the latest \ max(LOG_ID)
+ 1:
alter sequence PS_LOG_SEQ restart start with 20071;
This command reset the LAST_NUMBER
value and I could then insert new rows into the table. No more collision. :)
Note: this alter sequence
command is new in Oracle 12c.
Note: this blog post
documents the ALTER SEQUENCE RESTART option does exist, but as of 18c, is not documented. Its apparently intended for internal Oracle use.
Without any prefixes, e.g. at it's simplest:
.loading-spinner {
animation: rotate 1.5s linear infinite;
}
@keyframes rotate {
to {
transform: rotate(360deg);
}
}
Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"
This might be faster if you have many files. This uses the decorate-sort-undecorate pattern so that the last-modified date of each file is fetched only once rather than every time the sort algorithm compares two files. This potentially reduces the number of I/O calls from O(n log n) to O(n).
It's more code, though, so this should only be used if you're mainly concerned with speed and it is measurably faster in practice (which I haven't checked).
class Pair implements Comparable {
public long t;
public File f;
public Pair(File file) {
f = file;
t = file.lastModified();
}
public int compareTo(Object o) {
long u = ((Pair) o).t;
return t < u ? -1 : t == u ? 0 : 1;
}
};
// Obtain the array of (file, timestamp) pairs.
File[] files = directory.listFiles();
Pair[] pairs = new Pair[files.length];
for (int i = 0; i < files.length; i++)
pairs[i] = new Pair(files[i]);
// Sort them by timestamp.
Arrays.sort(pairs);
// Take the sorted pairs and extract only the file part, discarding the timestamp.
for (int i = 0; i < files.length; i++)
files[i] = pairs[i].f;
Try changing it to.
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
Object appears to be a more specific declaration than any. From the TypeScript spec (section 3):
All types in TypeScript are subtypes of a single top type called the Any type. The any keyword references this type. The Any type is the one type that can represent any JavaScript value with no constraints. All other types are categorized as primitive types, object types, or type parameters. These types introduce various static constraints on their values.
Also:
The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list.
Objects do not allow the same flexibility.
For example:
var myAny : any;
myAny.Something(); // no problemo
var myObject : Object;
myObject.Something(); // Error: The property 'Something' does not exist on value of type 'Object'.
From the javadoc for Set.iterator()
:
Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).
And, as already stated by shuuchan, a TreeSet
is an implemention of Set
that has a guaranteed order:
The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
If you are using Spring JDBC, you can use Spring's GeneratedKeyHolder class to get the inserted ID.
See this answer... How to get inserted id using Spring Jdbctemplate.update(String sql, obj...args)
Information on this topic is now available on Wikipedia at: Search data structure
+----------------------+----------+------------+----------+--------------+
| | Insert | Delete | Search | Space Usage |
+----------------------+----------+------------+----------+--------------+
| Unsorted array | O(1) | O(1) | O(n) | O(n) |
| Value-indexed array | O(1) | O(1) | O(1) | O(n) |
| Sorted array | O(n) | O(n) | O(log n) | O(n) |
| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |
| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |
| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |
| Heap | O(log n) | O(log n)** | O(n) | O(n) |
| Hash table | O(1) | O(1) | O(1) | O(n) |
+----------------------+----------+------------+----------+--------------+
* The cost to add or delete an element into a known location in the list
(i.e. if you have an iterator to the location) is O(1). If you don't
know the location, then you need to traverse the list to the location
of deletion/insertion, which takes O(n) time.
** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
arbitrary element.
There's a hook called useLocation in react-router v5, no need for HOC or other stuff, it's very succinctly and convenient.
import { useLocation } from 'react-router-dom';
const ExampleComponent: React.FC = () => {
const location = useLocation();
return (
<Router basename='/app'>
<main>
<AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />
</main>
</Router>
);
}
You can use either HttpClient
or RestSharp
. Since I do not know what your code is, here is an example using HttpClient
:
using (var client = new HttpClient())
{
// This would be the like http://www.uber.com
client.BaseAddress = new Uri("Base Address/URL Address");
// serialize your json using newtonsoft json serializer then add it to the StringContent
var content = new StringContent(YourJson, Encoding.UTF8, "application/json")
// method address would be like api/callUber:SomePort for example
var result = await client.PostAsync("Method Address", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
Detecting sheet of paper is kinda old school. If you want to tackle skew detection then it is better if you straightaway aim for text line detection. With this you will get the extremas left, right, top and bottom. Discard any graphics in the image if you dont want and then do some statistics on the text line segments to find the most occurring angle range or rather angle. This is how you will narrow down to a good skew angle. Now after this you put these parameters the skew angle and the extremas to deskew and chop the image to what is required.
As for the current image requirement, it is better if you try CV_RETR_EXTERNAL instead of CV_RETR_LIST.
Another method of detecting edges is to train a random forests classifier on the paper edges and then use the classifier to get the edge Map. This is by far a robust method but requires training and time.
Random forests will work with low contrast difference scenarios for example white paper on roughly white background.
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
In order to generate the value use
private static final long serialVersionUID = $randomLong$L;
$END$
and provide the randomLong template variable with the following value: groovyScript("new Random().nextLong().abs()")
https://pharsfalvi.wordpress.com/2015/03/18/adding-serialversionuid-in-idea/
Short solution for preventing user from using context menu, copy and cut in jQuery:
jQuery(document).bind("cut copy contextmenu",function(e){
e.preventDefault();
});
Also disabling text selection in CSS might come handy:
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =
:
HOME=c
An environment variable is a regular variable that has been marked for export to the environment.
export HOME
HOME=c
You can combine the assignment with the export
statement.
export HOME=c
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you, Thierry
Edit: Fixed the fill statement and template syntax.
You could always do just:
a=[1,2,3]
b=['a','b']
c=[1,2,3,4]
d=[1,2,3]
a==b #returns False
a==c #returns False
a==d #returns True
They're a bad idea in general because it's a truly rare condition where a failure (exceptional condition, more generically) is properly met with NO response whatsoever. On top of that, empty catch
blocks are a common tool used by people who use the exception engine for error checking that they should be doing preemptively.
To say that it's always bad is untrue...that's true of very little. There can be circumstances where either you don't care that there was an error or that the presence of the error somehow indicates that you can't do anything about it anyway (for example, when writing a previous error to a text log file and you get an IOException
, meaning that you couldn't write out the new error anyway).
$sql="SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Your_Table_Name' AND COLUMN_NAME = 'Your_New_Column_Name'";
$RESULT = mysqli_query($conn,$sql);
The abobe query return 0 if the column is not present in your table then you need to run alter query like below
if($RESULT){
$sqll="ALTER TABLE Your_table_Name ADD COLUMN Your_New_Column_Name varchar(20) NOT NULL DEFAULT 0";
}
For my case handling UIDeviceOrientationDidChangeNotification
was not good solution as it is called more frequent and UIDeviceOrientation
is not always equal to UIInterfaceOrientation
because of (FaceDown, FaceUp).
I handle it using UIApplicationDidChangeStatusBarOrientationNotification
:
//To add the notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeOrientation:)
//to remove the
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
...
- (void)didChangeOrientation:(NSNotification *)notification
{
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation)) {
NSLog(@"Landscape");
}
else {
NSLog(@"Portrait");
}
}
Consider fwrite():
<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
final long startTime = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
// Do something
}
final long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime));
Declare:
SET @a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (@a);
You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>()
. Try this:
@model LetLord.Models.Tenant
<div class="row-fluid">
<div class="span4 well-border">
@Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
</div>
</div>
As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.
Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.
With the repository pattern, you would only need to change one object and one repository. The impact is very small.
Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:
You have a single place to make changes to your data access
You have a single place responsible for a set of tables (usually)
It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests
There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!
Add the maven repository outside the buildscript
configuration block of your main build.gradle
file as follows:
repositories {
maven {
url "https://github.com/jitsi/jitsi-maven-repository/raw/master/releases"
}
}
Make sure that you add them after the following:
apply plugin: 'com.android.application'
@cmaster made the best elaborated answer. In brief:
git checkout master #
git pull # update local master from remote master
git checkout <your_branch>
git merge master # solve merge conflicts if you have`
You should not rewrite branch history instead keep them in actual state for future references. While merging to master, it creates one extra commit but that is cheap. Commits does not cost.
Instead of getting image row by row, you can put it directly to an array. For CV_8U type image, you can use byte array, for other types check here.
Mat img; // Should be CV_8U for using byte[]
int size = (int)img.total() * img.channels();
byte[] data = new byte[size];
img.get(0, 0, data); // Gets all pixels
You might use flush
to force validation constraints to be realised and detected in a known place rather than when the transaction is committed. It may be that commit
gets called implicitly by some framework logic, through declarative logic, the container, or by a template. In this case, any exception thrown may be difficult to catch and handle (it could be too high in the code).
For example, if you save()
a new EmailAddress object, which has a unique constraint on the address, you won't get an error until you commit.
Calling flush()
forces the row to be inserted, throwing an Exception if there is a duplicate.
However, you will have to roll back the session after the exception.
Another way to solve this kind of error is to start eclipse with this argument
-vmargs -Djava.net.preferIPv4Stack=true
Working fine with Eclipse (x64) 4.3.1
try this
json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)
Set<String> windows = driver.getWindowHandles();
Iterator<String> itr = windows.iterator();
//patName will provide you parent window
String patName = itr.next();
//chldName will provide you child window
String chldName = itr.next();
//Switch to child window
driver.switchto().window(chldName);
//Do normal selenium code for performing action in child window
//To come back to parent window
driver.switchto().window(patName);
This format is used to get current timestamp and stored in mysql
$date = date("Y-m-d H:i:s");
$update_query = "UPDATE db.tablename SET insert_time=".$date." WHERE username='" .$somename . "'";
If you are using Angular 4+ then you can just use titlecase
{{toUppercase | titlecase}}
don't have to write any pipes.
Try this one for Updating:
[HttpPost]
public ActionResult Edit(Models.MathClass mathClassModel)
{
//get current entry from db (db is context)
var item = db.Entry<Models.MathClass>(mathClassModel);
//change item state to modified
item.State = System.Data.Entity.EntityState.Modified;
//load existing items for ManyToMany collection
item.Collection(i => i.Students).Load();
//clear Student items
mathClassModel.Students.Clear();
//add Toner items
foreach (var studentId in mathClassModel.SelectedStudents)
{
var student = db.Student.Find(int.Parse(studentId));
mathClassModel.Students.Add(student);
}
if (ModelState.IsValid)
{
db.SaveChanges();
return RedirectToAction("Index");
}
return View(mathClassModel);
}
we can change the icon of markers, i did it on right click event. Lets see if it works for you...
// Create a Marker
var marker = new google.maps.Marker({
position: location,
map: map,
title:'Sample Tool Tip'
});
// Set Icon on any event
google.maps.event.addListener(marker, "rightclick", function() {
marker.setIcon('blank.png'); // set image path here...
});
thank you, your first error guides me here and the solution solve mine too!
for permission error, f = open('output', 'w+')
, change it into f = open(output+'output', 'w+')
.
or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.
for sure, you could probably running python/your script as administrator to pass permission error though
By using @ModelAttribute we can pass the model from one controller to another controller
[ Input to the first Controller][1]
[]: https://i.stack.imgur.com/rZQe5.jpg from jsp page first controller binds the form data with the @ModelAttribute to the User Bean
@Controller
public class FirstController {
@RequestMapping("/fowardModel")
public ModelAndView forwardModel(@ModelAttribute("user") User u) {
ModelAndView m = new ModelAndView("forward:/catchUser");
m.addObject("usr", u);
return m;
}
}
@Controller
public class SecondController {
@RequestMapping("/catchUser")
public ModelAndView catchModel(@ModelAttribute("user") User u) {
System.out.println(u); //retrive the data passed by the first contoller
ModelAndView mv = new ModelAndView("userDetails");
return mv;
}
}
Not sure of exact syntax (you use varchar2 type which means not SQL Server hence TOP) but you can use the LIMIT keyword for MySQL:
Select * FROM test_table WHERE user_id = value
ORDER BY DATE_ADDED DESC LIMIT 1
Or rownum in Oracle
SELECT * FROM
(Select rownum as rnum, * FROM test_table WHERE user_id = value ORDER BY DATE_ADDED DESC)
WHERE rnum = 1
If DB2, I'm not sure whether it's TOP, LIMIT or rownum...
fastest way
function:
var x=function(a,b,c,d){d=[];c=b-a+1;while(c--){d[c]=b--}return d},
theArray=x(lowEnd,highEnd);
or
var arr=[],c=highEnd-lowEnd+1;
while(c--){arr[c]=highEnd--}
EDIT
readable version
var arr = [],
c = highEnd - lowEnd + 1;
while ( c-- ) {
arr[c] = highEnd--
}
Demo
FOR THE DOWNVOTERS
performance
http://jsperf.com/for-push-while-set/2
faster in ie and 3x faster in firefox
only on aipad air the for loop is a little faster.
tested on win8, osx10.8, ubuntu14.04, ipad, ipad air, ipod;
with chrome,ff,ie,safari,mobile safari.
i would like to see the performance on older ie browsers where the for loop isn't that optimized!
In bash you can try this:
stringZ=abcABC123ABCabc
# 0123456789.....
# 0-based indexing.
echo ${stringZ:0:2} # prints ab
More samples in The Linux Documentation Project
Press Command+Shift+4
and then keep the mouse pointer on Simulator and then press "Space Bar"
key one camera icon will appear, now left click
the mouse. Your simulator screen shot is saved on desktop. You can take the screen shot any small screen in the same way.
You can use LINQ to XML,
XDocument doc = XDocument.Load(file);
var result = (from ele in doc.Descendants("section")
select ele).ToList();
foreach (var t in result)
{
if (t.Attributes("split").Count() != 0)
{
// Exist
}
// Suggestion from @UrbanEsc
if(t.Attributes("split").Any())
{
}
}
OR
XDocument doc = XDocument.Load(file);
var result = (from ele in doc.Descendants("section").Attributes("split")
select ele).ToList();
foreach (var t in result)
{
// Response.Write("<br/>" + t.Value);
}
When calling a function that is declared with throws
in Swift, you must annotate the function call site with try
or try!
. For example, given a throwing function:
func willOnlyThrowIfTrue(value: Bool) throws {
if value { throw someError }
}
this function can be called like:
func foo(value: Bool) throws {
try willOnlyThrowIfTrue(value)
}
Here we annotate the call with try
, which calls out to the reader that this function may throw an exception, and any following lines of code might not be executed. We also have to annotate this function with throws
, because this function could throw an exception (i.e., when willOnlyThrowIfTrue()
throws, then foo
will automatically rethrow the exception upwards.
If you want to call a function that is declared as possibly throwing, but which you know will not throw in your case because you're giving it correct input, you can use try!
.
func bar() {
try! willOnlyThrowIfTrue(false)
}
This way, when you guarantee that code won't throw, you don't have to put in extra boilerplate code to disable exception propagation.
try!
is enforced at runtime: if you use try!
and the function does end up throwing, then your program's execution will be terminated with a runtime error.
Most exception handling code should look like the above: either you simply propagate exceptions upward when they occur, or you set up conditions such that otherwise possible exceptions are ruled out. Any clean up of other resources in your code should occur via object destruction (i.e. deinit()
), or sometimes via defer
ed code.
func baz(value: Bool) throws {
var filePath = NSBundle.mainBundle().pathForResource("theFile", ofType:"txt")
var data = NSData(contentsOfFile:filePath)
try willOnlyThrowIfTrue(value)
// data and filePath automatically cleaned up, even when an exception occurs.
}
If for whatever reason you have clean up code that needs to run but isn't in a deinit()
function, you can use defer
.
func qux(value: Bool) throws {
defer {
print("this code runs when the function exits, even when it exits by an exception")
}
try willOnlyThrowIfTrue(value)
}
Most code that deals with exceptions simply has them propagate upward to callers, doing cleanup on the way via deinit()
or defer
. This is because most code doesn't know what to do with errors; it knows what went wrong, but it doesn't have enough information about what some higher level code is trying to do in order to know what to do about the error. It doesn't know if presenting a dialog to the user is appropriate, or if it should retry, or if something else is appropriate.
Higher level code, however, should know exactly what to do in the event of any error. So exceptions allow specific errors to bubble up from where they initially occur to the where they can be handled.
Handling exceptions is done via catch
statements.
func quux(value: Bool) {
do {
try willOnlyThrowIfTrue(value)
} catch {
// handle error
}
}
You can have multiple catch statements, each catching a different kind of exception.
do {
try someFunctionThatThowsDifferentExceptions()
} catch MyErrorType.errorA {
// handle errorA
} catch MyErrorType.errorB {
// handle errorB
} catch {
// handle other errors
}
For more details on best practices with exceptions, see http://exceptionsafecode.com/. It's specifically aimed at C++, but after examining the Swift exception model, I believe the basics apply to Swift as well.
For details on the Swift syntax and error handling model, see the book The Swift Programming Language (Swift 2 Prerelease).
I've investigated this issue, referring to the LayoutInflater docs and setting up a small sample demonstration project. The following tutorials shows how to dynamically populate a layout using LayoutInflater
.
Before we get started see what LayoutInflater.inflate()
parameters look like:
R.layout.main_page
)attachToRoot
is true
), or else simply an object that provides a set of LayoutParams
values for root of the returned hierarchy (if attachToRoot
is false
.)attachToRoot: Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams
for the root view in the XML.
Returns: The root View of the inflated hierarchy. If root was supplied and attachToRoot
is true
, this is root; otherwise it is the root of the inflated XML file.
Now for the sample layout and code.
Main layout (main.xml
):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Added into this container is a separate TextView, visible as small red square if layout parameters are successfully applied from XML (red.xml
):
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="25dp"
android:layout_height="25dp"
android:background="#ff0000"
android:text="red" />
Now LayoutInflater
is used with several variations of call parameters
public class InflaterTest extends Activity {
private View view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup parent = (ViewGroup) findViewById(R.id.container);
// result: layout_height=wrap_content layout_width=match_parent
view = LayoutInflater.from(this).inflate(R.layout.red, null);
parent.addView(view);
// result: layout_height=100 layout_width=100
view = LayoutInflater.from(this).inflate(R.layout.red, null);
parent.addView(view, 100, 100);
// result: layout_height=25dp layout_width=25dp
// view=textView due to attachRoot=false
view = LayoutInflater.from(this).inflate(R.layout.red, parent, false);
parent.addView(view);
// result: layout_height=25dp layout_width=25dp
// parent.addView not necessary as this is already done by attachRoot=true
// view=root due to parent supplied as hierarchy root and attachRoot=true
view = LayoutInflater.from(this).inflate(R.layout.red, parent, true);
}
}
The actual results of the parameter variations are documented in the code.
SYNOPSIS: Calling LayoutInflater
without specifying root leads to inflate call ignoring the layout parameters from the XML. Calling inflate with root not equal null
and attachRoot=true
does load the layout parameters, but returns the root object again, which prevents further layout changes to the loaded object (unless you can find it using findViewById()
).
The calling convention you most likely would like to use is therefore this one:
loadedView = LayoutInflater.from(context)
.inflate(R.layout.layout_to_load, parent, false);
To help with layout issues, the Layout Inspector is highly recommended.
Your query should look like
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
You can check the below question for help
It took me a while, but here's how I made it dynamic. It doesn't depend on a sorted table.
First I started with a column of state names (Column A) and a column of aircraft in each state (Column B). (Row 1 is a header row).
Finding the cell that contains the number of aircraft was:
=MATCH(MAX($B$2:$B$54),$B$2:$B$54,0)+MIN(ROW($B$2:$B$54))-1
I put that into a cell and then gave that cell a name, "StateRow" Then using the tips from above, I wound up with this:
=INDIRECT(ADDRESS(StateRow,1))
This returns the name of the state from the dynamic value in row "StateRow", column 1
Now, as the values in the count column change over time as more data is entered, I always know which state has the most aircraft.
Using dependency injection in your constructor makes managing the lifetime of your HttpClient
easier - taking the lifetime managemant outside of the code that needs it and making it easily changable at a later date.
My current preference is to create a seperate http client class that inherits from HttpClient
once per target endpoint domain and then make it a singleton using dependency injection. public class ExampleHttpClient : HttpClient { ... }
Then I take a constructor dependency on the custom http client in the service classes where I need access to that API. This solves the lifetime problem and has advantages when it comes to connection pooling.
You can see a worked example in related answer at https://stackoverflow.com/a/50238944/3140853
Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:
var peopleInOrder = people.OrderBy(person => person.LastName);
To sort in place, you'd need an IComparer<Person>
or a Comparison<Person>
. For that, you may wish to consider ProjectionComparer
in MiscUtil.
(I know I keep bringing MiscUtil up - it just keeps being relevant...)
When I try:
<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!" />
It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.
Pls try:
<script type="text/javascript">
function moreFields() {
alert("The text will be show");
}
</script>
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
Hope it helped.
Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:
(...) i18nTemplate.process(document, loadTimeData);
</script>
<script>start("current directory...")</script>
<script>addRow("..","..",1,"170 B","10/2/15, 8:32:45 PM");</script>
<script>addRow("fotos-interessantes-11.jpg","fotos-interessantes-> 11.jpg",false,"","");</script>
Maybe the most reliable way is to do something like this:
var folder = "img/";_x000D_
_x000D_
$.ajax({_x000D_
url : folder,_x000D_
success: function (data) {_x000D_
var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi; // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"_x000D_
var result = data.match(patt1);_x000D_
result = result.map(function(el) { return el.replace(/"/g, ""); }); // remove double quotes (") surrounding filename+extension // TODO: do this at regex!_x000D_
_x000D_
var uniqueNames = []; // this array will help to remove duplicate images_x000D_
$.each(result, function(i, el){_x000D_
var el_url_encoded = encodeURIComponent(el); // avoid images with same name but converted to URL encoded_x000D_
console.log("under analysis: " + el);_x000D_
if($.inArray(el, uniqueNames) === -1 && $.inArray(el_url_encoded, uniqueNames) === -1){_x000D_
console.log("adding " + el_url_encoded);_x000D_
uniqueNames.push(el_url_encoded);_x000D_
$("#slider").append( "<img src='" + el_url_encoded +"' alt=''>" ); // finaly add to HTML_x000D_
} else{ console.log(el_url_encoded + " already in!"); }_x000D_
});_x000D_
},_x000D_
error: function(xhr, textStatus, err) {_x000D_
alert('Error: here we go...');_x000D_
alert(textStatus);_x000D_
alert(err);_x000D_
alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);_x000D_
alert("responseText: "+xhr.responseText);_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
If you use different windows user, your SSH key and git settings will be independent.
If this is not an option for you, then your friend should add your SSH key to her Github account.
Although, previous solution will keep you pushing as yourself, but it will allow you to push into her repo. If you don't want this and work in different folder on the same pc, you can setup username and email locally inside a folder with git by removing -g
flag of the config command:
git config user.name her_username
git config user.email her_email
Alternatively, if you push over https
protocol, Github will prompt for username/password every time (unless you use a password manager).
This:
echo url('/');
And this:
echo asset('/');
both displayed the home url in my case :)
Per the documentation, scipy.io.wavfile.read(somefile)
returns a tuple of two items: the first is the sampling rate in samples per second, the second is a numpy
array with all the data read from the file:
from scipy.io import wavfile
samplerate, data = wavfile.read('./output/audio.wav')
Sorry my fault, try this...
#!/bin/bash
:
declare -r HEX_DIGITS="0123456789ABCDEF"
dec_value=$1
hex_value=""
until [ $dec_value == 0 ]; do
rem_value=$((dec_value % 16))
dec_value=$((dec_value / 16))
hex_digit=${HEX_DIGITS:$rem_value:1}
hex_value="${hex_digit}${hex_value}"
done
echo -e "${hex_value}"
Example:
$ ./dtoh 1024
400
As explained in other answers it converts the variable to a number. Specially useful when d
can be either a number or a string that evaluates to a number.
Example (using the addMonths
function in the question):
addMonths(34,1,true);
addMonths("34",1,true);
then the +d
will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d
is a number, a function or a string that can be converted to a number.
The earlier answers are calling helpers, but the following will help for calling controller methods. I have used this on Ruby on Rails 2.3.2.
First add the following code to your .irbrc file (which can be in your home directory)
class Object
def request(options = {})
url=app.url_for(options)
app.get(url)
puts app.html_document.root.to_s
end
end
Then in the Ruby on Rails console you can type something like...
request(:controller => :show, :action => :show_frontpage)
...and the HTML will be dumped to the console.