Without wanting to give you the answer here is the logic.
You have 2 possible values in each digit. you have 9 of them.
like in base 10 where you have 10 different values by digit say you have 2 of them (which makes from 0 to 99) : 0 to 99 makes 100 numbers. if you do the calcul you have an exponential function
base^numberOfDigits:
10^2 = 100 ;
2^9 = 512
You could use a sub query...
WHERE t1.field3 = (SELECT MAX(st1.field3) FROM table1 AS st1)
But I would actually move this out of the where clause and into the join statement, as an AND for the ON clause.
In my case I had previously initialized a git directory where I was trying to create a new one. I just deleted all the old files and started from scratch.
Both the right answer. HTML5 follows strict rules and in HTML5 we can close all the tags. So, it depends on you to use HTML5 or HTML and follow an appropriate answer.
<img src='stackoverflow.png'>
<img src='stackoverflow.png' />
The second property is more appropriate.
It seems to be this function
h_url=document.getElementById("u").value;
You can help yourself using some 'console.log' to see what object is Null.
The solution works good except if you have a Web Service.
You would need to do the Following as the Description Attribute is not serializable.
[DataContract]
public enum ControlSelectionType
{
[EnumMember(Value = "Not Applicable")]
NotApplicable = 1,
[EnumMember(Value = "Single Select Radio Buttons")]
SingleSelectRadioButtons = 2,
[EnumMember(Value = "Completely Different Display Text")]
SingleSelectDropDownList = 3,
}
public static string GetDescriptionFromEnumValue(Enum value)
{
EnumMemberAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(EnumMemberAttribute), false)
.SingleOrDefault() as EnumMemberAttribute;
return attribute == null ? value.ToString() : attribute.Value;
}
These are Unicode property shortcuts (\p{L}
for Unicode letters, \p{N}
for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)
At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:
[\p{L}\p{N}_.-]*
I'd suggest using $_POST
and $_GET
explicitly.
Using $_REQUEST should be unnecessary with proper site design anyway, and it comes with some downsides like leaving you open to easier CSRF/XSS
attacks and other silliness that comes from storing data in the URL.
The speed difference should be minimal either way.
Some browsers have a security feature that prevents JavaScript from knowing your file's local full path. It makes sense - as a client, you don't want the server to know your local machine's filesystem. It would be nice if all browsers did this.
I know this is an old post, but figured I'd add my two penneth. How about the seldom used and oft' forgot Description list? With a simple bit of css you can get a really clean markup.
<dl>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
</dl>
take a look at this example http://codepen.io/butlerps/pen/wGmXPL
You can stash your local changes first, then pull, then pop the stash.
git stash
git pull origin master
git stash pop
Anything that overrides changes from remote will have conflicts which you will have to manually resolve.
so weird but this worked for me.
close eclipse
start eclipse as eclipse --clean
My case was a simple oversight.
I put the JUnit dependency declaration inside <dependencies>
under the <dependencyManagement/>
node instead of <project/>
in the POM file. Correct way is:
<project>
<!-- Other elements -->
<dependencies>
<!-- Other dependencies-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
<project>
jQuery now defines a when function for this purpose.
It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.
That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:
$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
// the code here will be executed when all four ajax requests resolve.
// a1, a2, a3 and a4 are lists of length 3 containing the response text,
// status, and jqXHR object for each of the four ajax calls respectively.
});
function ajax1() {
// NOTE: This function must return the value
// from calling the $.ajax() method.
return $.ajax({
url: "someUrl",
dataType: "json",
data: yourJsonData,
...
});
}
In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.
If you don't know in advance how many ajax arguments you need to wait for (i.e. you want to use a variable number of arguments), it can still be done but is just a little bit trickier. See Pass in an array of Deferreds to $.when() (and maybe jQuery .when troubleshooting with variable number of arguments).
If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when()
- it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then()
or .fail()
on it to add detailed success/failure handlers.
For me the easiest way... Create an public EditText, for Example "myEditText1"
public EditText myEditText1;
Then, connect it with the EditText which should get cleared
myEditText1 = (EditText) findViewById(R.id.numberfield);
After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example
@OnClick(R.id.numberfield)
void textGone(){
if (myEditText1.isFocused()){
myEditText1.setText("");
}
}
Hope i could help you, Have a nice Day everyone
You can just put this for example at the top of the file:
/* eslint-disable no-console */
Read about Storage Engines.
MyISAM:
The MyISAM storage engine in MySQL.
InnoDB:
The InnoDB storage engine in MySQL.
MyISAM Limitations:
InnoDB Limitations:
ROW_FORMAT=COMPRESSED
)For brief understanding read below links:
This issue has driven me mad: Spring is such a potent tool and yet, such a simple thing as writing an output String as JSON seems impossible without ugly hacks.
My solution (in Kotlin) that I find the least intrusive and most transparent is to use a controller advice and check whether the request went to a particular set of endpoints (REST API typically since we most often want to return ALL answers from here as JSON and not make specializations in the frontend based on whether the returned data is a plain string ("Don't do JSON deserialization!") or something else ("Do JSON deserialization!")). The positive aspect of this is that the controller remains the same and without hacks.
The supports
method makes sure that all requests that were handled by the StringHttpMessageConverter
(e.g. the converter that handles the output of all controllers that return plain strings) are processed and in the beforeBodyWrite
method, we control in which cases we want to interrupt and convert the output to JSON (and modify headers accordingly).
@ControllerAdvice
class StringToJsonAdvice(val ob: ObjectMapper) : ResponseBodyAdvice<Any?> {
override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean =
converterType === StringHttpMessageConverter::class.java
override fun beforeBodyWrite(
body: Any?,
returnType: MethodParameter,
selectedContentType: MediaType,
selectedConverterType: Class<out HttpMessageConverter<*>>,
request: ServerHttpRequest,
response: ServerHttpResponse
): Any? {
return if (request.uri.path.contains("api")) {
response.getHeaders().contentType = MediaType.APPLICATION_JSON
ob.writeValueAsString(body)
} else body
}
}
I hope in the future that we will get a simple annotation in which we can override which HttpMessageConverter
should be used for the output.
I work in WordPress a lot so use PHP.
My method is to contain my HTML in a PHP Variable, and then echo the variable in data-content
.
$my-data-content = '<form><input type="text"/></form>';
along with
data-content='<?php echo $my-data-content; ?>'
Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve()
, dgesv spits this kind of error when the matrix you passed as a parameter is singular.
As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)
I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.
The most voted answer certainly works for me but it makes the Manage session window popping up again and again.
I've solved that by auto clicking the refresh button using browser console like below
function ClickRefresh(){
console.log("Clicked on refresh button");
document.querySelector("paper-icon-button").click()
}
setInterval(ClickRefresh, 60000)
Feel free to contribute more snippets for this at this gist https://gist.github.com/Subangkar/fd1ef276fd40dc374a7c80acc247613e
You also should set border:none
to that css class.
$report_starting_date=date('2014-09-16');
$report_ending_date=date('2014-09-26');
$report_starting_date1=date('Y-m-d',strtotime($report_starting_date.'-1 day'));
while (strtotime($report_starting_date1)<strtotime($report_ending_date))
{
$report_starting_date1=date('Y-m-d',strtotime($report_starting_date1.'+1 day'));
$dates[]=$report_starting_date1;
}
print_r($dates);
// dates ('2014-09-16', '2014-09-26')
//print result Array
(
[0] => 2014-09-16
[1] => 2014-09-17
[2] => 2014-09-18
[3] => 2014-09-19
[4] => 2014-09-20
[5] => 2014-09-21
[6] => 2014-09-22
[7] => 2014-09-23
[8] => 2014-09-24
[9] => 2014-09-25
[10] => 2014-09-26
)
in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.
Alternatively to usleep()
, which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep()
:
nanosleep
- high resolution sleep#include <time.h> int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
The
nanosleep()
function shall cause the current thread to be suspended from execution until either the time interval specified by therqtp
argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified byrqtp
, as measured by the system clock CLOCK_REALTIME.The use of the
nanosleep()
function has no effect on the action or blockage of any signal.
Fixed it...
Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} |
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} |
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt
How about some examples to show it in action...
@Test
public void isInstanceOf() {
Exception anEx1 = new Exception("ex");
Exception anEx2 = new RuntimeException("ex");
RuntimeException anEx3 = new RuntimeException("ex");
//Base case, handles inheritance
Assert.assertTrue(anEx1 instanceof Exception);
Assert.assertTrue(anEx2 instanceof Exception);
Assert.assertTrue(anEx3 instanceof Exception);
//Other cases
Assert.assertFalse(anEx1 instanceof RuntimeException);
Assert.assertTrue(anEx2 instanceof RuntimeException);
Assert.assertTrue(anEx3 instanceof RuntimeException);
}
@Test
public void isAssignableFrom() {
Exception anEx1 = new Exception("ex");
Exception anEx2 = new RuntimeException("ex");
RuntimeException anEx3 = new RuntimeException("ex");
//Correct usage = The base class goes first
Assert.assertTrue(Exception.class.isAssignableFrom(anEx1.getClass()));
Assert.assertTrue(Exception.class.isAssignableFrom(anEx2.getClass()));
Assert.assertTrue(Exception.class.isAssignableFrom(anEx3.getClass()));
//Incorrect usage = Method parameter is used in the wrong order
Assert.assertTrue(anEx1.getClass().isAssignableFrom(Exception.class));
Assert.assertFalse(anEx2.getClass().isAssignableFrom(Exception.class));
Assert.assertFalse(anEx3.getClass().isAssignableFrom(Exception.class));
}
Change the document root in the file C:\xampp\apache\conf\httpd.conf to the folder where is the index.php of your project.
open notepad++, then drag and drop the folder you want to open as tree view.
OR
File ->open folder as workspace , select the file you want.
The simplest solution is to give the address of the final vector you want , and modify it inside the function.
void calculation(double result[] ){ //do the calculation on result
result[0] = 10+5;
result[1] = 10 +6;
.....
}
int main(){
double result[10] = {0}; //this is the vector of the results
calculation(result); //this will modify result
}
In Oracle, (+) denotes the "optional" table in the JOIN. So in your query,
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id(+)
it's a LEFT OUTER JOIN of table 'b' to table 'a'. It will return all data of table 'a' without losing its data when the other side (optional table 'b') has no data.
The modern standard syntax for the same query would be
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b ON a.id=b.id
or with a shorthand for a.id=b.id
(not supported by all databases):
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b USING(id)
Older syntax, in both Oracle and other databases:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id
More modern syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
INNER JOIN b ON a.id=b.id
Or simply:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
JOIN b ON a.id=b.id
It will only return all data where both 'a' & 'b' tables 'id' value is same, means common part.
This is just the same as a LEFT JOIN, but switches which table is optional.
Old Oracle syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id(+)=b.id
Modern standard syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
RIGHT JOIN b ON a.id=b.id
https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:6585774577187
I followed the solution above from Jonas and it worked well until I needed to add a second column. What I found is that when making the columns visible again Oracle does not necessarily set them visible in the order listed in the statement.
To demonstrate this follow Jonas' example above. As he showed, once the steps are complete the table is in the order that you'd expect. Things then break down when you add another column as shown below:
Example (continued from Jonas'):
Add another column which is to be inserted before column C.
ALTER TABLE t ADD (b2 INT);
Use the technique demonstrated above to move the newly added B2 column before column C.
ALTER TABLE t MODIFY (c INVISIBLE, d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY (c VISIBLE, d VISIBLE, e VISIBLE);
DESCRIBE t;
Name
----
A
B
B2
D
E
C
As shown above column C has moved to the end. It seems that the ALTER TABLE statement above processed the columns in the order D, E, C rather than in the order specified in the statement (perhaps in physical table order). To ensure that the column is placed where desired it is necessary to make the columns visible one by one in the desired order.
ALTER TABLE t MODIFY (c INVISIBLE, d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY c VISIBLE;
ALTER TABLE t MODIFY d VISIBLE;
ALTER TABLE t MODIFY e VISIBLE;
DESCRIBE t;
Name
----
A
B
B2
C
D
E
Define an interface, and implement it in the class that will receive the callback.
Have attention to the multi-threading in your case.
Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html
interface CallBack { //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
void methodToCallBack();
}
class CallBackImpl implements CallBack { //class that implements the method to callback defined in the interface
public void methodToCallBack() {
System.out.println("I've been called back");
}
}
class Caller {
public void register(CallBack callback) {
callback.methodToCallBack();
}
public static void main(String[] args) {
Caller caller = new Caller();
CallBack callBack = new CallBackImpl(); //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
caller.register(callBack);
}
}
In your case, apart from multi-threading you could do like this:
interface ServerInterface {
void newSeverConnection(Socket socket);
}
public class Server implements ServerInterface {
public Server(int _address) {
System.out.println("Starting Server...");
serverConnectionHandler = new ServerConnections(_address, this);
workers.execute(serverConnectionHandler);
System.out.println("Do something else...");
}
void newServerConnection(Socket socket) {
System.out.println("A function of my child class was called.");
}
}
public class ServerConnections implements Runnable {
private ServerInterface serverInterface;
public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
serverPort = _serverPort;
serverInterface = _serverInterface;
}
@Override
public void run() {
System.out.println("Starting Server Thread...");
if (serverInterface == null) {
System.out.println("Server Thread error: callback null");
}
try {
mainSocket = new ServerSocket(serverPort);
while (true) {
serverInterface.newServerConnection(mainSocket.accept());
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Multi-threading
Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.
The observer-pattern
The observer-pattern does nearly this, the major difference is the use of an ArrayList
for adding more than one listener. Where this is not needed, you get better performance with one reference.
Using regexp: \S will match non whitespace character:anything but not a space, tab or new line. If your string has a single character which is not a space, tab or new line, then it's not empty. Therefore you just need to search for one character: \S
JavaScript:
function checkvalue() {
var mystring = document.getElementById('myString').value;
if(!mystring.match(/\S/)) {
alert ('Empty value is not allowed');
return false;
} else {
alert("correct input");
return true;
}
}
HTML:
<form onsubmit="return checkvalue(this)">
<input name="myString" type="text" value='' id="myString">
<input type="submit" value="check value" />
</form>
A single line of code using Linq
public static bool IsPalindrome(string str)
{
return str.SequenceEqual(str.Reverse());
}
Just use this js file. (I mentioned 2 examples with different js files. hope the second one is what you need) You can simply change the scroll amount, speed etc by changing the parameters.
https://github.com/nathco/jQuery.scrollSpeed
Here's a Demo
An anonymous class is extending or implementing while creating its object For example :
Interface in = new InterFace()
{
..............
}
Here anonymous class is implementing Interface.
Class cl = new Class(){
.................
}
here anonymous Class is extending a abstract Class.
If you have a jenkinsfile for your pipeline, check if you see at execution time your branch name in your environment variables.
You can print them with:
pipeline {
agent any
environment {
DISABLE_AUTH = 'true'
DB_ENGINE = 'sqlite'
}
stages {
stage('Build') {
steps {
sh 'printenv'
}
}
}
}
However, PR 91 shows that the branch name is only set in certain pipeline configurations:
You don't need to loop or to check anything. Just take a cube root of 12,000 and round it down:
r = int(12000**(1/3.0))
print r*r*r # 10648
$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
(the w3schools example, it works perfect)
There are a couple of ways to address your problem, however this is probably the most straightforward:
Your main
method is static, so it does not have access to instance members (isLeapYear
field and isLeapYear
method. One approach to rectify this is to make both the field and the method static as well:
static boolean isLeapYear;
/* (snip) */
public static boolean isLeapYear(int year)
{
/* (snip) */
}
Lastly, you're not actually calling your isLeapYear
method (which is why you're not seeing any results). Add this line after int year = kboard.nextInt();
:
isLeapYear(year);
That should be a start. There are some other best practices you could follow but for now just focus on getting your code to work; you can refactor later.
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
You aren't creating any buttons, you just have an empty list.
You can forget the list and just create the buttons in the loop.
private void button1_Click(object sender, EventArgs e)
{
int top = 50;
int left = 100;
for (int i = 0; i < 10; i++)
{
Button button = new Button();
button.Left = left;
button.Top = top;
this.Controls.Add(button);
top += button.Height + 2;
}
}
In OSX, or BSD, there's an equivalent -r
flag which apparently takes a unix timestamp. Here's an example that runs date four times: once for the first date, to show what it is; one for the conversion to unix timestamp with %s
, and finally, one which, with -r
, converts what %s
provides back to a string.
$ date; date +%s; date -r `date +%s`
Tue Oct 24 16:27:42 CDT 2017
1508880462
Tue Oct 24 16:27:42 CDT 2017
At least, seems to work on my machine.
$ uname -a
Darwin XXX-XXXXXXXX 16.7.0 Darwin Kernel Version 16.7.0: Thu Jun 15 17:36:27 PDT 2017; root:xnu-3789.70.16~2/RELEASE_X86_64 x86_64
If you are using yum try:
sudo yum install mysql-devel
This is actually on the main page of nltk.org:
>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']
Endless possibilities, for signed integers only:
n + ((r - n) % r)
You could use Jackson to do this. I have yet to find a simple Gson solution.
Where data_map.json
is a JSON (object) resource file
and data_list.json
is a JSON (array) resource file.
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Based on:
*
* http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
*/
public class JsonLoader {
private static final ObjectMapper OBJ_MAPPER;
private static final TypeReference<Map<String,Object>> OBJ_MAP;
private static final TypeReference<List<Map<String,Object>>> OBJ_LIST;
static {
OBJ_MAPPER = new ObjectMapper();
OBJ_MAP = new TypeReference<Map<String,Object>>(){};
OBJ_LIST = new TypeReference<List<Map<String,Object>>>(){};
}
public static void main(String[] args) {
try {
System.out.println(jsonToString(parseJsonString(read("data_map.json", true))));
System.out.println(jsonToString(parseJsonString(read("data_array.json", true))));
} catch (IOException e) {
e.printStackTrace();
}
}
private static final Object parseJsonString(String jsonString) {
try {
if (jsonString.startsWith("{")) {
return readJsonObject(jsonString);
} else if (jsonString.startsWith("[")) {
return readJsonArray(jsonString);
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String jsonToString(Object json) throws JsonProcessingException {
return OBJ_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}
private static final Map<String,Object> readJsonObject(String jsonObjectString) throws JsonParseException, JsonMappingException, IOException {
return OBJ_MAPPER.readValue(jsonObjectString, OBJ_MAP);
}
private static final List<Map<String,Object>> readJsonArray(String jsonArrayString) throws JsonParseException, JsonMappingException, IOException {
return OBJ_MAPPER.readValue(jsonArrayString, OBJ_LIST);
}
public static final Map<String,Object> loadJsonObject(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
return OBJ_MAPPER.readValue(load(path, isResource), OBJ_MAP);
}
public static final List<Map<String,Object>> loadJsonArray(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
return OBJ_MAPPER.readValue(load(path, isResource), OBJ_LIST);
}
private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
if (isResource) {
return JsonLoader.class.getClassLoader().getResource(path);
}
return new URL("file:/" + path);
}
protected static File load(String path, boolean isResource) throws MalformedURLException {
return load(pathToUrl(path, isResource));
}
protected static File load(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
return new File(url.getPath());
}
}
public static String read(String path, boolean isResource) throws IOException {
return read(path, "UTF-8", isResource);
}
public static String read(String path, String charset, boolean isResource) throws IOException {
return read(pathToUrl(path, isResource), charset);
}
@SuppressWarnings("resource")
public static String read(URL url, String charset) throws IOException {
return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
}
}
Here is the complete code for Dheeraj Sachan's example.
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
public class JsonHandler {
private static ObjectMapper propertyMapper;
static {
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
propertyMapper = new ObjectMapper();
propertyMapper.setDateFormat(df);
propertyMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
propertyMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
propertyMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
private static class MyHashMap extends HashMap<String, List<Video>>{
private static final long serialVersionUID = 7023107716981734468L;
}
private static class Video implements Serializable {
private static final long serialVersionUID = -446275421030765463L;
private String dashUrl;
private String videoBitrate;
private String audioBitrate;
private int videoWidth;
private int videoHeight;
private long fileSize;
@Override
public String toString() {
return "Video [url=" + dashUrl + ", video=" + videoBitrate + ", audio=" + audioBitrate
+ ", width=" + videoWidth + ", height=" + videoHeight + ", size=" + fileSize + "]";
}
}
public static void main(String[] args) {
try {
HashMap<String, List<Video>> map = loadJson("sample.json", true);
Iterator<Entry<String, List<Video>>> lectures = map.entrySet().iterator();
while (lectures.hasNext()) {
Entry<String, List<Video>> lecture = lectures.next();
System.out.printf("Lecture #%s%n", lecture.getKey());
for (Video video : lecture.getValue()) {
System.out.println(video);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static <T> T parseUnderScoredResponse(String json, Class<T> classOfT) {
try {
if (json == null) {
return null;
}
return propertyMapper.readValue(json, classOfT);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
if (isResource) {
return JsonHandler.class.getClassLoader().getResource(path);
}
return new URL("file:/" + path);
}
public static File load(String path, boolean isResource) throws MalformedURLException {
return load(pathToUrl(path, isResource));
}
public static File load(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
return new File(url.getPath());
}
}
@SuppressWarnings("resource")
public static String readFile(URL url, String charset) throws IOException {
return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
}
public static String loadJsonString(String path, boolean isResource) throws IOException {
return readFile(path, isResource, "UTF-8");
}
public static String readFile(String path, boolean isResource, String charset) throws IOException {
return readFile(pathToUrl(path, isResource), charset);
}
public static HashMap<String, List<Video>> loadJson(String jsonString) throws IOException {
return JsonHandler.parseUnderScoredResponse(jsonString, MyHashMap.class);
}
public static HashMap<String, List<Video>> loadJson(String path, boolean isResource) throws IOException {
return loadJson(loadJsonString(path, isResource));
}
}
Not the solution, but you can use debug key for signing release builds to avoid blocking the installation from Google Play Protect. It looks like Play Protect doesn't warn for builds signed with automatically generated debug.keystore
.
Note that your debug builds are not unsigned, they are just signed with a debug key.
Of course, you cannot use the build for production distribution (Google Play, Amazon, etc.), but it's still worth for pre-production internal testing which requires a high-frequency feedback loop.
You can add a task to build release with debug.keystore by adding the configuration in build.gradle
, something like:
android {
buildTypes {
// add after the `release` definition
releaseDebugKey { initWith release }
}
signingConfigs {
// use debug.keystore for releaseDebugKey builds
releaseDebugKey { initWith debug }
}
}
then execute ./gradlew assembleReleaseDebugKey
to build a release build with debug key.
Put this in style :
.hash_link_tag{margin-top: -50px; position: absolute;}
and use this class in separate div
tag before the links, example:
<div class="hash_link_tag" id="link1"></div>
<a href="#link1">Link1</a>
or use this php code for echo link tag:
function HashLinkTag($id)
{
echo "<div id='$id' class='hash_link_tag'></div>";
}
Seems like a permissions issue. This is what worked for me
sudo chown -R $(whoami) /Library/Ruby/Gems/*
or in your case
sudo chown -R $(whoami) /usr/local/lib/ruby/gems/2.0.0/gems/
What does this do:
This is telling the system to change the files to change the ownership to the current user. Something must have gotten messed up when something got installed. Usually this is because there are multiple accounts or users are using sudo to install when they should not always have to.
If prepared statements are used, the type will be int where appropriate. This code returns an array of rows, where each row is an associative array. Like if fetch_assoc()
was called for all rows, but with preserved type info.
function dbQuery($sql) {
global $mysqli;
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$stmt->store_result();
$meta = $stmt->result_metadata();
$params = array();
$row = array();
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
while ($stmt->fetch()) {
$tmp = array();
foreach ($row as $key => $val) {
$tmp[$key] = $val;
}
$ret[] = $tmp;
}
$meta->free();
$stmt->close();
return $ret;
}
You need to change the sshd_config
file in the remote server (probably in /etc/ssh/sshd_config
).
Change
PasswordAuthentication no
to
PasswordAuthentication yes
And then restart the sshd
daemon.
I agree with rpd, this is the answer and can be done on a regular basis to clean up your id column that is getting bigger with only a few hundred rows of data, but maybe an id of 34444543!, as the data is deleted out regularly but id is incremented automatically.
ALTER TABLE users DROP id
The above sql can be run via sql query or as php. This will delete the id column.
Then re add it again, via the code below:
ALTER TABLE `users` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
Place this in a piece of code that may get run maybe in an admin panel, so when anyone enters that page it will run this script that auto cleans your database, and tidys it.
You can do just this:
[[element] * numcols] * numrows
For example:
>>> [['a'] *3] * 2
[['a', 'a', 'a'], ['a', 'a', 'a']]
But this has a undesired side effect:
>>> b = [['a']*3]*3
>>> b
[['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]
>>> b[1][1]
'a'
>>> b[1][1] = 'b'
>>> b
[['a', 'b', 'a'], ['a', 'b', 'a'], ['a', 'b', 'a']]
Try this. Here is the code to get the sheet names in order.
private Dictionary<int, string> GetExcelSheetNames(string fileName)
{
Excel.Application _excel = null;
Excel.Workbook _workBook = null;
Dictionary<int, string> excelSheets = new Dictionary<int, string>();
try
{
object missing = Type.Missing;
object readOnly = true;
Excel.XlFileFormat.xlWorkbookNormal
_excel = new Excel.ApplicationClass();
_excel.Visible = false;
_workBook = _excel.Workbooks.Open(fileName, 0, readOnly, 5, missing,
missing, true, Excel.XlPlatform.xlWindows, "\\t", false, false, 0, true, true, missing);
if (_workBook != null)
{
int index = 0;
foreach (Excel.Worksheet sheet in _workBook.Sheets)
{
// Can get sheet names in order they are in workbook
excelSheets.Add(++index, sheet.Name);
}
}
}
catch (Exception e)
{
return null;
}
finally
{
if (_excel != null)
{
if (_workBook != null)
_workBook.Close(false, Type.Missing, Type.Missing);
_excel.Application.Quit();
}
_excel = null;
_workBook = null;
}
return excelSheets;
}
This Python script has GUI to select with explorer a Ipython Notebook you want to convert to pdf. The approach with wkhtmltopdf is the only approach I found works well and provides high quality pdfs. Other approaches described here are problematic, syntax highlighting does not work or graphs are messed up.
You'll need to install wkhtmltopdf: http://wkhtmltopdf.org/downloads.html
and Nbconvert
pip install nbconvert
# OR
conda install nbconvert
Python script
# Script adapted from CloudCray
# Original Source: https://gist.github.com/CloudCray/994dd361dece0463f64a
# 2016--06-29
# This will create both an HTML and a PDF file
import subprocess
import os
from Tkinter import Tk
from tkFileDialog import askopenfilename
WKHTMLTOPDF_PATH = "C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf" # or wherever you keep it
def export_to_html(filename):
cmd = 'ipython nbconvert --to html "{0}"'
subprocess.call(cmd.format(filename), shell=True)
return filename.replace(".ipynb", ".html")
def convert_to_pdf(filename):
cmd = '"{0}" "{1}" "{2}"'.format(WKHTMLTOPDF_PATH, filename, filename.replace(".html", ".pdf"))
subprocess.call(cmd, shell=True)
return filename.replace(".html", ".pdf")
def export_to_pdf(filename):
fn = export_to_html(filename)
return convert_to_pdf(fn)
def main():
print("Export IPython notebook to PDF")
print(" Please select a notebook:")
Tk().withdraw() # Starts in folder from which it is started, keep the root window from appearing
x = askopenfilename() # show an "Open" dialog box and return the path to the selected file
x = str(x.split("/")[-1])
print(x)
if not x:
print("No notebook selected.")
return 0
else:
fn = export_to_pdf(x)
print("File exported as:\n\t{0}".format(fn))
return 1
main()
The newest release of Git Extensions supports Visual Studio 2010 now (along with Visual Studio 2008 and Visual Studio 2005).
I found it to be fairly easy to use with Visual Studio 2008 and the interface seems to be the same in Visual Studio 2010.
If you use PM2 via node modules instead of globally, you'll need to set interpreter: 'none'
in order for the above solutions to work. Related docs here.
In ecosystem.config.js
:
apps: [
{
name: 'myApp',
script: 'yarn',
args: 'start',
interpreter: 'none',
},
],
I was concatenating the variable and adding multiple items in same row. so below code work for me. "\n" new line code is mandatory to add first and last of each line if you will add it on last only it will append last 1-2 character to new lines.
$itemCode = '';
foreach($returnData['repairdetail'] as $checkkey=>$repairDetailData){
if($checkkey >0){
$itemCode .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";
}else{
$itemCode .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";
}
$repairDetaile[]= array(
$itemCode,
)
}
// pass all array to here
foreach ($repairDetaile as $csvData) {
fputcsv($csv_file,$csvData,',','"');
}
fclose($csv_file);
You just need to override onCreateDialog
in an Activity.
//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";
private static final int DIALOG_LOAD_FILE = 1000;
private void loadFileList() {
try {
mPath.mkdirs();
}
catch(SecurityException e) {
Log.e(TAG, "unable to write on the sd card " + e.toString());
}
if(mPath.exists()) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
return filename.contains(FTYPE) || sel.isDirectory();
}
};
mFileList = mPath.list(filter);
}
else {
mFileList= new String[0];
}
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
switch(id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
if(mFileList == null) {
Log.e(TAG, "Showing file picker before loading the file list");
dialog = builder.create();
return dialog;
}
builder.setItems(mFileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChosenFile = mFileList[which];
//you can do stuff with the file here too
}
});
break;
}
dialog = builder.show();
return dialog;
}
You can do like this.
<input type="button" value="mybutton1" onclick="dosomething(this)">
function dosomething(element){
alert("value is "+element.value); //you can print any value like id,class,value,innerHTML etc.
};
DROP that table and again run Spring Project. That might help. Sometime you are overriding foreignKey.
To detect your controller is pushed or not just use below code in anywhere you want:
if ([[[self.parentViewController childViewControllers] firstObject] isKindOfClass:[self class]]) {
// Not pushed
}
else {
// Pushed
}
I hope this code can help anyone...
I had installed Android studio and was not able to access the AVD Manager directly. I had to follow the steps as mentioned below:
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
If you have notepad++ installed in your pc, then you can copy text as RTF (Rich Text Format) and paste it in your outlook mail.
1) Paste you code snippet into notepad++
2) From Menu bar navigate to "Plugins -> NppExport -> Copy RTF to clipboard"
3) Paste into your email
4) Done
float_num.toFixed(2);
Note:toFixed()
will round or pad with zeros if necessary to meet the specified length.
It's just shorthand for $(document).ready()
, as in: $(document).ready(function() {
YOUR_CODE_HERE
});
. Sometimes you have to use it because your function is running before the DOM finishes loading.
Everything is explained here: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
Old post but as you said "why is it not using the correct certificate" I would like to offer an way to find out which SSL certificate is used for SMTP (see here) which required openssl:
openssl s_client -connect exchange01.int.contoso.com:25 -starttls smtp
This will outline the used SSL certificate for the SMTP service. Based on what you see here you can replace the wrong certificate (like you already did) with a correct one (or trust the certificate manually).
Use pd.set_option('display.max_colwidth', None)
for automatic linebreaks and multi-line cells.
This is a great resource on how to use jupyters display with pandas to the fullest.
Edited:
Used to be pd.set_option('display.max_colwidth', -1)
.
check this out A little framework: a complete cookies reader/writer with full Unicode support
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
In my gulp setup, I'm specifying the vendor files first and then specifying the (more general) everything, second. And it successfully puts the vendor js before the other custom stuff.
gulp.src([
// vendor folder first
path.join(folder, '/vendor/**/*.js'),
// custom js after vendor
path.join(folder, '/**/*.js')
])
This can be used in automation scripts if you don't need all tables in all schemas:
for table in $(psql -qAntc '\dt' | cut -d\| -f2); do
...
done
Try to use:
mvn clean package install
This command should install your artifacts in you local maven repo.
PS: I see that this is an old question, but it may be helpful for somebody in the future.
ALL_TAB_COLUMNS
should be queryable from PL/SQL. DESC
is a SQL*Plus command.
SQL> desc all_tab_columns;
Name Null? Type
----------------------------------------- -------- ----------------------------
OWNER NOT NULL VARCHAR2(30)
TABLE_NAME NOT NULL VARCHAR2(30)
COLUMN_NAME NOT NULL VARCHAR2(30)
DATA_TYPE VARCHAR2(106)
DATA_TYPE_MOD VARCHAR2(3)
DATA_TYPE_OWNER VARCHAR2(30)
DATA_LENGTH NOT NULL NUMBER
DATA_PRECISION NUMBER
DATA_SCALE NUMBER
NULLABLE VARCHAR2(1)
COLUMN_ID NUMBER
DEFAULT_LENGTH NUMBER
DATA_DEFAULT LONG
NUM_DISTINCT NUMBER
LOW_VALUE RAW(32)
HIGH_VALUE RAW(32)
DENSITY NUMBER
NUM_NULLS NUMBER
NUM_BUCKETS NUMBER
LAST_ANALYZED DATE
SAMPLE_SIZE NUMBER
CHARACTER_SET_NAME VARCHAR2(44)
CHAR_COL_DECL_LENGTH NUMBER
GLOBAL_STATS VARCHAR2(3)
USER_STATS VARCHAR2(3)
AVG_COL_LEN NUMBER
CHAR_LENGTH NUMBER
CHAR_USED VARCHAR2(1)
V80_FMT_IMAGE VARCHAR2(3)
DATA_UPGRADED VARCHAR2(3)
HISTOGRAM VARCHAR2(15)
Textareas shouldn't wrap by default, but you can set wrap="soft" to explicitly disable wrap:
<textarea name="nowrap" cols="30" rows="3" wrap="soft"></textarea>
EDIT: The "wrap" attribute is not officially supported. I got it from the german SELFHTML page (an english source is here) that says IE 4.0 and Netscape 2.0 support it. I also tested it in FF 3.0.7 where it works as supposed. Things have changed here, SELFHTML is now a wiki and the english source link is dead.
EDIT2: If you want to be sure every browser supports it, you can use CSS to change wrap behaviour:
Using Cascading Style Sheets (CSS), you can achieve the same effect with
white-space: nowrap; overflow: auto;
. Thus, the wrap attribute can be regarded as outdated.
From here (seems to be an excellent page with information about textarea).
EDIT3: I'm not sure when it changed (according to the comments, must've been around 2014), but wrap
is now an official HTML5 attribute, see w3schools. Changed the answer to match this.
delete this directory:
C:\Users\[username]\.gradle
Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.
With seconds!
$('.Timestamp').datetimepicker({
format: 'DD/MM/YYYY HH:mm:ss'
});
To skip future dates:
$(function () {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datetimepicker,#datetimepicker1').datetimepicker({
pickTime: false,
format: "DD-MM-YYYY",
maxDate: new Date(currentYear, currentMonth, currentDate + 1)
});
});
Hey i know i am extremely late to this answer, but just thought i must share this,
The method to call when u reset the image must be the same method that u called while u were setting it.
When u want to reset the image source @dennis.sheepard answer works fine only if u are originally setting the image in the bitmap using setImageResource()
for instance,
i had used setImageBitmap()
and hence setting setImageResource(0)
didn work, instead i used setImageBitmap(null)
.
I have some code which is similar, but does not rewrite the entire contents each time. This is meant to run periodically and append a JSON entry at the end of an array.
If the file doesn't exist yet, it creates it and dumps the JSON into an array. If the file has already been created, it goes to the end, replaces the ]
with a ,
drops the new JSON object in, and then closes it up again with another ]
# Append JSON object to output file JSON array
fname = "somefile.txt"
if os.path.isfile(fname):
# File exists
with open(fname, 'a+') as outfile:
outfile.seek(-1, os.SEEK_END)
outfile.truncate()
outfile.write(',')
json.dump(data_dict, outfile)
outfile.write(']')
else:
# Create file
with open(fname, 'w') as outfile:
array = []
array.append(data_dict)
json.dump(array, outfile)
Recovering from Repository Corruption is the official answer.
The really short answer is: find uncorrupted objects and copy them.
dump this into a more specific collection of just the ids you don't want
var notTheseBarIds = filterBars.Select(fb => fb.BarId);
then try this:
fooSelect = (from f in fooBunch
where !notTheseBarIds.Contains(f.BarId)
select f).ToList();
or this:
fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();
If you wish, you can also use the column names instead of column numbers.
For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.
dataGridView.Rows[4].Cells["Name"].Value.ToString();
Hope it helps.
Up to date 2020
confirmed working with:
"react-router-dom": "^5.1.2"
"react": "^16.10.2"
useHistory()
hook!import React from 'react';
import { useHistory } from "react-router-dom";
export function HomeSection() {
const history = useHistory();
const goLogin = () => history.push('login');
return (
<Grid>
<Row className="text-center">
<Col md={12} xs={12}>
<div className="input-group">
<span className="input-group-btn">
<button onClick={goLogin} type="button" />
</span>
</div>
</Col>
</Row>
</Grid>
);
}
Are there any performance benefits to using one over the other?
The current answer is no, because none of the current browser engines implements import/export
from the ES6 standard.
Some comparison charts http://kangax.github.io/compat-table/es6/ don't take this into account, so when you see almost all greens for Chrome, just be careful. import
keyword from ES6 hasn't been taken into account.
In other words, current browser engines including V8 cannot import new JavaScript file from the main JavaScript file via any JavaScript directive.
( We may be still just a few bugs away or years away until V8 implements that according to the ES6 specification. )
This document is what we need, and this document is what we must obey.
And the ES6 standard said that the module dependencies should be there before we read the module like in the programming language C, where we had (headers) .h
files.
This is a good and well-tested structure, and I am sure the experts that created the ES6 standard had that in mind.
This is what enables Webpack or other package bundlers to optimize the bundle in some special cases, and reduce some dependencies from the bundle that are not needed. But in cases we have perfect dependencies this will never happen.
It will need some time until import/export
native support goes live, and the require
keyword will not go anywhere for a long time.
What is require
?
This is node.js
way to load modules. ( https://github.com/nodejs/node )
Node uses system-level methods to read files. You basically rely on that when using require
. require
will end in some system call like uv_fs_open
(depends on the end system, Linux, Mac, Windows) to load JavaScript file/module.
To check that this is true, try to use Babel.js, and you will see that the import
keyword will be converted into require
.
/**
* Get the method name for a depth in call stack. <br />
* Utility function
* @param depth depth in the call stack (0 means current method, 1 means call method, ...)
* @return method name
*/
public static String getMethodName(final int depth)
{
final StackTraceElement[] ste = new Throwable().getStackTrace();
//System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
return ste[ste.length - depth].getMethodName();
}
For example, if you try to get the calling method line for debug purpose, you need to get past the Utility class in which you code those static methods:
(old java1.4 code, just to illustrate a potential StackTraceElement usage)
/**
* Returns the first "[class#method(line)]: " of the first class not equal to "StackTraceUtils". <br />
* From the Stack Trace.
* @return "[class#method(line)]: " (never empty, first class past StackTraceUtils)
*/
public static String getClassMethodLine()
{
return getClassMethodLine(null);
}
/**
* Returns the first "[class#method(line)]: " of the first class not equal to "StackTraceUtils" and aclass. <br />
* Allows to get past a certain class.
* @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils.
* @return "[class#method(line)]: " (never empty, because if aclass is not found, returns first class past StackTraceUtils)
*/
public static String getClassMethodLine(final Class aclass)
{
final StackTraceElement st = getCallingStackTraceElement(aclass);
final String amsg = "[" + st.getClassName() + "#" + st.getMethodName() + "(" + st.getLineNumber()
+")] <" + Thread.currentThread().getName() + ">: ";
return amsg;
}
/**
* Returns the first stack trace element of the first class not equal to "StackTraceUtils" or "LogUtils" and aClass. <br />
* Stored in array of the callstack. <br />
* Allows to get past a certain class.
* @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils.
* @return stackTraceElement (never null, because if aClass is not found, returns first class past StackTraceUtils)
* @throws AssertionFailedException if resulting statckTrace is null (RuntimeException)
*/
public static StackTraceElement getCallingStackTraceElement(final Class aclass)
{
final Throwable t = new Throwable();
final StackTraceElement[] ste = t.getStackTrace();
int index = 1;
final int limit = ste.length;
StackTraceElement st = ste[index];
String className = st.getClassName();
boolean aclassfound = false;
if(aclass == null)
{
aclassfound = true;
}
StackTraceElement resst = null;
while(index < limit)
{
if(shouldExamine(className, aclass) == true)
{
if(resst == null)
{
resst = st;
}
if(aclassfound == true)
{
final StackTraceElement ast = onClassfound(aclass, className, st);
if(ast != null)
{
resst = ast;
break;
}
}
else
{
if(aclass != null && aclass.getName().equals(className) == true)
{
aclassfound = true;
}
}
}
index = index + 1;
st = ste[index];
className = st.getClassName();
}
if(resst == null)
{
//Assert.isNotNull(resst, "stack trace should null"); //NO OTHERWISE circular dependencies
throw new AssertionFailedException(StackTraceUtils.getClassMethodLine() + " null argument:" + "stack trace should null"); //$NON-NLS-1$
}
return resst;
}
static private boolean shouldExamine(String className, Class aclass)
{
final boolean res = StackTraceUtils.class.getName().equals(className) == false && (className.endsWith("LogUtils"
) == false || (aclass !=null && aclass.getName().endsWith("LogUtils")));
return res;
}
static private StackTraceElement onClassfound(Class aclass, String className, StackTraceElement st)
{
StackTraceElement resst = null;
if(aclass != null && aclass.getName().equals(className) == false)
{
resst = st;
}
if(aclass == null)
{
resst = st;
}
return resst;
}
In C#/.NET 3.5 you could write a little program to do:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
string controller = context.ConnectedServer;
Console.WriteLine( "Domain Controller:" + controller );
}
This will list all the users in the current domain:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(context))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
foreach (UserPrincipal principal in searcher.FindAll())
{
Console.WriteLine( principal.SamAccountName);
}
}
}
}
You can also change the data type to bigInt and it will solve your problem, it's not a good practice to keep integers as strings unless needed. :)
ALTER TABLE T_PERSON MODIFY mobile_no BIGINT;
onActivityCreated()
is now deprecated as Fragments Version 1.3.0-alpha02
The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.
Detailed information can be found here
In latest bootstrap version there is a class to make modal body scrollable.
.modal-dialog-scrollable to .modal-dialog.
Bootstrap modal link for modal body scrollable content
<!-- Scrollable modal -->
<div class="modal-dialog modal-dialog-scrollable">
...
</div>
Learning Google's JavaScript library is a good option. If you don't feel like getting into coding you might find Maps Engine Lite useful.
It is a tool recently published by Google where you can create your personal maps (create markers, draw geometries and adapt the colors and styles).
Here is an useful tutorial I found: Quick Tip: Embedding New Google Maps
random char package com.company;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
// write your code here
char hurufBesar =randomSeriesForThreeCharacter(65,90);
char angka = randomSeriesForThreeCharacter(48,57);
char simbol = randomSeriesForThreeCharacter(33,47);
char hurufKecil= randomSeriesForThreeCharacter(97,122);
char angkaLagi = randomSeriesForThreeCharacter(48,57);
System.out.println(hurufBesar+" "+angka+" "+simbol+" "+hurufKecil+" "+angkaLagi);
}
public static char randomSeriesForThreeCharacter(int min,int max) {
int randomNumber = ThreadLocalRandom.current().nextInt(min, max + 1);
char random_3_Char = (char) (randomNumber);
return random_3_Char;
}
}
#! /bin/bash
function do_something {
echo value=${1}
}
MAX=4
for (( i=0; i<MAX; i++ )) ; {
do_something ${i}
}
Here's an example that can also work in older shells, while still being efficient for large counts:
Z=$(date) awk 'BEGIN { for ( i=0; i<4; i++ ) { print i,"hello",ENVIRON["Z"]; } }'
But good luck doing useful things inside of awk
: How do I use shell variables in an awk script?
This is the fastest solution that does not require you to know or calculate the overall buffer size first:
var data []byte
for i := 0; i < 1000; i++ {
data = append(data, getShortStringFromSomewhere()...)
}
return string(data)
By my benchmark, it's 20% slower than the copy solution (8.1ns per append rather than 6.72ns) but still 55% faster than using bytes.Buffer.
I had the same problem. I had used
git format-patch <commit_hash>
to create the patch. My main problem was patch was failing due to some conflicts, but I could not see any merge conflict in the file content. I had used git am --3way <patch_file_path>
to apply the patch.
The correct command to apply the patch should be:
git am --3way --ignore-space-change <patch_file_path>
If you execute the above command for patching, it will create a merge conflict if patch apply fails. Then you can fix the conflict in your files, like the same way merge conflicts are resolved for git merge
or you can do this:
echo "usage: up [--level <n>| -n <levels>][--help][--version]
Report bugs to:
up home page: "
There isn't any in printf
- the two are synonyms.
html file
<a (click)= "getcoursedetails(obj.Id)" routerLinkActive="active" class="btn btn-danger">Read more...</a>
ts file
getcoursedetails(id)
{
this._route.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
this._route.navigate(["course",id]);
});
If you install the SDK, the offline documentation can be found in $ANDROID_SDK/docs/
.
I found the problem that was causing the HTTP error.
In the setFalse()
function that is triggered by the Save button my code was trying to submit the form that contained the button.
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit();
document.submitForm.submit();
when I remove the document.submitForm.submit();
it works:
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit()
@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!
For everybody that falls off google, in here, this is the fix for VSCode 1.40 (2019):
Open the global settings.json: File > Preferences > Settings
Then select the tab 'User', open the section 'Extensions', click on 'C/C++'. Then scroll the right panel till you find a 'Edit in settings.json' button.
Last, you add the "C_Cpp.default.includePath" section. The code provided there is from my own system (Windows 7). You can use it as a base for your own libraries paths. (Remember to change the YOUR USERNAME
to your correct system (my case windows) username)
(edit info: There is a problem with the recursion of my approach. VSCode doesn't like multiple definitions for the same thing. I solved it with "C_Cpp.intelliSenseEngine": "Tag Parser"
)
the code before line 7, on the settings.json has nothing to do with arduino or includePath. You may not copy that...
JSON section to add to settings.json:
"C_Cpp.default.includePath": [
"C:/Program Files (x86)/Arduino/libraries/**",
"C:/Program Files (x86)/Arduino/hardware/arduino/avr/cores/arduino/**",
"C:/Program Files (x86)/Arduino/hardware/tools/avr/avr/include/**",
"C:/Program Files (x86)/Arduino/hardware/tools/avr/lib/gcc/avr/5.4.0/include/**",
"C:/Program Files (x86)/Arduino/hardware/arduino/avr/variants/standard/**",
"C:/Users/<YOUR USERNAME>/.platformio/packages/framework-arduinoavr/**",
"C:/Users/<YOUR USERNAME>/Documents/Arduino/libraries/**",
"{$workspaceFolder}/libraries/**",
"{$workspaceFolder}/**"
],
"C_Cpp.intelliSenseEngine": "Tag Parser"
REST is not necessarily tied to HTTP. RESTful web services are just web services that follow a RESTful architecture.
What is Rest -
1- Client-server
2- Stateless
3- Cacheable
4- Layered system
5- Code on demand
6- Uniform interface
Add this is work for me
<repositories>
<!-- Repository for ORACLE JDBC Driver -->
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
I had the same problem. Check out the comment in https://gist.github.com/khernyo/4226923#comment-812526
It says:
for gradle android plugin v0.3 use "com.android.build.gradle.tasks.PackageApplication"
That should fix your problem.
I was having the same issue which it seems was down to config issue. The github mac osx app had created a ssh private key called github_rsa
In your Eclipse go to Window > Preferences > Network Connections > SSH2
In the general tab you should see SSH2 home /Users/<you username>/.ssh
you'll probably see id_dsa,id_rsa defined as private keys.
Click 'Add private key' and select github_rsa located /Users/<you username>/.ssh
Check the file which you have selected in the request.
For me i was getting the error because the file was not present in the system, as i have imported the request from some other machine.
Hope this code will help
<html>
<head>
<style type="text/css">
.js #flash {display: none;}
</style>
<script type="text/javascript">
document.documentElement.className = 'js';
</script>
</head>
<body>
<!-- the rest of your code goes here -->
<script type="text/javascript" src="/scripts/jquery.js"></script>
<script type="text/javascript">
// Stuff to do as soon as the body finishes loading.
// No need for $(document).ready() here.
</script>
</body>
</html>
The AAR file consists of a JAR file and some resource files (it is basically a standard zip file with a custom file extension). Here are the steps to convert:
Just change home to your liking
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/home';
header('Location: ' . $home_url);
Static arrays are allocated memory at compile time and the memory is allocated on the stack. Whereas, the dynamic arrays are allocated memory at the runtime and the memory is allocated from heap.
int arr[] = { 1, 3, 4 }; // static integer array.
int* arr = new int[3]; // dynamic integer array.
You did not post the code generated by the compiler, so there' some guesswork here, but even without having seen it, one can say that this:
test rax, 1
jpe even
... has a 50% chance of mispredicting the branch, and that will come expensive.
The compiler almost certainly does both computations (which costs neglegibly more since the div/mod is quite long latency, so the multiply-add is "free") and follows up with a CMOV. Which, of course, has a zero percent chance of being mispredicted.
If you're downloading text then I'd recommend using the WebClient and get a streamreader to the text:
WebClient web = new WebClient();
System.IO.Stream stream = web.OpenRead("http://www.yoursite.com/resource.txt");
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
String text = reader.ReadToEnd();
}
If this is taking a long time then it is probably a network issue or a problem on the web server. Try opening the resource in a browser and see how long that takes. If the webpage is very large, you may want to look at streaming it in chunks rather than reading all the way to the end as in that example. Look at http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx to see how to read from a stream.
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
var dictionary = (from x in y
select new SomeClass
{
prop1 = value1,
prop2 = value2
}
).ToDictionary(item => item.prop1);
That's assuming that SomeClass.prop1
is the desired Key
for the dictionary.
install these ==>> pip install -U scikit-learn scipy matplotlib if still getting the same error then , make sure that your imoprted statment should be correct. i made the mistike while writing ensemble so ,(check spelling) its should be >>> from sklearn.ensemble import RandomForestClassifier
pip install worked for me, and it failed with a permission issue, which was resolved when I used
sudo pip install pandas
I see that the best sudo workaround is from /tmp: Is it acceptable and safe to run pip install under sudo?
Firstly add a div with id.
<div id="my_map_add" style="width:100%;height:300px;"></div>
<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>
You are right, the second Dockerfile will overwrite the CMD
command of the first one. Docker will always run a single command, not more. So at the end of your Dockerfile, you can specify one command to run. Not more.
But you can execute both commands in one line:
FROM centos+ssh
EXPOSE 22
EXPOSE 4149
CMD service sshd start && /opt/mq/sbin/rabbitmq-server start
What you could also do to make your Dockerfile a little bit cleaner, you could put your CMD commands to an extra file:
FROM centos+ssh
EXPOSE 22
EXPOSE 4149
CMD sh /home/centos/all_your_commands.sh
And a file like this:
service sshd start &
/opt/mq/sbin/rabbitmq-server start
As Jim Garrison said in the comment, no obvious reason why you'd make a one-element list out of drug.upper()
(which implies drug is a string).
But that's not your error, as your function medications_minimum3()
doesn't even use the second argument (something you should fix).
TypeError: unhashable type: 'list'
usually means that you are trying to use a list as a hash argument (like for accessing a dictionary). I'd look for the error in counter[row[11]]+=1
-- are you sure that row[11]
is of the right type? Sounds to me it might be a list.
ModelAndView: The name itself explains it is data structure which contains Model and View data.
Map() model=new HashMap();
model.put("key.name", "key.value");
new ModelAndView("view.name", model);
// or as follows
ModelAndView mav = new ModelAndView();
mav.setViewName("view.name");
mav.addObject("key.name", "key.value");
if model contains only single value, we can write as follows:
ModelAndView("view.name","key.name", "key.value");
You can add one li
element where you want to add divider
<ul>
<li> your content </li>
<li class="divider-vertical-second-menu"></li>
<li> NExt content </li>
<li class="divider-vertical-second-menu"></li>
<li> last item </li>
</ul>
In CSS you can Add following code.
.divider-vertical-second-menu{
height: 40px;
width: 1px;
margin: 0 5px;
overflow: hidden;
background-color: #DDD;
border-right: 2px solid #FFF;
}
This will increase you speed of execution as it will not load any image. just test it out.. :)
I do believe that
if (startDate <= date && date <= endDate) {
alert("Yay");
} else {
alert("Nay! :(");
}
works too...
Is there a way to get a list of all the keys in a Go language map?
ks := reflect.ValueOf(m).MapKeys()
how do I iterate over all the keys?
Use the accepted answer:
for k, _ := range m { ... }
Inspect didn't work for me. Maybe as I was using -net host
and some namespaces.
Anyway, I found this to work nicely:
docker exec -i -t NAME /sbin/ifconfig docker0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
I'm using Mac OS X Yosemite and Netbeans 8.02, I got the same error and the simple solution I have found is like above, this is useful when you need to include native library in the project. So do the next for Netbeans:
1.- Right click on the Project
2.- Properties
3.- Click on RUN
4.- VM Options: java -Djava.library.path="your_path"
5.- for example in my case: java -Djava.library.path=</Users/Lexynux/NetBeansProjects/NAO/libs>
6.- Ok
I hope it could be useful for someone. The link where I found the solution is here: java.library.path – What is it and how to use
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
Unfortunately, ggplot2 does not offer a way to do this (easily) without transforming your data into long format. You can try to fight it but it will just be easier to do the data transformation. Here all the methods, including melt
from reshape2, gather
from tidyr, and pivot_longer
from tidyr: Reshaping data.frame from wide to long format
Here's a simple example using pivot_longer
:
> df <- data.frame(time = 1:5, a = 1:5, b = 3:7)
> df
time a b
1 1 1 3
2 2 2 4
3 3 3 5
4 4 4 6
5 5 5 7
> df_wide <- df %>% pivot_longer(c(a, b), names_to = "colname", values_to = "val")
> df_wide
# A tibble: 10 x 3
time colname val
<int> <chr> <int>
1 1 a 1
2 1 b 3
3 2 a 2
4 2 b 4
5 3 a 3
6 3 b 5
7 4 a 4
8 4 b 6
9 5 a 5
10 5 b 7
As you can see, pivot_longer
puts the selected column names in whatever is specified by names_to
(default "name"), and puts the long values into whatever is specified by values_to
(default "value"). If I'm ok with the default names, I can use use df %>% pivot_longer(c("a", "b"))
.
Now you can plot as normal, ex.
ggplot(df_wide, aes(x = time, y = val, color = colname)) + geom_line()
You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects
For Print Result to text file
we can follow
echo "test data" > test.txt
This will create test.txt file and written "test data"
If you want to append then
echo "test data" >> test.txt
In Python, a list
is a dynamic array. You can create one like this:
lst = [] # Declares an empty list named lst
Or you can fill it with items:
lst = [1,2,3]
You can add items using "append":
lst.append('a')
You can iterate over elements of the list using the for
loop:
for item in lst:
# Do something with item
Or, if you'd like to keep track of the current index:
for idx, item in enumerate(lst):
# idx is the current idx, while item is lst[idx]
To remove elements, you can use the del command or the remove function as in:
del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list
Note, though, that one cannot iterate over the list and modify it at the same time; to do that, you should instead iterate over a slice of the list (which is basically a copy of the list). As in:
for item in lst[:]: # Notice the [:] which makes a slice
# Now we can modify lst, since we are iterating over a copy of it
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
Use this
dataTable.Columns["OldColumnName"].ColumnName = "NewColumnName";
The easiest solution is to use UIStackView (horizontal). Add to stack view: first view and second view with labels. Then set isHidden property of first view to false. All constrains will be calculated and updates automatically.
Use Nullable<DateTime>
if possible.
VB is not a language. VB is a program that hosts VBA, just as Office hosts VBA. VB is a set of App objects, just like Word and Excel have, and a forms package, just like in Office.
So you can only write VBA code in VB.
PS this info is on the INFO tab on the VB question page for VB.
From VBA Info
VBA 6, was shipped in 1998 and includes a myriad of licensed hosts, among them: Office 2000 - 2010, AutoCAD, PI Processbook, and the stand-alone Visual Basic 6.0
A simple solution could be css-only. You can set styles in your stylesheet, and then adjust them on the bottom of it. Modern smartphones act like they are just 480px wide, while they are actually a lot more. The code to detect a smaller screen in css is
@media handheld, only screen and (max-width: 560px), only screen and (max-device-width: 480px) {
#hoofdcollumn {margin: 10px 5%; width:90%}
}
Hope this helps!
Simple and easy!
get_queried_object_id()
Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:
src("'js/**/!(*.min).js")
Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js
Here's an httplib
solution that behaves like urllib2. You can just give it a URL and it just works. No need to mess about splitting up your URLs into hostname and path. This function already does that.
import httplib
import socket
def get_link_status(url):
"""
Gets the HTTP status of the url or returns an error associated with it. Always returns a string.
"""
https=False
url=re.sub(r'(.*)#.*$',r'\1',url)
url=url.split('/',3)
if len(url) > 3:
path='/'+url[3]
else:
path='/'
if url[0] == 'http:':
port=80
elif url[0] == 'https:':
port=443
https=True
if ':' in url[2]:
host=url[2].split(':')[0]
port=url[2].split(':')[1]
else:
host=url[2]
try:
headers={'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0',
'Host':host
}
if https:
conn=httplib.HTTPSConnection(host=host,port=port,timeout=10)
else:
conn=httplib.HTTPConnection(host=host,port=port,timeout=10)
conn.request(method="HEAD",url=path,headers=headers)
response=str(conn.getresponse().status)
conn.close()
except socket.gaierror,e:
response="Socket Error (%d): %s" % (e[0],e[1])
except StandardError,e:
if hasattr(e,'getcode') and len(e.getcode()) > 0:
response=str(e.getcode())
if hasattr(e, 'message') and len(e.message) > 0:
response=str(e.message)
elif hasattr(e, 'msg') and len(e.msg) > 0:
response=str(e.msg)
elif type('') == type(e):
response=e
else:
response="Exception occurred without a good error message. Manually check the URL to see the status. If it is believed this URL is 100% good then file a issue for a potential bug."
return response
This works for me for a single column
$('#example').dataTable( {
"aoColumns": [
{ "bSortable": false
}]});
It is very easy to achieve with built in method SelectAll
Simply cou can write this:
txtTextBox.Focus();
txtTextBox.SelectAll();
And everything in textBox will be selected :)
This is going to sound really cheesy, but it's the best way I've been able to keep the terms straight in my head:
Declaration: Picture Thomas Jefferson giving a speech... "I HEREBY DECLARE THAT THIS FOO EXISTS IN THIS SOURCE CODE!!!"
Definition: picture a dictionary, you are looking up Foo and what it actually means.
I used https://www.npmjs.com/package/line-by-line for reading more than 1 000 000 lines from a text file. In this case, an occupied capacity of RAM was about 50-60 megabyte.
const LineByLineReader = require('line-by-line'),
lr = new LineByLineReader('big_file.txt');
lr.on('error', function (err) {
// 'err' contains error object
});
lr.on('line', function (line) {
// pause emitting of lines...
lr.pause();
// ...do your asynchronous line processing..
setTimeout(function () {
// ...and continue emitting lines.
lr.resume();
}, 100);
});
lr.on('end', function () {
// All lines are read, file is closed now.
});
Following is the complete example for CKEDITOR 4.x :
HTML
<textarea name="post_content" id="post_content" class="form-control"></textarea>
SCRIPT
CKEDITOR.replace('post_content', {
allowedContent:true,
});
The above code will allow all tags in the editor.
For more Detail : CK EDITOR Allowed Content Rules
Visual Basic has a nice function : ReDim Preserve
.
Someone has kindly written an equivalent function - you can find it here. I think it does exactly what you are asking for (and you're not re-inventing the wheel - you're copying someone else's)...
If the element is position absolutely, then it isn't relative, or in reference to any object - including the page itself. So margin: auto;
can't decide where the middle is.
Its waiting to be told explicitly, using left
and top
where to position itself.
You can still center it programatically, using javascript or somesuch.
On Vista with virtualization on, the file is here. Note that the AppData folder is hidden. Either show hidden folders, or go straight to it by typing %AppData% in the address bar of Windows Explorer.
C:\Users\[user]\AppData\Roaming\Notepad++\shortcuts.xml
If someone is still looking, here's what worked for me - to read an arbitrary length of string including spaces.
Thanks to many posters on the web for sharing this simple & elegant solution. If it works the credit goes to them but any errors are mine.
char *name;
scanf ("%m[^\n]s",&name);
printf ("%s\n",name);
I'm going to take a stab in the dark and guess you're talking about Windows. In a nutshell, kernel mode has full access to hardware, but user mode doesn't. For instance, many if not most device drivers are written in kernel mode because they need to control finer details of their hardware.
See also this wikibook.
A URL of the form https://github.com/<owner>/<project>/commit/<hash>
will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:
https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685
You can also shorten the hash to any unique prefix, like so:
https://github.com/jerith666/git-graph/commit/35e32b
I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):
git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685
Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.
With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:
table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']
The output then is:
Heading1 Heading2
0 1 3
1 2 4
why not keep it simple
cd SOME_PATH && run_some_command && cd -
the last 'cd' command will take you back to the last pwd directory. This should work on all *nix systems.
This works on both MacOSX and Linux:
#!/bin/bash
ping -q -w1 -c1 google.com &>/dev/null && echo online || echo offline
If you only need to compare two files, I guess the fastest way would be (in C, I don't know if it's applicable to .NET)
OTOH, if you need to find if there are duplicate files in a set of N files, then the fastest way is undoubtedly using a hash to avoid N-way bit-by-bit comparisons.
Have you tried using the WebClient class?
you should be able to use
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);
Documentation at
http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx
Comments in the following listing of Java Code are the greyed out characters:
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
The Java language supports three kinds of comments:
/* text */
The compiler ignores everything from /*
to */
.
/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /*
and */
. The JDK javadoc tool uses doc comments when preparing automatically generated documentation.
// text
The compiler ignores everything from //
to the end of the line.
Now regarding when you should be using them:
Use // text
when you want to comment a single line of code.
Use /* text */
when you want to comment multiple lines of code.
Use /** documentation */
when you would want to add some info about the program that can be used for automatic generation of program documentation.
I also encountered same problem. I do not know why, i just add -lpthread
option to compiler and everything ok.
Old:
$ g++ -rdynamic -m64 -fPIE -pie -o /tmp/node/out/Release/mksnapshot ...*.o *.a -ldl -lrt
got following error. If i append -lpthread
option to above command then OK.
/usr/bin/ld: /tmp/node/out/Release/obj.host/v8_libbase/deps/v8/src/base/platform/condition-variable.o: undefined reference to symbol 'pthread_condattr_setclock@@GLIBC_2.3.3'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
Use
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaplayer.prepareAsync();
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaplayer.start();
}
});
Writing instructions to get a core dump under Ubuntu 16.04 LTS:
As @jtn has mentioned in his answer, Ubuntu delegates the display of crashes to apport, which in turn refuses to write the dump because the program is not an installed package.
To remedy the problem, we need to make sure apport writes core dump files for non-package programs as well. To do so, create a file named ~/.config/apport/settings with the following contents:
[main]
unpackaged=true
[Optional] To make the dumps readble by gdb, run the following command:
apport-unpack <location_of_report> <target_directory>
References: Core_dump – Oracle VM VirtualBox
So is this the answer?
"If you need to calculate something but not show it, set the element to visibility:hidden
and position:absolute
, add it to the DOM tree, get the offsetHeight, and remove it. (That's what the prototype library does behind the lines last time I checked)."
I have the same problem on a number of elements. There is no jQuery or Prototype to be used on the site but I'm all in favor of borrowing the technique if it works. As an example of some things that failed to work, followed by what did, I have the following code:
// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
var DoOffset = true;
if (!elementPassed) { return 0; }
if (!elementPassed.style) { return 0; }
var thisHeight = 0;
var heightBase = parseInt(elementPassed.style.height);
var heightOffset = parseInt(elementPassed.offsetHeight);
var heightScroll = parseInt(elementPassed.scrollHeight);
var heightClient = parseInt(elementPassed.clientHeight);
var heightNode = 0;
var heightRects = 0;
//
if (DoBase) {
if (heightBase > thisHeight) { thisHeight = heightBase; }
}
if (DoOffset) {
if (heightOffset > thisHeight) { thisHeight = heightOffset; }
}
if (DoScroll) {
if (heightScroll > thisHeight) { thisHeight = heightScroll; }
}
//
if (thisHeight == 0) { thisHeight = heightClient; }
//
if (thisHeight == 0) {
// Dom Add:
// all else failed so use the protype approach...
var elBodyTempContainer = document.getElementById('BodyTempContainer');
elBodyTempContainer.appendChild(elementPassed);
heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
elBodyTempContainer.removeChild(elementPassed);
if (heightNode > thisHeight) { thisHeight = heightNode; }
//
// Bounding Rect:
// Or this approach...
var clientRects = elementPassed.getClientRects();
heightRects = clientRects.height;
if (heightRects > thisHeight) { thisHeight = heightRects; }
}
//
// Default height not appropriate here
// if (thisHeight == 0) { thisHeight = elementHeightDefault; }
if (thisHeight > 3000) {
// ERROR
thisHeight = 3000;
}
return thisHeight;
}
which basically tries anything and everything only to get a zero result. ClientHeight with no affect. With the problem elements I typically get NaN in the Base and zero in the Offset and Scroll heights. I then tried the Add DOM solution and clientRects to see if it works here.
29 Jun 2011, I did indeed update the code to try both adding to DOM and clientHeight with better results than I expected.
1) clientHeight was also 0.
2) Dom actually gave me a height which was great.
3) ClientRects returns a result almost identical to the DOM technique.
Because the elements added are fluid in nature, when they are added to an otherwise empty DOM Temp element they are rendered according to the width of that container. This get weird, because that is 30px shorter than it eventually ends up.
I added a few snapshots to illustrate how the height is calculated differently.
The height differences are obvious. I could certainly add absolute positioning and hidden but I am sure that will have no effect. I continued to be convinced this would not work!
(I digress further) The height comes out (renders) lower than the true rendered height. This could be addressed by setting the width of the DOM Temp element to match the existing parent and could be done fairly accurately in theory. I also do not know what would result from removing them and adding them back into their existing location. As they arrived through an innerHTML technique I will be looking using this different approach.
* HOWEVER * None of that was necessary. In fact it worked as advertised and returned the correct height!!!
When I was able to get the menus visible again amazingly DOM had returned the correct height per the fluid layout at the top of the page (279px). The above code also uses getClientRects which return 280px.
This is illustrated in the following snapshot (taken from Chrome once working.)
Now I have noooooo idea why that prototype trick works, but it seems to. Alternatively, getClientRects also works.
I suspect the cause of all this trouble with these particular elements was the use of innerHTML instead of appendChild, but that is pure speculation at this point.
So this function gets rid of most of a specified listener type on an element:
function removeListenersFromElement(element, listenerType){
const listeners = getEventListeners(element)[listenerType];
let l = listeners.length;
for(let i = l-1; i >=0; i--){
removeEventListener(listenerType, listeners[i].listener);
}
}
There have been a few rare exceptions where one can't be removed for some reason.
Another possible cause of the “Workspace in use or cannot be created, chose a different one” issue is that the real path to your workspace may have changed.
In my case, the real location of the workspace had changed, but I had used a symlink to make it look like it was in the same location. I saw errors in logs indicating that eclipse was looking at the previous "real" location, as opposed to following the symlink, and this was causing the errors.
In my case, I just moved the workspace back to its old location.
I added
"types": [
"node"
]
in my tsconfig file and its worked for me tsconfig.json file look like
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "es2015",
"types": [
"node",
"underscore"
]
},
This is a PDO-only visualization, as the mysql_*
library is deprecated.
<?php
// Begin Vault (this is in a vault, not actually hard-coded)
$host="hostname";
$username="GuySmiley";
$password="thePassword";
$dbname="dbname";
$port="3306";
// End Vault
try {
$dbh = new PDO("mysql:host=$host;port=$port;dbname=$dbname;charset=utf8", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "I am connected.<br/>";
// ... continue with your code
// PDO closes connection at end of script
} catch (PDOException $e) {
echo 'PDO Exception: ' . $e->getMessage();
exit();
}
?>
Note that this OP Question appeared not to be about port numbers afterall. If you are using the default port of 3306
always, then consider removing it from the uri, that is, remove the port=$port;
part.
If you often change ports, consider the above port usage for more maintainability having changes made to the $port
variable.
Some likely errors returned from above:
PDO Exception: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
PDO Exception: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.
In the below error, we are at least getting closer, after changing our connect information:
PDO Exception: SQLSTATE[HY000] [1045] Access denied for user 'GuySmiley'@'localhost' (using password: YES)
After further changes, we are really close now, but not quite:
PDO Exception: SQLSTATE[HY000] [1049] Unknown database 'mustard'
From the Manual on PDO Connections:
What about
lstCountry.Items[lstCountry.SelectedIndex].Text;
The JSONArray.length() returns the number of elements in the JSONObject contained in the Array. Not the size of the array itself.
The approach I took reads the header information from the first row to determine the indexes of the columns of interest.
You mentioned in the question that you also want the values output to a string. I dynamically build a format string for the output from the FORMAT column list. Rows are appended to the values string separated by a new line char.
The output column order is determined by the order of the column names in the FORMAT list.
In my code below the case of the column name in the FORMAT list is important. In the question above you've got 'Pincode' in your FORMAT list, but 'PinCode' in your excel. This wouldn't work below, it would need to be 'PinCode'.
from xlrd import open_workbook
wb = open_workbook('sample.xls')
FORMAT = ['Arm_id', 'DSPName', 'PinCode']
values = ""
for s in wb.sheets():
headerRow = s.row(0)
columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == firstRow[x].value]
formatString = ("%s,"*len(columnIndex))[0:-1] + "\n"
for row in range(1,s.nrows):
currentRow = s.row(row)
currentRowValues = [currentRow[x].value for x in columnIndex]
values += formatString % tuple(currentRowValues)
print values
For the sample input you gave above this code outputs:
>>> 1.0,JaVAS,282001.0
2.0,JaVAS,282002.0
3.0,JaVAS,282003.0
And because I'm a python noob, props be to: this answer, this answer, this question, this question and this answer.
Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.
You have four ways of accessing a specific item in a vector:
[]
operatorat(...)
std::for_each
from the algorithm
header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.In the following examples I will be using the following vector as a lab rat and explaining the first three methods:
static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));
This creates a vector as seen below:
1 2 3 4
First let's look at the []
way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possibly you access the item you want. I say possibly because the []
operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:
v[10] = 9;
This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100
instead of 234
, which is somewhat connected to that very location where you retrieve an item from you vector.
A much better way is to use at(...)
. This will automatically check for out of bounds
behaviour and break throwing an std::out_of_range
. So in the case when we have
v.at(10) = 9;
We will get:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)
The third way is similar to the []
operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:
std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9; // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...
As you can see we can also do
*(it+10) = 9;
which is again an invalid memory access. This is basically the same as using at(0 + offset)
but without the out of bounds error checking.
I would advice using at(...)
whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the []
operator.
The verbose
configuration option might allow you to see what you want. There is an example in the documentation.
NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.
I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.
class k:
pass
a = k()
k2 = a.__class__
a2 = k2()
At this point, a and a2 are both instances of the same class (class k).
On a different note, it is also always a good practice to add a token to your form and verify it to check if the data was not sent from outside. Here are the steps:
Generate a unique token (you can use hash) Ex:
$token = hash (string $algo , string $data [, bool $raw_output = FALSE ] );
Assign this token to a session variable. Ex:
$_SESSION['form_token'] = $token;
Add a hidden input to submit the token. Ex:
input type="hidden" name="token" value="{$token}"
then as part of your validation, check if the submitted token matches the session var.
Ex: if ( $_POST['token'] === $_SESSION['form_token'] ) ....
there are many options that would change the height of an input box. padding, font-size, height would all do this. different combinations of these produce taller input boxes with different styles. I suggest just changing the font-size (and font-family for looks) and add some padding to make it even taller and also more appealing. I will give you an example of all three style though:
#signin input {
font-size:20px;
}
OR
#signin input {
padding:10px;
}
OR
#signin input {
height:24px;
}
This is the combination of the three that I recommend:
#signin input {
font-size:20px;font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-weight: 300;
padding:10px;
}
Try this:
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:view.bounds];
view.layer.masksToBounds = NO;
view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(0.0f, 5.0f);
view.layer.shadowOpacity = 0.5f;
view.layer.shadowPath = shadowPath.CGPath;
First of all: The UIBezierPath
used as shadowPath
is crucial. If you don't use it, you might not notice a difference at first, but the keen eye will observe a certain lag occurring during events like rotating the device and/or similar. It's an important performance tweak.
Regarding your issue specifically: The important line is view.layer.masksToBounds = NO
. It disables the clipping of the view's layer's sublayers that extend further than the view's bounds.
For those wondering what the difference between masksToBounds
(on the layer) and the view's own clipToBounds
property is: There isn't really any. Toggling one will have an effect on the other. Just a different level of abstraction.
Swift 2.2:
override func layoutSubviews()
{
super.layoutSubviews()
let shadowPath = UIBezierPath(rect: bounds)
layer.masksToBounds = false
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = CGSizeMake(0.0, 5.0)
layer.shadowOpacity = 0.5
layer.shadowPath = shadowPath.CGPath
}
Swift 3:
override func layoutSubviews()
{
super.layoutSubviews()
let shadowPath = UIBezierPath(rect: bounds)
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
layer.shadowOpacity = 0.5
layer.shadowPath = shadowPath.cgPath
}
This is now part of the language. See TypeScriptLang.org > Basic Types > enum for the documentation on this. An excerpt from the documentation on how to use these enums:
enum Color {Red, Green, Blue};
var c: Color = Color.Green;
Or with manual backing numbers:
enum Color {Red = 1, Green = 2, Blue = 4};
var c: Color = Color.Green;
You can also go back to the enum name by using for example Color[2]
.
Here's an example of how this all goes together:
module myModule {
export enum Color {Red, Green, Blue};
export class MyClass {
myColor: Color;
constructor() {
console.log(this.myColor);
this.myColor = Color.Blue;
console.log(this.myColor);
console.log(Color[this.myColor]);
}
}
}
var foo = new myModule.MyClass();
This will log:
undefined 2 Blue
Because, at the time of writing this, the Typescript Playground will generate this code:
var myModule;
(function (myModule) {
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
})(myModule.Color || (myModule.Color = {}));
var Color = myModule.Color;
;
var MyClass = (function () {
function MyClass() {
console.log(this.myColor);
this.myColor = Color.Blue;
console.log(this.myColor);
console.log(Color[this.myColor]);
}
return MyClass;
})();
myModule.MyClass = MyClass;
})(myModule || (myModule = {}));
var foo = new myModule.MyClass();
Replace:
$authorization = "Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"
with:
$authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274";
to make it a valid and working Authorization header.
element.remove()
The DOM is organized in a tree of nodes, where each node has a value, along with a list of references to its child nodes. So element.parentNode.removeChild(element)
mimics exactly what is happening internally: First you go the parent node, then remove the reference to the child node.
As of DOM4, a helper function is provided to do the same thing: element.remove()
. This works in 96% of browsers (as of 2020), but not IE 11. If you need to support older browsers, you can:
It's nice that Go has a Duration
type -- having explicitly defined units can prevent real-world problems.
And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.
/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
return time.Duration(factor) * d // method 1 -- multiply in 'Duration'
// return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}
The official documentation demonstrates using method #1:
To convert an integer number of units to a Duration, multiply:
seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s
. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).
By the way, the int64
representation of Duration
in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration
, like int64
, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292
, and that's exactly how it is implemented:
// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64
So, because we know that the underlying representation of Duration
is an int64
, performing the cast between int64
and Duration
is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.
If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.
Edit httpd.conf file, which is in /etc/httpd/conf/httpd.conf
. Add the below code.
<Directory "/">
#Options FollowSymLinks
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride None
Allow from all
</Directory>
<Directory "/home/">
#Options FollowSymLinks
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride None
Allow from all
</Directory>
After the line no. 555 (in my case) . Check for the file permissions and restart the server.
service httpd restart
Now, it will work . Still you are facing the same problem, disable the seLinux
in /etc/selinux/config
change SELINUX=disabled
and restart the server as mentioned above and try it.
Hope this helps
function wordLimit($str, $limit) {
$arr = explode(' ', $str);
if(count($arr) <= $limit){
return $str;
}
$result = '';
for($i = 0; $i < $limit; $i++){
$result .= $arr[$i].' ';
}
return trim($result);
}
echo wordLimit('Hello Word', 1); // Hello
echo wordLimit('Hello Word', 2); // Hello Word
echo wordLimit('Hello Word', 3); // Hello Word
echo wordLimit('Hello Word', 0); // ''
Since version 4.14 of Linux kernel, vfs_read
and vfs_write
functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:
# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);
# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
loff_t *pos);
Also, filp_open
no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs
).
Download File Usind Download Manager
DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("https://www.globalgreyebooks.com/content/books/ebooks/game-of-life.pdf");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("My File");
request.setDescription("Downloading");//request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"game-of-life");
downloadmanager.enqueue(request);
The dig utility is pretty convenient to use. The order of the arguments don't really matter.I'll show you some easy examples.
To get all root name servers use
# dig
To get a TXT record of a specific host use
# dig example.com txt
# dig host.example.com txt
To query a specific name server just add @nameserver.tld
# dig host.example.com txt @a.iana-servers.net
The SPF RFC4408 says that SPF records can be stored as SPF or TXT. However nearly all use only TXT records at the moment. So you are pretty safe if you only fetch TXT records.
I made a SPF checker for visualising the SPF records of a domain. It might help you to understand SPF records better. You can find it here: http://spf.myisp.ch
use the val() method:
$(document).ready(function () {
var j = $("textarea");
if (j.val().length > 0) {
alert(j.val());
}
});
Just uncomment extension=php_openssl.dll Restart Apache Service and that should help.
What is happening here is that database route does not accept any url methods.
I would try putting the url methods in the app route just like you have in the entry_page function:
@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
if request.method == 'POST':
date = request.form['date']
title = request.form['blog_title']
post = request.form['blog_main']
post_entry = models.BlogPost(date = date, title = title, post = post)
db.session.add(post_entry)
db.session.commit()
return redirect(url_for('database'))
else:
return render_template('entry.html')
@app.route('/database', methods=['GET', 'POST'])
def database():
query = []
for i in session.query(models.BlogPost):
query.append((i.title, i.post, i.date))
return render_template('database.html', query = query)
If you are using the vs code for editing then try restarting the editor.This scenario fixed my issue.I think it's the issue with editor cache.
I ran into a similar issue. I deleted these:
contents of the build folder.
then rebuild.
* DON'T FORGET TO BACKUP YOUR PROJECT FIRST *
SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.
As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.
More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.
Adding to the other answers and doing nothing more of what @Maleta explained in a comment on https://stackoverflow.com/a/28481374/1626594, doing alpha*255 then round then to hex. Here's a quick converter http://jsfiddle.net/8ajxdLap/4/
function rgb2hex(rgb) {_x000D_
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?((?:[0-9]*[.])?[0-9]+)[\s+]?\)/i);_x000D_
if (rgbm && rgbm.length === 5) {_x000D_
return "#" +_x000D_
('0' + Math.round(parseFloat(rgbm[4], 10) * 255).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
} else {_x000D_
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);_x000D_
if (rgbm && rgbm.length === 4) {_x000D_
return "#" +_x000D_
("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
} else {_x000D_
return "cant parse that";_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
$('button').click(function() {_x000D_
var hex = rgb2hex($('#in_tb').val());_x000D_
$('#in_tb_result').html(hex);_x000D_
});
_x000D_
body {_x000D_
padding: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Convert RGB/RGBA to hex #RRGGBB/#AARRGGBB:<br>_x000D_
<br>_x000D_
<input id="in_tb" type="text" value="rgba(200, 90, 34, 0.75)"> <button>Convert</button><br>_x000D_
<br> Result: <span id="in_tb_result"></span>
_x000D_
select concat('''','abc','''')
A better solution for your problem might be the Charts library. It enables you to use the excellent Highcharts javascript library to make beautiful and interactive plots. Highcharts uses the HTML svg
tag so all your charts are actually vector images.
Some features:
Disclaimer: I'm the developer of the library
=$G1="X"
would be the correct (and easiest) method. Just select the entire sheet first, as conditional formatting only works on selected cells. I just tried it and it works perfectly. You must start at G1 rather than G2 otherwise it will offset the conditional formatting by a row.
I was having the exact same error.
Here's what you need to do:
If you are using MAMP, close your server. Then click on the preferences button when you open up MAMP again (before restarting your server of course).
Then you will need to click on the ports tab, and click the button "Set Web and MySQL Ports to 80 & 3306".
Try this:
SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL
To test it using a new date instance:
SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL
Output is: 06-10-2015 22:00, which is the previous day.
I know this thread is old, but i just got into that exactly problem and i fixed it by just using the page-header
class in my page, under the nav. Also i used the <nav>
tag instead of <div>
but i am not sure it would present any different behavior.
Using the page-header
as a container for the page, you won't need to mess with the <body>
, only if you disagree with the default space that the page-header
gives you.
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<div class="container-fluid">_x000D_
<nav class="navbar navbar-default navbar-fixed-top">_x000D_
_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Bootstrap</a>_x000D_
</div>_x000D_
<div id="navbar" class="navbar-collapse collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li class="active"><a href="#">Home</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">Action</a></li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li role="separator" class="divider"></li>_x000D_
<li class="dropdown-header">Nav header</li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
<li><a href="#">One more separated link</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
<div class="navbar-right">_x000D_
</div>_x000D_
</div>_x000D_
</nav>_x000D_
</div>_x000D_
<div class="page-header">_x000D_
<div class="clearfix">_x000D_
<div class="col-md-12">_x000D_
<div class="col-md-8 col-sm-6 col-xs-12">_x000D_
<h1>Registration form <br /><small>A Bootstrap template showing a registration form with standard fields</small></h1>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<form role="form">_x000D_
<div class="col-lg-6">_x000D_
<div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk"></span>Required Field</strong></div>_x000D_
<div class="form-group">_x000D_
<label for="InputName">Enter Name</label>_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control" name="InputName" id="InputName" placeholder="Enter Name" required>_x000D_
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="InputEmail">Enter Email</label>_x000D_
<div class="input-group">_x000D_
<input type="email" class="form-control" id="InputEmailFirst" name="InputEmail" placeholder="Enter Email" required>_x000D_
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="InputEmail">Confirm Email</label>_x000D_
<div class="input-group">_x000D_
<input type="email" class="form-control" id="InputEmailSecond" name="InputEmail" placeholder="Confirm Email" required>_x000D_
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="InputMessage">Enter Message</label>_x000D_
<div class="input-group">_x000D_
<textarea name="InputMessage" id="InputMessage" class="form-control" rows="5" required></textarea>_x000D_
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
</div>_x000D_
</div>_x000D_
<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">_x000D_
</div>_x000D_
</form>_x000D_
</div>
_x000D_