I had the same issue when upgrading from Tomcat 7 to 8: a continuous large flood of log warnings about cache.
Add this within the Context
xml element of your $CATALINA_BASE/conf/context.xml
:
<!-- The default value is 10240 kbytes, even when not added to context.xml.
So increase it high enough, until the problem disappears, for example set it to
a value 5 times as high: 51200. -->
<Resources cacheMaxSize="51200" />
So the default is 10240
(10 mbyte), so set a size higher than this. Than tune for optimum settings where the warnings disappear.
Note that the warnings may come back under higher traffic situations.
The problem is caused by Tomcat being unable to reach its target cache size due to cache entries that are less than the TTL of those entries. So Tomcat didn't have enough cache entries that it could expire, because they were too fresh, so it couldn't free enough cache and thus outputs warnings.
The problem didn't appear in Tomcat 7 because Tomcat 7 simply didn't output warnings in this situation. (Causing you and me to use poor cache settings without being notified.)
The problem appears when receiving a relative large amount of HTTP requests for resources (usually static) in a relative short time period compared to the size and TTL of the cache. If the cache is reaching its maximum (10mb by default) with more than 95% of its size with fresh cache entries (fresh means less than less than 5 seconds in cache), than you will get a warning message for each webResource that Tomcat tries to load in the cache.
Use JMX if you need to tune cacheMaxSize on a running server without rebooting it.
The quickest fix would be to completely disable cache: <Resources cachingAllowed="false" />
, but that's suboptimal, so increase cacheMaxSize as I just described.
A WebSource is a file or directory in a web application. For performance reasons, Tomcat can cache WebSources. The maximum of the static resource cache (all resources in total) is by default 10240 kbyte (10 mbyte). A webResource is loaded into the cache when the webResource is requested (for example when loading a static image), it's then called a cache entry. Every cache entry has a TTL (time to live), which is the time that the cache entry is allowed to stay in the cache. When the TTL expires, the cache entry is eligible to be removed from the cache. The default value of the cacheTTL is 5000 milliseconds (5 seconds).
There is more to tell about caching, but that is irrelevant for the problem.
The following code from the Cache class shows the caching policy in detail:
152 // Content will not be cached but we still need metadata size
153 long delta = cacheEntry.getSize();
154 size.addAndGet(delta);
156 if (size.get() > maxSize) {
157 // Process resources unordered for speed. Trades cache
158 // efficiency (younger entries may be evicted before older
159 // ones) for speed since this is on the critical path for
160 // request processing
161 long targetSize =
162 maxSize * (100 - TARGET_FREE_PERCENT_GET) / 100;
163 long newSize = evict(
164 targetSize, resourceCache.values().iterator());
165 if (newSize > maxSize) {
166 // Unable to create sufficient space for this resource
167 // Remove it from the cache
168 removeCacheEntry(path);
169 log.warn(sm.getString("cache.addFail", path));
170 }
171 }
When loading a webResource, the code calculates the new size of the cache. If the calculated size is larger than the default maximum size, than one or more cached entries have to be removed, otherwise the new size will exceed the maximum. So the code will calculate a "targetSize", which is the size the cache wants to stay under (as an optimum), which is by default 95% of the maximum. In order to reach this targetSize, entries have to be removed/evicted from the cache. This is done using the following code:
215 private long evict(long targetSize, Iterator<CachedResource> iter) {
217 long now = System.currentTimeMillis();
219 long newSize = size.get();
221 while (newSize > targetSize && iter.hasNext()) {
222 CachedResource resource = iter.next();
224 // Don't expire anything that has been checked within the TTL
225 if (resource.getNextCheck() > now) {
226 continue;
227 }
229 // Remove the entry from the cache
230 removeCacheEntry(resource.getWebappPath());
232 newSize = size.get();
233 }
235 return newSize;
236 }
So a cache entry is removed when its TTL is expired and the targetSize hasn't been reached yet.
After the attempt to free cache by evicting cache entries, the code will do:
165 if (newSize > maxSize) {
166 // Unable to create sufficient space for this resource
167 // Remove it from the cache
168 removeCacheEntry(path);
169 log.warn(sm.getString("cache.addFail", path));
170 }
So if after the attempt to free cache, the size still exceeds the maximum, it will show the warning message about being unable to free:
cache.addFail=Unable to add the resource at [{0}] to the cache for web application [{1}] because there was insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache
So as the warning message says, the problem is
insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache
If your web application loads a lot of uncached webResources (about maximum of cache, by default 10mb) within a short time (5 seconds), then you'll get the warning.
The confusing part is that Tomcat 7 didn't show the warning. This is simply caused by this Tomcat 7 code:
1606 // Add new entry to cache
1607 synchronized (cache) {
1608 // Check cache size, and remove elements if too big
1609 if ((cache.lookup(name) == null) && cache.allocate(entry.size)) {
1610 cache.load(entry);
1611 }
1612 }
combined with:
231 while (toFree > 0) {
232 if (attempts == maxAllocateIterations) {
233 // Give up, no changes are made to the current cache
234 return false;
235 }
So Tomcat 7 simply doesn't output any warning at all when it's unable to free cache, whereas Tomcat 8 will output a warning.
So if you are using Tomcat 8 with the same default caching configuration as Tomcat 7, and you got warnings in Tomcat 8, than your (and mine) caching settings of Tomcat 7 were performing poorly without warning.
There are multiple solutions:
As described here: http://tomcat.apache.org/tomcat-8.0-doc/config/resources.html
By adding <Resources cacheMaxSize="XXXXX" />
within the Context
element in $CATALINA_BASE/conf/context.xml
, where "XXXXX" stands for an increased cache size, specified in kbytes. The default is 10240 (10 mbyte), so set a size higher than this.
You'll have to tune for optimum settings. Note that the problem may come back when you suddenly have an increase in traffic/resource requests.
To avoid having to restart the server every time you want to try a new cache size, you can change it without restarting by using JMX.
To enable JMX, add this to $CATALINA_BASE/conf/server.xml
within the Server
element:
<Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener" rmiRegistryPortPlatform="6767" rmiServerPortPlatform="6768" />
and download catalina-jmx-remote.jar
from https://tomcat.apache.org/download-80.cgi and put it in $CATALINA_HOME/lib
.
Then use jConsole (shipped by default with the Java JDK) to connect over JMX to the server and look through the settings for settings to increase the cache size while the server is running. Changes in these settings should take affect immediately.
Lower the cacheTtl
value by something lower than 5000 milliseconds and tune for optimal settings.
For example: <Resources cacheTtl="2000" />
This comes effectively down to having and filling a cache in ram without using it.
Configure logging to disable the logger for org.apache.catalina.webresources.Cache
.
For more info about logging in Tomcat: http://tomcat.apache.org/tomcat-8.0-doc/logging.html
You can disable the cache by setting cachingAllowed
to false
.
<Resources cachingAllowed="false" />
Although I can remember that in a beta version of Tomcat 8, I was using JMX to disable the cache. (Not sure why exactly, but there may be a problem with disabling the cache via server.xml.)
In my case the problem is fixed by setting the right permissions for the tomcat home path:
cd /opt/apache-tomee-webprofile-7.1.0/
chown -R tomcat:tomcat *
Try this!
Client client = ClientBuilder.newClient();
String jsonStr = client
.target("http:....")
.request(MediaType.APPLICATION_JSON)
.header("WM_SVC.NAME", "RegistryService")
.header("WM_QOS.CORRELATION_ID", "d1f0c0d2-2cf4-497b-b630-06d609d987b0")
.get(String.class);
P.S You can add any number of headers like this!
The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.
The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
Setting this attribute to ObjectMapper instance works,
objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
i agree with you about alternative solutions which you mentioned above
1. Use POST instead of GET;
2. Transform the List into a JSON string and pass it to the service.
and its true that you can't add List
to MultiValuedMap
because of its impl class MultivaluedMapImpl
have capability to accept String Key and String Value. which is shown in following figure
still you want to do that things than try following code.
Controller Class
package net.yogesh.test;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import com.google.gson.Gson;
@Path("test")
public class TestController {
@Path("testMethod")
@GET
@Produces("application/text")
public String save(
@QueryParam("list") List<String> list) {
return new Gson().toJson(list) ;
}
}
Client Class
package net.yogesh.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class Client {
public static void main(String[] args) {
String op = doGet("http://localhost:8080/JerseyTest/rest/test/testMethod");
System.out.println(op);
}
private static String doGet(String url){
List<String> list = new ArrayList<String>();
list = Arrays.asList(new String[]{"string1,string2,string3"});
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
String lst = (list.toString()).substring(1, list.toString().length()-1);
params.add("list", lst);
ClientConfig config = new DefaultClientConfig();
com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
WebResource resource = client.resource(url);
ClientResponse response = resource.queryParams(params).type("application/x-www-form-urlencoded").get(ClientResponse.class);
String en = response.getEntity(String.class);
return en;
}
}
hope this'll help you.
for Python and Swagger example:
import requests
base_url = 'https://petstore.swagger.io/v2'
def store_order(uid):
api_url = f"{base_url}/store/order"
api_data = {
'id':uid,
"petId": 0,
"quantity": 0,
"shipDate": "2020-04-08T07:56:05.832Z",
"status": "placed",
"complete": "true"
}
# is a kind of magic..
r = requests.post(api_url, json=api_data)
return r
print(store_order(0).content)
Most important string with MIME type: r = requests.post(api_url, json=api_data)
Your @POST
method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:
@XmlRootElement
public class MyJaxBean {
@XmlElement public String param1;
@XmlElement public String param2;
}
Then your @POST
method would look like the following:
@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
System.out.println("param1 = " + input.param1);
System.out.println("param2 = " + input.param2);
}
This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input
in this case. The actual message would look something like:
POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com
{"param1":"hello","param2":"world"}
Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.
HTML <FORM>
The parameters would be annotated using @FormParam:
@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
@FormParam("param2") String param2) {
...
}
The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:
POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25
param1=hello¶m2=world
The content is URL encoded in this case.
If you do not know the names of the FormParam's you can do the following:
@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
...
}
HTTP Headers
You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:
@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
@HeaderParam("param2") String param2) {
...
}
Here's what the HTTP message would look like. Note that this POST does not have a body.
POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world
I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.
HTTP Query Parameters
This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.
@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
@QueryParam("param2") String param2) {
...
}
Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:
POST /create?param1=hello¶m2=world HTTP/1.1
Content-Length: 0
Host: www.example.com
You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.
HTTP Path Parameters
Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:
@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
@PathParam("param2") String param2) {
...
}
The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.
POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com
This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.
As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM
-based HTML pages, then use @FormParam
. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer
implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM
encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.
Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.
Make sure that all these libs are in your class path:
compile(group: 'com.sun.jersey', name: 'jersey-core', version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-server', version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-servlet', version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-json', version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-client', version: '1.19.4')
compile(group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-jaxrs', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-xc', version: '1.9.2')
Add "Pojo Mapping" and "Jackson Provider" to the jersey client config:
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
clientConfig.getClasses().add(JacksonJsonProvider.class);
This solve to me!
ClientResponse response = null;
response = webResource
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
MyClass myclass = response.getEntity(MyClass.class);
System.out.println(myclass);
}
For Jersey 1.X
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// or you can return null too
return new java.security.cert.X509Certificate[0];
}
}};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String string, SSLSession sslSession) {
return true;
}
});
Just set the outline to none like this
[Identifier] { outline:none; }
Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.
An alternative option is to set it in the machine level web.config, so its not even in the web site folder.
To generate it do it just like the linked article in David's answer.
Check this out: http://code.google.com/p/resting/. I could use resting to consume HTTPS REST services.
You probably mean the difference between Http Only cookies and their counter part?
Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.
Compare the cell with "" (empty line):
=IF(A1="",1,0)
if you have a char/varchar value formatted as the standard GUID, you can simply store it as BINARY(16) using the simple CAST(MyString AS BINARY16), without all those mind-boggling sequences of CONCAT + SUBSTR.
BINARY(16) fields are compared/sorted/indexed much faster than strings, and also take two times less space in the database
As @Brian Riley already said you should either remove 1 column in your select
select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;
or add it to your grouping
select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;
With this we can pass a key function to use for the sorting
Array.prototype.sortBy = function(key_func, reverse=false){
return this.sort( (a, b) => {
var keyA = key_func(a),
keyB = key_func(b);
if(keyA < keyB) return reverse? 1: -1;
if(keyA > keyB) return reverse? -1: 1;
return 0;
});
}
Then for example if we have
var arr = [ {date: "01/12/00", balls: {red: "a8", blue: 10}},
{date: "12/13/05", balls: {red: "d6" , blue: 11}},
{date: "03/02/04", balls: {red: "c4" , blue: 15}} ]
We can do
arr.sortBy(el => el.balls.red)
/* would result in
[ {date: "01/12/00", balls: {red: "a8", blue: 10}},
{date: "03/02/04", balls: {red: "c4", blue: 15}},
{date: "12/13/05", balls: {red: "d6", blue: 11}} ]
*/
or
arr.sortBy(el => new Date(el.date), true) // second argument to reverse it
/* would result in
[ {date: "12/13/05", balls: {red: "d6", blue:11}},
{date: "03/02/04", balls: {red: "c4", blue:15}},
{date: "01/12/00", balls: {red: "a8", blue:10}} ]
*/
or
arr.sortBy(el => el.balls.blue + parseInt(el.balls.red[1]))
/* would result in
[ {date: "12/13/05", balls: {red: "d6", blue:11}}, // red + blue= 17
{date: "01/12/00", balls: {red: "a8", blue:10}}, // red + blue= 18
{date: "03/02/04", balls: {red: "c4", blue:15}} ] // red + blue= 19
*/
When the DLL was created an import lib is usually automatically created and you should use that linked in to your program along with header files to call it but if not then you can manually call windows functions like LoadLibrary and GetProcAddress to get it working.
Based on inspiration from answer. I defined a function as below. Looks like its working fine. Please let me know if you find any issue
def isanumber(inp):
try:
val = int(inp)
return True
except ValueError:
try:
val = float(inp)
return True
except ValueError:
return False
Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository
in your settings.xml
or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.
A workaround is as follows. In the value:
releases::default::https://YOUR_NEXUS_URL/releases
you need to remove the default
section, making it:
releases::https://YOUR_NEXUS_URL/releases
The prior version 2.8.2 does not have this bug.
I think, that you have to declare the associated sheet!
Try something like this
objsheet(1).Cells[i,j].Value;
If you are on windows, you can use PeekConsoleInput to detect if there's any input,
HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD events;
INPUT_RECORD buffer;
PeekConsoleInput( handle, &buffer, 1, &events );
then use ReadConsoleInput to "consume" the input character ..
PeekConsoleInput(handle, &buffer, 1, &events);
if(events > 0)
{
ReadConsoleInput(handle, &buffer, 1, &events);
return buffer.Event.KeyEvent.wVirtualKeyCode;
}
else return 0
to be honest this is from some old code I have, so you have to fiddle a bit with it.
The cool thing though is that it reads input without prompting for anything, so the characters are not displayed at all.
I was in the same trouble. For my case, that was a conflict between /etc/zabbix/zabbix_agentd.conf and zabbix_server.conf parameters. I adjusted
"DBHost=localhost",
"DBName=zabbix",
"DBUser=zabbix",
"DBPassword=******",
"DebugLevel=3"
"ListenPort".
If you run the default installation, you should keep ListenPort=10051 for the server and 10050 for the agent.
Cheers!
Using @Adrian Frühwirth answer:
function strip {
local STRING=${1#$"$2"}
echo ${STRING%$"$2"}
}
use it like this
HELLO=":hello:"
HELLO=$(strip "$HELLO" ":")
echo $HELLO # hello
The "$1" is not "useless non-sense". If your class is anonymous, a number is appended.
If you don't want the class itself, but its declaring class, then you can use getEnclosingClass()
. For example:
Class<?> enclosingClass = getClass().getEnclosingClass();
if (enclosingClass != null) {
System.out.println(enclosingClass.getName());
} else {
System.out.println(getClass().getName());
}
You can move that in some static utility method.
But note that this is not the current class name. The anonymous class is different class than its enclosing class. The case is similar for inner classes.
As stated in the JQuery documentation
The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
"await is only valid in async function"
But why? 'await' explicitly turns an async call into a synchronous call, and therefore the caller cannot be async (or asyncable) - at least, not because of the call being made at 'await'.
I am bit confused. If all you are wanting is for a variables value to not pass to another script then there is no need to delete the variable from the scope. Simply nullify the variable then explicit check if it is or is not null. Why go through the trouble of deleting the variable from scope? What purpose does this server that nullifying can not?
foo = null;
if(foo === null) or if(foo !== null)
public MainWindow()
{
// This button needs to exist on your form.
myButton.Click += myButton_Click;
}
void myButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Message here");
this.Close();
}
Pekka has the correct answer (hence my making this answer a Community Wiki): Use src
, not href
, to specify the file.
Regarding:
When i try it this way:
<script type="text/javascript"> document.write('<script type="text/javascript" src="datetimepicker_css.js"></script>'); </script>the first tag in the document.write function closes
what is the correct way to do this?
You don't want or need document.write
for this, but just in case you ever do need to put the characters </script>
inside a script
tag for some other reason: You do that by ensuring that the HTML parser (which doesn't understand JavaScript) doesn't see a literal </script>
. There are a couple of ways of doing that. One way is to escape the /
even though you don't need to:
<script type='text/javascript'>
alert("<\/script>"); // Works, HTML parser doesn't see this as a closing script tag
// ^--- note the seemingly-unnecessary backslash
</script>
Or if you're feeling more paranoid:
<script type='text/javascript'>
alert("</scr" + "ipt>"); // Works, HTML parser doesn't see this as a closing script tag
</script>
...since in each case, JavaScript sees the string as </script>
but the HTML parser doesn't.
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);
its going to give you solution i suppose
This line causes the [unchecked] warning:
List<String> list = new LinkedList();
So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?
I think, it would be much more difficult task then adding <>
feature.
UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.
Primitives are a different kind of type than objects created from within Javascript. From the Mozilla API docs:
var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)
I can't find any way to construct primitive types with code, perhaps it's not possible. This is probably why people use typeof "foo" === "string"
instead of instanceof
.
An easy way to remember things like this is asking yourself "I wonder what would be sane and easy to learn"? Whatever the answer is, Javascript does the other thing.
According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData});
Codetoffel answer does work just fine for me though.
You might try passing actual types instead of strings.
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime, datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
But it's going to be really hard to diagnose this without any of your data to tinker with.
And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)
Here is how I do it with jQuery
j(".textBoxClass").keypress(function(e)
{
// if the key pressed is the enter key
if (e.which == 13)
{
// do work
}
});
Other javascript wouldnt be too different. the catch is checking for keypress argument of "13", which is the enter key
As Peter says, they won't be in Maven Central
from the Android SDK Manager download the 'Android Support Repository' and a Maven repo of the support libraries will be downloaded to your Android SDK directory (see 'extras' folder)
to deploy the libraries to your local .m2 repository you can use maven-android-sdk-deployer
2017 edit:
you can now reference the Google online M2 repo
repositories {
google()
jcenter()
}
I wrote some simple thing:
When you initialize icheck
as:
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
Add this code under it:
$('input').on('ifChecked', function (event){
$(this).closest("input").attr('checked', true);
});
$('input').on('ifUnchecked', function (event) {
$(this).closest("input").attr('checked', false);
});
After this you can easily find your original checkbox's state.
I wrote this code for using icheck
in gridView
and accessed its state from server side by C#.
Simply find your checkBox from its id.
. I usually do it
element.value="<script>alert('test');</script>"
.
If sounds like you are generating an inline <script>
element, in which case the </script>
will end the HTML element and cause the script to terminate in the middle of the string.
Escape the /
so that it isn't treated as an end tag by the HTML parser:
element.value = "<script>alert('test');<\/script>"
If your integer is timestamp in milliseconds use:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format milliseconds to yyyy-mm-dd string.
See this jsFiddle example. Resize and see how the fixed elements even move with the floated elements they are in. Use the inner-most scroll bar to see how the scroll would work on a site (fixed elements staying fixed).
As many here have stated, one key is not setting any positional settings on the fixed
element (no top
, right
, bottom
, or left
values).
Rather, we put all the fixed elements (note how the last box has four of them) first in the box they are to be positioned off of, like so:
<div class="reference">
<div class="fixed">Test</div>
Some other content in.
</div>
Then we use margin-top
and margin-left
to "move" them in relation to their container, something like as this CSS does:
.fixed {
position: fixed;
margin-top: 200px; /* Push/pull it up/down */
margin-left: 200px; /* Push/pull it right/left */
}
Note that because fixed
elements ignore all other layout elements, the final container in our fiddle can have multiple fixed
elements, and still have all those elements related to the top left corner. But this is only true if they are all placed first in the container, as this comparison fiddle shows that if dispersed within the container content, positioning becomes unreliable.
Whether the wrapper is static, relative, or absolute in positioning, it does not matter.
Agree with Subir Kumar Sao and Faiz.
element_enter.findElement(By.xpath("//html/body/div[1]/div[3]/div[1]/form/div/div/input")).sendKeys(barcode);
I couldn't figure out what the "categories" NSSet variable should be set to, so if someone could fill me in I will gladly edit this post. The following does, however, bring up the push notification dialog.
[[UIApplication sharedApplication] registerForRemoteNotifications];
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
Edit: I got a push notification to send to my phone with this code, so I'm not sure the categories parameter is necessary.
You can optimize the query using Dense_rank() function.
for Example :
select distinct salary from ( select salary ,dense_rank() over (order by salary desc) ranking from Employee ) where ranking = 6
Note: ranking 6 is the number of nth order.
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat
For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html
Ok, so you've found a solution already. Just wanted to share what has been useful to me so many times;
I have created setpy2
alias which helps me switch python.
alias setpy2="mkdir -p /tmp/bin; ln -s `which python2.7` /tmp/bin/python; export PATH=/tmp/bin:$PATH"
Execute setpy2
before you run npm install
. The switch stays in effect until you quit the terminal, afterwards python
is set back to system default.
You can make use of this technique for any other command/tool as well.
That can be achieve in plain LaTeX without any specific package.
\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
\left\{
\begin{array}{l}
0\\
1
\end{array}
\right.
\end{math}
\end{document}
This code produces something which looks what you seems to need.
The same example as in the @Tombart can be obtained with similar code.
\documentclass{article}
\begin{document}
\begin{math}
f(x)=\left\{
\begin{array}{ll}
1, & \mbox{if $x<0$}.\\
0, & \mbox{otherwise}.
\end{array}
\right.
\end{math}
\end{document}
This code produces very similar results.
TypeScript uses '<>' to surround casts, so the above becomes:
var script = <HTMLScriptElement>document.getElementsByName("script")[0];
However, unfortunately you cannot do:
var script = (<HTMLScriptElement[]>document.getElementsByName(id))[0];
You get the error
Cannot convert 'NodeList' to 'HTMLScriptElement[]'
But you can do :
(<HTMLScriptElement[]><any>document.getElementsByName(id))[0];
You would use the javascript date object:
MDN documentation for the Date object
var d = new Date();
Using collections.defaultdict
is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.
Here it's used twice: for the resulting dict, and for each of the values in the dict.
import collections
def aggregate_names(errors):
result = collections.defaultdict(lambda: collections.defaultdict(list))
for real_name, false_name, location in errors:
result[real_name][false_name].append(location)
return result
Combining this with your code:
dictionary = aggregate_names(previousFunction(string))
Or to test:
EXAMPLES = [
('Fred', 'Frad', 123),
('Jim', 'Jam', 100),
('Fred', 'Frod', 200),
('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)
In .net core 3 this is now possible with the built-in classes in System.Text.Json (edit: System.Text.Json is also available as a NuGet package for .net core 2.0 and .net framework 4.7.2 and later versions according to the docs):
var person = new Person();
// Create and add a converter which will use the string representation instead of the numeric value.
var stringEnumConverter = new System.Text.Json.Serialization.JsonStringEnumConverter();
JsonSerializerOptions opts = new JsonSerializerOptions();
opts.Converters.Add(stringEnumConverter);
// Generate json string.
var json = JsonSerializer.Serialize<Person>(person, opts);
To configure JsonStringEnumConverter
with attribute decoration for the specific property:
using System.Text.Json.Serialization;
[JsonConverter(typeof(JsonStringEnumConverter))]
public Gender Gender { get; set; }
If you want to always convert the enum as string, put the attribute at the enum itself.
[JsonConverter(typeof(JsonStringEnumConverter))]
enum Gender { Male, Female }
If you use Vim, you can use the inbuilt diff functionality. vim -d file1 file2
takes you right into the diff screen, where you can do all sort of merge and deletes.
Let's start by eliminating StringTokenizer
. It is getting old and doesn't even support regular expressions. Its documentation states:
StringTokenizer
is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use thesplit
method ofString
or thejava.util.regex
package instead.
So let's throw it out right away. That leaves split()
and Scanner
. What's the difference between them?
For one thing, split()
simply returns an array, which makes it easy to use a foreach loop:
for (String token : input.split("\\s+") { ... }
Scanner
is built more like a stream:
while (myScanner.hasNext()) {
String token = myScanner.next();
...
}
or
while (myScanner.hasNextDouble()) {
double token = myScanner.nextDouble();
...
}
(It has a rather large API, so don't think that it's always restricted to such simple things.)
This stream-style interface can be useful for parsing simple text files or console input, when you don't have (or can't get) all the input before starting to parse.
Personally, the only time I can remember using Scanner
is for school projects, when I had to get user input from the command line. It makes that sort of operation easy. But if I have a String
that I want to split up, it's almost a no-brainer to go with split()
.
try:
[checked]="item.checked"
check out: How to Deal with Different Form Controls in Angular
Since java 1.5 you can also pass a java.net.Proxy instance to the openConnection(proxy)
method:
//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
If your proxy requires authentication it will give you response 407.
In this case you'll need the following code:
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("user",
"password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
public class XYZ extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
// formattedDate have current date/time
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
// Now we display formattedDate value in TextView
TextView txtView = new TextView(this);
txtView.setText("Current Date and Time : "+formattedDate);
txtView.setGravity(Gravity.CENTER);
txtView.setTextSize(20);
setContentView(txtView);
}
}
You can use the padding-left
attribute on the list items (not on the list itself!).
try this
combobox.SelectedIndex = BindingSource.Item(9) where "9 = colum name 9 from table"
I use this query
column "Tablespace" format a13
column "Used MB" format 99,999,999
column "Free MB" format 99,999,999
column "Total MB" format 99,999,999
select
fs.tablespace_name "Tablespace",
(df.totalspace - fs.freespace) "Used MB",
fs.freespace "Free MB",
df.totalspace "Total MB",
round(100 * (fs.freespace / df.totalspace)) "Pct. Free"
from
(select
tablespace_name,
round(sum(bytes) / 1048576) TotalSpace
from
dba_data_files
group by
tablespace_name
) df,
(select
tablespace_name,
round(sum(bytes) / 1048576) FreeSpace
from
dba_free_space
group by
tablespace_name
) fs
where
df.tablespace_name = fs.tablespace_name;
How about using classes?
# config.py
class MYSQL:
PORT = 3306
DATABASE = 'mydb'
DATABASE_TABLES = ['tb_users', 'tb_groups']
# main.py
from config import MYSQL
print(MYSQL.PORT) # 3306
For those of you who share my weird fondness of manually editing config files, adding (or modifying) the following would also do the trick.
.git/config (personal config)
[submodule "cookbooks/apt"]
url = https://github.com/opscode-cookbooks/apt
.gitmodules (committed shared config)
[submodule "cookbooks/apt"]
path = cookbooks/apt
url = https://github.com/opscode-cookbooks/apt
See this as well - difference between .gitmodules and specifying submodules in .git/config?
I have used in this way.. Working fine!
$inputs = request()->validate([
'name' => 'required | min:6 | max: 20',
'email' => 'required',
'password' => 'required| min:4| max:7 |confirmed',
'password_confirmation' => 'required| min:4'
]);
Algorithm to use for checking well balanced parenthesis -
Now traverse the string expression input.
If the current character is an opening bracket ( '{', '(', '[' ) then push it to the parenStack.
If the current character is a closing bracket ( '}', ')', ']' ) then pop from parenStack and if the popped character is equal to the matching starting bracket in matchingParenMap then continue looping else return false.
After complete traversal if no opening brackets are left in parenStack it means it is a well balanced expression.
I have explained the code snippet of the algorithm used on my blog. Check link - http://hetalrachh.home.blog/2019/12/25/stack-data-structure/
Get NodeList of elements
var elem = document.querySelectorAll('[data-id="container"]')
html: <div data-id="container"></div>
Get the first element
var firstElem = document.querySelector('[id="container"]')
html: <div id="container"></div>
Target a collection of nodes which returns a nodelist
document.getElementById('footer').querySelectorAll('[data-id]')
html:
<div class="footer">
<div data-id="12"></div>
<div data-id="22"></div>
</div>
Get elements based on multiple (OR) data values
document.querySelectorAll('[data-section="12"],[data-selection="20"]')
html:
<div data-selection="20"></div>
<div data-section="12"></div>
Get elements based on combined (AND) data values
document.querySelectorAll('[data-prop1="12"][data-prop2="20"]')
html:
<div data-prop1="12" data-prop2="20"></div>
Get items where the value starts with
document.querySelectorAll('[href^="https://"]')
You do not want to force the garbage collector to run.
However, if you ever did (as a purely academic exercise, of course):
GC.Collect()
this worked for me... found this out on my own... hope it helps you!
1) do NOT have a global "static" FragmentManager / FragmentTransaction.
2) onCreate, ALWAYS initialize the FragmentManager again!
sample below :-
public abstract class FragmentController extends AnotherActivity{
protected FragmentManager fragmentManager;
protected FragmentTransaction fragmentTransaction;
protected Bundle mSavedInstanceState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedInstanceState = savedInstanceState;
setDefaultFragments();
}
protected void setDefaultFragments() {
fragmentManager = getSupportFragmentManager();
//check if on orientation change.. do not re-add fragments!
if(mSavedInstanceState == null) {
//instantiate the fragment manager
fragmentTransaction = fragmentManager.beginTransaction();
//the navigation fragments
NavigationFragment navFrag = new NavigationFragment();
ToolbarFragment toolFrag = new ToolbarFragment();
fragmentTransaction.add(R.id.NavLayout, navFrag, "NavFrag");
fragmentTransaction.add(R.id.ToolbarLayout, toolFrag, "ToolFrag");
fragmentTransaction.commitAllowingStateLoss();
//add own fragment to the nav (abstract method)
setOwnFragment();
}
}
Remove the panel background
<item name="android:windowBackground">@color/transparent_color</item>
<color name="transparent_color">#00000000</color>
This is Mystyle:
<style name="ThemeDialogCustom">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowBackground">@color/transparent_color</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:colorBackgroundCacheHint">@null</item>
</style>
Which i have added to the constructor.
Add textColor :
<item name="android:textColor">#ff0000</item>
From the manual page:
-P prefix
--directory-prefix=prefix
Set directory prefix to prefix. The directory prefix is the
directory where all other files and sub-directories will be
saved to, i.e. the top of the retrieval tree. The default
is . (the current directory).
So you need to add -P /tmp/cron_test/
(short form) or --directory-prefix=/tmp/cron_test/
(long form) to your command. Also note that if the directory does not exist it will get created.
If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.
Steps to create:
Good thing about this solution:
Not so good thing about this solution:
Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq
<button class="btn btn--animation-from-right">
<span class="btn__text-static">Cover left</span>
<div class="btn__text-dynamic">
<span class="btn__text-dynamic-inner">Cover left</span>
</div>
</button>
.btn {
padding: 10px 20px;
position: relative;
border: 2px solid #222;
color: #fff;
background-color: #222;
position: relative;
overflow: hidden;
cursor: pointer;
text-transform: uppercase;
font-family: monospace;
letter-spacing: -1px;
[class^="btn__text"] {
font-size: 24px;
}
.btn__text-dynamic,
.btn__text-dynamic-inner {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
z-index: 2;
transition: all ease 0.5s;
}
.btn__text-dynamic {
background-color: #fff;
color: #222;
overflow: hidden;
}
&:hover {
.btn__text-dynamic {
transform: translateX(-100%);
}
.btn__text-dynamic-inner {
transform: translateX(100%);
}
}
}
.btn--animation-from-right {
&:hover {
.btn__text-dynamic {
transform: translateX(100%);
}
.btn__text-dynamic-inner {
transform: translateX(-100%);
}
}
}
You can remove .btn--animation-from-right modifier if you want to animate to the left.
because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:
SELECT *
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
Then note that we have two table aliases a
and b
. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b
, the statement will be:
UPDATE b
SET b.marks = a.marks
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a
only (leaving b intact) for those records that match by name:
DELETE a
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
You can use the SQL Fiddle created by JW as a playground
I have just been in a similar position with regards to setting the 777 permissions on the apache website hosting directory. After a little bit of tinkering it seems that changing the group ownership of the folder to the "apache" group allowed access to the folder based on the user group.
1) make sure that the group ownership of the folder is set to the group apache used / generates for use. (check /etc/groups, mine was www-data on Ubuntu)
2) set the folder permissions to 774 to stop "everyone" from having any change access, but allowing the owner and group permissions required.
3) add your user account to the group that has permission on the folder (mine was www-data).
this will unhide all files and folders on your computer
attrib -r -s -h /S /D
You may try;
$this->Output(/path/to/file);
So for you, it will be like;
$this->Output(/kuitit/); //or try ("/kuitit/")
This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.
In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os
Next you need to have a line changing the text color, place it were you want in your code.
os.system('color 4')
You can figure out the other colors by starting cmd.exe and typing color help.
The good part? Thats all their is to it, to simple lines of code. -Day
You can use http://rhaboo.org as a wrapper around localStorage. It stores complex objects but doesn't merely stringify and parse the whole thing like most such libraries do. That's really inefficient if you want to store a lot of data and add to it or change it in small chunks. Also, JSON discards a lot of important stuff like non-numerical properties of arrays.
In rhaboo you can write things like this:
var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
var laststamp = store.stamp ? store.stamp.toString() : "never";
store.write('stamp', new Date());
store.write('somethingfancy', {
one: ['man', 'went'],
2: 'mow',
went: [ 2, { mow: ['a', 'meadow' ] }, {} ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');
console.log( store.somethingfancy.went[1].mow[1] ); //says lawn
BTW, I wrote rhaboo
Just Try, no need other plugin / frameworks
document.getElementById("jarscroolbtn").addEventListener("click", jarscrollfunction);_x000D_
_x000D_
function jarscrollfunction() {_x000D_
var body = document.body; // For Safari_x000D_
var html = document.documentElement; // Chrome, Firefox, IE and Opera _x000D_
body.scrollTop = 0; _x000D_
html.scrollTop = 0;_x000D_
}
_x000D_
<button id="jarscroolbtn">Scroll contents</button>
_x000D_
html, body {_x000D_
scroll-behavior: smooth;_x000D_
}
_x000D_
If you are using time.time()
and wants timestamp as output
Simply use
CONSTANT_SECONDS = 900 # time in seconds (900 seconds = 15 min)
current_time = int(time.time())
time_before_15_min = current_time - CONSTANT_SECONDS
You can change 900 seconds as per your required time.
Try
//book[title/@lang = 'it']
This reads:
book
elements
title
lang
"it"
You may find this helpful — it's an article entitled "XPath in Five Paragraphs" by Ronald Bourret.
But in all honesty, //book[title[@lang='it']]
and the above should be equivalent, unless your XPath engine has "issues." So it could be something in the code or sample XML that you're not showing us -- for example, your sample is an XML fragment. Could it be that the root element has a namespace, and you aren't counting for that in your query? And you only told us that it didn't work, but you didn't tell us what results you did get.
Android P+ requires this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
Then:
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:com.example.mypackage"));
startActivity(intent);
to uninstall. Seems easier...
Simple version:
for /F "delims==, tokens=4" %a IN ('ping -n 2 127.0.0.1 ^| findstr /R "^Packets: Sent =.$"') DO (
if %a EQU 2 (
echo Success
) ELSE (
echo FAIL
)
)
But sometimes first ping just fail and second one work (or vice versa) right? So we want to get success when at least one ICMP reply has been returned successfully:
for /F "delims==, tokens=4" %a IN ('ping -n 2 192.168.1.1 ^| findstr /R "^Packets: Sent =.$"') DO (
if %a EQU 2 (
echo Success
) ELSE (
if %a EQU 1 (
echo Success
) ELSE (
echo FAIL
)
)
)
If you want to see all indexes across all databases all at once:
use information_schema;
SELECT * FROM statistics;
Union type is in my mind best option in this case:
interface Employee{
id: number;
name: string;
salary: number | null;
}
// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };
EDIT : For this to work as expected, you should enable the strictNullChecks
in tsconfig
.
WHERE 1 = 0
or similar false conditions work, but I dislike how they look. Marginally cleaner code for Oracle 12c+ IMHO is
CREATE TABLE bar AS
SELECT *
FROM foo
FETCH FIRST 0 ROWS ONLY;
Same limitations apply: only column definitions and their nullability are copied into a new table.
You would do that when the responsibility of creating/updating the referenced column isn't in the current entity, but in another entity.
I know this is kind of old, but I just got something along the same lines to work. Couldn't you do this?
tr.highlight {
border-top: 10px solid;
border-bottom: 10px solid;
border-color: transparent;
}
Hope this helps.
In Ubuntu (at least 12.04) it seems sendmail is not installed by default. You will have to install it using the command
sudo apt-get install sendmail-bin
You may also need to configure the proper permissions for it as mentioned above.
For those using Microsoft products with a web.config file:
Merge this with your web.config.
To allow on any domain replace
value="domain"
withvalue="*"
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.webserver>
<httpprotocol>
<customheaders>
<add name="Access-Control-Allow-Origin" value="domain" />
</customheaders>
</httpprotocol>
</system.webserver>
</configuration>
If you don't have permission to edit web.config, then add this line in your server-side code.
Response.AppendHeader("Access-Control-Allow-Origin", "domain");
if this code does not work even under document ready, most probable you assigned a return false;
somewhere in your js file to that button, if it is button try to change it to a ,span, anchor or div and test if it is working.
$(document).on("click","#test-element",function() {
alert("click bound to document listening for #test-element");
});
put public, protected or private before the $connection.
No need to use date_default_timezone_set
for the whole script, just specify the timezone
you want with a DateTime object:
$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London')); // Another way
echo $now->format("Y-m-d\TH:i:sO"); // something like "2015-02-11T06:16:47+0100" (ISO 8601)
There is no one size fits-all approach, but one thing that I found particularly helpful is setting opacity for a div's direct children, except for the one that you want to keep fully visible. In code:
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
<div class="child4"></div>
</div>
and css:
div.parent > div:not(.child1){
opacity: 0.5;
}
In case you have background colors/images on the parent you fix color opacity with rgba and background-image by applying alpha filters
My preferred way is to have __init__.py on every directory that contains modules that get used by other modules, and in the entry point, override sys.path as below:
def get_path(ss):
return os.path.join(os.path.dirname(__file__), ss)
sys.path += [
get_path('Server'),
get_path('Models')
]
This makes the files in specified directories visible for import, and I can import user from Server.py.
I also got this problem and found quite simple solution. I have Samsung adb driver installed on my system. I tried "Update driver" -> "Let me pick" -> "Already installed drivers" -> Samsung adb driver. That worked well.
Here is what I use
$textToStore = nl2br(htmlentities($inputText, ENT_QUOTES, 'UTF-8'));
$inputText
is the text provided by either the form or textarea.
$textToStore
is the returned text from nl2br
and htmlentities
, to be stored in your database.
ENT_QUOTES
will convert both double and single quotes, so you'll have no trouble with those.
If you're using membership you can do: Membership.GetUser()
Your code is returning the Windows account which is assigned with ASP.NET.
Additional Info Edit: You will want to include System.Web.Security
using System.Web.Security
HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Using pytz
from datetime import datetime
from pytz import timezone
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
timezonelist = ['UTC','US/Pacific','Europe/Berlin']
for zone in timezonelist:
now_time = datetime.now(timezone(zone))
print now_time.strftime(fmt)
You need to concatenate the selector and pseudo selector. You'll also need a style element to contain your styles. Most people use an external stylesheet, for lots of benefits (caching for one).
<a class="hover">click</a>
<style type="text/css">
a.hover:hover {
text-decoration: underline;
}
</style>
Just a note: the hover class is not necessary, unless you are defining only certain links to have this behavior (which may be the case)
Try this:
final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
public void onLongPress(MotionEvent e) {
Log.e("", "Longpress detected");
}
});
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
};
You can put an <a>
element inside the <div>
and set it to display: block
and height: 100%
.
The most popular (==standard?) way of determining the time zone I've seen around is simply asking the users themselves. If your website requires subscription, this could be saved in the users' profile data. For anon users, the dates could be displayed as UTC or GMT or some such.
I'm not trying to be a smart aleck. It's just that sometimes some problems have finer solutions outside of any programming context.
Doing it the mathy way...
nums = [1, 2, 3, 4, 5]
min_combo = (min(nums), max(nums))
Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.
Do you mean that for a select element with an id of "next" you need to perform some specific script?
$("#next").change(function(){
//enter code here
});
You can nest your queries:
select * from (
select bla
from bla
where bla
order by finaldate desc
)
where rownum < 2
Here is what worked for me (Excel 14.0 - aka MS Office Pro Plus 2010):
=DATE(YEAR(A1), MONTH(A1), DAY(A1) - 16)
This takes the date (format mm/dd/yyyy) in cell A1 and subtracts 16 days with output in format of mm/dd/yyyy.
I had the same problem on Windows 7.
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE
The solution turned out to be very simple - right click on command prompt shortcut and choose "Run as Administrator". After that, the problem disappeared)
Just to make this absolutely clear for all:
A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.
This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.
To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.
To qualify the preferred naming conventions:
primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}
I simplified the test a bit - if all(x%y
instead of if not any(not x%y
I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.
pairs = {(x, x+2) for x in primes if x+2 in primes}
Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.
If you have more than one column to be converted you can do the following:
df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)
In Python, the Scipy library can be used to convert the 2-D NumPy matrix into a Sparse matrix. SciPy 2-D sparse matrix package for numeric data is scipy.sparse
The scipy.sparse package provides different Classes to create the following types of Sparse matrices from the 2-dimensional matrix:
CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations.
Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:
import sys # Return the size of an object in bytes
import numpy as np # To create 2 dimentional matrix
from scipy.sparse import csr_matrix, csc_matrix
# csr_matrix: used to create compressed sparse row matrix from Matrix
# csc_matrix: used to create compressed sparse column matrix from Matrix
create a 2-D Numpy matrix
A = np.array([[1, 0, 0, 0, 0, 0],\
[0, 0, 2, 0, 0, 1],\
[0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
print("Memory utilised (bytes): ", sys.getsizeof(A))
print("Type of the object", type(A))
Print the matrix & other details:
Dense matrix representation:
[[1 0 0 0 0 0]
[0 0 2 0 0 1]
[0 0 0 2 0 0]]
Memory utilised (bytes): 184
Type of the object <class 'numpy.ndarray'>
Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:
S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))
The output of print statements:
Sparse 'row' matrix:
(0, 0) 1
(1, 2) 2
(1, 5) 1
(2, 3) 2
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csr.csc_matrix'>
Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:
S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))
The output of print statements:
Sparse 'column' matrix:
(0, 0) 1
(1, 2) 2
(2, 3) 2
(1, 5) 1
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csc.csc_matrix'>
As it can be seen the size of the compressed matrices is 56 bytes and the original matrix size is 184 bytes.
For a more detailed explanation and code examples please refer to this article: https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/
Very simple option in case you have many individual columns to delete in a data table and you want to avoid typing in all column names #careadviced
dt <- dt[, -c(1,4,6,17,83,104)]
This will remove columns based on column number instead.
It's obviously not as efficient because it bypasses data.table advantages but if you're working with less than say 500,000 rows it works fine
When in an iframe on the same origin as the parent, the window.frameElement
method returns the element (e.g. iframe
or object
) in which the window is embedded. Otherwise, if browsing in a top-level context, or if the parent and the child frame have different origins, it will evaluate to null
.
window.frameElement
? 'embedded in iframe or object'
: 'not embedded or cross-origin'
This is an HTML Standard with basic support in all modern browsers.
While doing brew link node In addition I got the following issues as well:
Error: Could not symlink include/node /usr/local/include is not writable.
Linking /usr/local/Cellar/node/9.3.0... Error: Permission denied @ dir_s_mkdir - /usr/local/lib
To solve the above just go to /usr/local/ and check the availability of folders 'include' and 'lib', if those folders are not available just create them manually.
And run brew install node again
It's completely up to you. You can either put them in the header or not, as long as the elements within them are internal navigation elements only (i.e. don't link to external sites such as a twitter or facebook account) then it's fine.
They tend to get placed in a header simply because that's where navigation often goes, but it's not set in stone.
You can read more about it at HTML5 Doctor.
In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click
on android:theme = "@style/AppTheme"
in the Android manifest file. It will open styles.xml
file where you can change the parent attribute of the style tag.
At parent=
in styles.xml
you can browse all available styles by using auto-complete inside the ""
. E.g. try parent="Theme."
with your cursor right after the .
and then pressing Ctrl + Space
.
You can also preview themes in the preview window in Android Studio.
To assign a variable inside block which outside of block always use __block specifier before that variable your code should be like this:-
__block Person *aPerson = nil;
You don't say what system you're using, but as you already have some answers that may or may not work for Windows, I'll answer for POSIX systems.
In POSIX, keyboard input comes through something called a terminal interface, which by default buffers lines of input until Return/Enter is hit, so as to deal properly with backspace. You can change that with the tcsetattr call:
#include <termios.h>
struct termios info;
tcgetattr(0, &info); /* get current terminal attirbutes; 0 is the file descriptor for stdin */
info.c_lflag &= ~ICANON; /* disable canonical mode */
info.c_cc[VMIN] = 1; /* wait until at least one keystroke available */
info.c_cc[VTIME] = 0; /* no timeout */
tcsetattr(0, TCSANOW, &info); /* set immediately */
Now when you read from stdin (with getchar()
, or any other way), it will return characters immediately, without waiting for a Return/Enter. In addition, backspace will no longer 'work' -- instead of erasing the last character, you'll read an actual backspace character in the input.
Also, you'll want to make sure to restore canonical mode before your program exits, or the non-canonical handling may cause odd effects with your shell or whoever invoked your program.
For Spring-boot 1.3.3 the method exchange() for List is working as in the related answer
Another way to avoid the error is to use the cast like this:
let secondValue: string = (<any>someObject)[key];
(Note the parenthesis)
The only problem is that this isn't type-safe anymore, as you are casting to any
. But you can always cast back to the correct type.
ps: I'm using typescript 1.7, not sure about previous versions.
While using Django with postgres 10.6, logging was enabled by default, and I was able to simply do:
tail -f /var/log/postgresql/*
Ubuntu 18.04, django 2+, python3+
In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service
to https://my-service
helped.
Just wanted to clarify that the snippet from accepted answer gives the nearest midnight in the past:
var d = new Date();
d.setHours(0,0,0,0); // last midnight
If you want to get the nearest midnight in future, use the following code:
var d = new Date();
d.setHours(24,0,0,0); // next midnight
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
Take a look at HTMLSelectElement.selectedOptions.
HTML
<select name="north-america" multiple>
<option valud="ca" selected>Canada</a>
<option value="mx" selected>Mexico</a>
<option value="us">USA</a>
</select>
JavaScript
var elem = document.querySelector("select");
console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]
This would also work on non-multiple
<select>
elements
Warning: Support for this selectedOptions
seems pretty unknown at this point
I have this in most Node.JS apps. It also works in the browser.
function log() {
const now = new Date();
const currentDate = `[${now.toISOString()}]: `;
const args = Array.from(arguments);
args.unshift(currentDate);
console.log.apply(console, args);
}
You can see the following code to solved the problem
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
$join->where('kg_shops.active','=', 1);
});
Or another way to solved it
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
$join->on('kg_shops.active','=', DB::raw('1'));
});
vertical-align
is only supposed to work on elements that are rendered as inline
. <span>
is rendered as inline by default, but not all elements are. The paragraph block element, <p>
, is rendered as a block by default. Table render types (e.g. table-cell
) will allow you to use vertical-align as well.
Some browsers may allow you to use the vertical-align
CSS property on items such as the paragraph block, but they are not supposed to. Text denoted as a paragraph should be filled with written-language content or the mark-up is incorrect and should be using one of a number of other options instead.
I hope this helps!
Open the windows cmd. First list all the java processes,
jps -m
now get the name and run below command,
for /f "tokens=1" %i in ('jps -m ^| find "Name_of_the_process"') do ( taskkill /F /PID %i )
or simply kill the process ID
taskkill /F /PID <ProcessID>
sample :)
C:\Users\tk>jps -m
15176 MessagingMain
18072 SoapUI-5.4.0.exe
15164 Jps -m
3420 org.eclipse.equinox.launcher_1.3.201.v20161025-1711.jar -os win32 -ws win32 -arch x86_64 -showsplash -launcher C:\Users\tk\eclipse\jee-neon\eclipse\eclipse.exe -name Eclipse --launcher.library C:\Users\tk\.p2\pool\plugins\org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.401.v20161122-1740\eclipse_1617.dll -startup C:\Users\tk\eclipse\jee-neon\eclipse\\plugins/org.eclipse.equinox.launcher_1.3.201.v20161025-1711.jar --launcher.appendVmargs -exitdata 4b20_d0 -product org.eclipse.epp.package.jee.product -vm C:/Program Files/Java/jre1.8.0_131/bin/javaw.exe -vmargs -Dosgi.requiredJavaVersion=1.8 -XX:+UseG1GC -XX:+UseStringDeduplication -Dosgi.requiredJavaVersion=1.8 -Xms256m -Xmx1024m -Declipse.p2.max.threads=10 -Doomph.update.url=http://download.eclipse.org/oomph/updates/milestone/latest -Doomph.redirection.index.redirection=index:/->http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/ -jar C:\Users\tk\
and
C:\Users\tk>for /f "tokens=1" %i in ('jps -m ^| find "MessagingMain"') do ( taskkill /F /PID %i )
C:\Users\tk>(taskkill /F /PID 15176 )
SUCCESS: The process with PID 15176 has been terminated.
or
C:\Users\tk>taskkill /F /PID 15176
SUCCESS: The process with PID 15176 has been terminated.
If you're on Linux, seriously consider just using the g_file_get_contents function from glib. It handles all the code for loading a file, allocating memory, and handling errors.
Well, I think it would be a bad idea to replicate the code which is already present in classes like SimpleDateFormat
.
On the other hand, personally I'd suggest avoiding Calendar
and Date
entirely if you can, and using Joda Time instead, as a far better designed date and time API. For example, you need to be aware that SimpleDateFormat
is not thread-safe, so you either need thread-locals, synchronization, or a new instance each time you use it. Joda parsers and formatters are thread-safe.
JavaScript is Object-Based, not Object-Oriented. The difference is that Object-Based languages don't support proper inheritance, whereas Object-Oriented ones do.
There is a way to achieve 'normal' inheritance in JavaScript (Reference here), but the basic model is based on prototyping.
For anyone looking for an answer in 2020. This worked for me.
In Views:
class InstancesView(generic.ListView):
model = AlarmInstance
context_object_name = 'settings_context'
queryset = Group.objects.all()
template_name = 'insta_list.html'
@register.filter
def filter_unknown(self, aVal):
result = aVal.filter(is_known=False)
return result
@register.filter
def filter_known(self, aVal):
result = aVal.filter(is_known=True)
return result
In template:
{% for instance in alarm.qar_alarm_instances|filter_unknown:alarm.qar_alarm_instances %}
In pseudocode:
For each in model.child_object|view_filter:filter_arg
Hope that helps.
Formerly, there was two methods of download code in Github: clone or download as zip a .git repo, or upload a file (for example, a binary) for later download.
When download a repo (clone or download as zip), Github doesn't count the number of downloads for technical limitations. Clone a repository is a read-only operation. There is no authentication required. This operation can be done via many protocols, including HTTPS, the same protocol that the web page uses to show the repo in the browser. It's very difficult to count it.
See: http://git-scm.com/book/en/Git-on-the-Server-The-Protocols
Recently, Github deprecate the download functionality. This was because they understand that Github is focused in building software, and not in distribute binaries.
If you are using oracle... STRING
will be created as VARCHAR(255)
column and TEXT
, as a CLOB
.
NATIVE_DATABASE_TYPES = {
primary_key: "NUMBER(38) NOT NULL PRIMARY KEY",
string: { name: "VARCHAR2", limit: 255 },
text: { name: "CLOB" },
ntext: { name: "NCLOB" },
integer: { name: "NUMBER", limit: 38 },
float: { name: "BINARY_FLOAT" },
decimal: { name: "DECIMAL" },
datetime: { name: "TIMESTAMP" },
timestamp: { name: "TIMESTAMP" },
timestamptz: { name: "TIMESTAMP WITH TIME ZONE" },
timestampltz: { name: "TIMESTAMP WITH LOCAL TIME ZONE" },
time: { name: "TIMESTAMP" },
date: { name: "DATE" },
binary: { name: "BLOB" },
boolean: { name: "NUMBER", limit: 1 },
raw: { name: "RAW", limit: 2000 },
bigint: { name: "NUMBER", limit: 19 }
}
If you want to cut the whitespaces before and behind the word, but keep the middle ones.
You could use:
word = ' Hello World '
stripped = word.strip()
print(stripped)
Here is a generic solution using plpgsql:
CREATE OR REPLACE FUNCTION create_role_if_not_exists(rolename NAME) RETURNS TEXT AS
$$
BEGIN
IF NOT EXISTS (SELECT * FROM pg_roles WHERE rolname = rolename) THEN
EXECUTE format('CREATE ROLE %I', rolename);
RETURN 'CREATE ROLE';
ELSE
RETURN format('ROLE ''%I'' ALREADY EXISTS', rolename);
END IF;
END;
$$
LANGUAGE plpgsql;
Usage:
posgres=# SELECT create_role_if_not_exists('ri');
create_role_if_not_exists
---------------------------
CREATE ROLE
(1 row)
posgres=# SELECT create_role_if_not_exists('ri');
create_role_if_not_exists
---------------------------
ROLE 'ri' ALREADY EXISTS
(1 row)
In case fragments should have custom view of ToolBar you can implement ToolBar for each fragment separately.
add ToolBar into fragment_layout:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"/>
find it in fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
//set toolbar appearance
toolbar.setBackground(R.color.material_blue_grey_800);
//for crate home button
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
menu listener could be created two ways: override onOptionsItemSelected in your fragment:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
getActivity().onBackPressed();
}
return super.onOptionsItemSelected(item);
}
or set listener for toolbar when create it in onCreateView():
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
return false;
}
});
It seems things were designed to avoid developers to se the root user, a better solution would be:
sudo mysql -u root
Then create a normal user, set a password, then use that user to work.
create user 'user'@'localhost' identified by 'user1234';
grant all on your_database.* to 'user'@'localhost';
select host, user from mysql.user;
Then try to access:
mysql -u user -p
Boom!
On old paper-printer terminals, advancing to the next line involved two actions: moving the print head back to the beginning of the horizontal scan range (carriage return) and advancing the roll of paper being printed on (line feed).
Since we no longer use paper-printer terminals, those actions aren't really relevant anymore, but the characters used to signal them have stuck around in various incarnations.
I got the same error in ReactJS function component, using ReactJS useState hook. The solution was to declare the type of useState at initialisation:
const [items , setItems] = useState<IItem[]>([]); // replace IItem[] with your own typing: string, boolean...
Understanding the language syntax is important when considering clarity of code. Consider copying a character string, for example with post-increment:
char a[256] = "Hello world!";
char b[256];
int i = 0;
do {
b[i] = a[i];
} while (a[i++]);
We want the loop to execute through encountering the zero character (which tests false) at the end of the string. That requires testing the value pre-increment and also incrementing the index. But not necessarily in that order - a way to code this with the pre-increment would be:
int i = -1;
do {
++i;
b[i] = a[i];
} while (a[i]);
It is a matter of taste which is clearer and if the machine has a handfull of registers both should have identical execution time, even if a[i] is a function that is expensive or has side-effects. A significant difference might be the exit value of the index.
Well, you can always use PHP's system function call.
http://php.net/manual/en/function.system.php
http://www.php.net/manual/en/function.exec.php
That runs any command-line program from PHP.
Jefferson is right, you have to do it backwards.
Here's the c# equivalent:
for (var i == list.Items.Count - 1; i >= 0; i--)
{
list.Items.RemoveAt(i);
}
Try this.
This works even for tables with constraints (foreign key relationships). Alternatively you can just drop the database and recreate, but you may not have the necessary permissions to do that.
mysqldump -u[USERNAME] -p[PASSWORD] \
--add-drop-table --no-data [DATABASE] | \
grep -e '^DROP \| FOREIGN_KEY_CHECKS' | \
mysql -u[USERNAME] -p[PASSWORD] [DATABASE]
In order to overcome foreign key check effects, add show table
at the end of the generated script and run many times until the show table
command results in an empty set.
I found out another solution for this case without using Reactivex neither services. I actually love the rxjx API however I think it goes best when resolving an async and/or complex function. Using It in that way, Its pretty exceeded to me.
What I think you are looking for is for a broadcast. Just that. And I found out this solution:
<app>
<app-nav (selectedTab)="onSelectedTab($event)"></app-nav>
// This component bellow wants to know when a tab is selected
// broadcast here is a property of app component
<app-interested [broadcast]="broadcast"></app-interested>
</app>
@Component class App {
broadcast: EventEmitter<tab>;
constructor() {
this.broadcast = new EventEmitter<tab>();
}
onSelectedTab(tab) {
this.broadcast.emit(tab)
}
}
@Component class AppInterestedComponent implements OnInit {
broadcast: EventEmitter<Tab>();
doSomethingWhenTab(tab){
...
}
ngOnInit() {
this.broadcast.subscribe((tab) => this.doSomethingWhenTab(tab))
}
}
This is a full working example: https://plnkr.co/edit/xGVuFBOpk2GP0pRBImsE
Memcached is multithreaded and fast.
Redis has lots of features and is very fast, but completely limited to one core as it is based on an event loop.
We use both. Memcached is used for caching objects, primarily reducing read load on the databases. Redis is used for things like sorted sets which are handy for rolling up time-series data.
'Create a class to hold the pair...
Public Class ColumnValue
Public ColumnName As String
Public ColumnValue As New Object
End Class
'Build the pair...
For Each row In [YourDataTable].Rows
For Each item As DataColumn In row.Table.Columns
Dim rowValue As New ColumnValue
rowValue.ColumnName = item.Caption
rowValue.ColumnValue = row.item(item.Ordinal)
RowValues.Add(rowValue)
rowValue = Nothing
Next
' Now you can grab the value by the column name...
Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select p.ColumnValue).FirstOrDefault
Next
This implementation wrap entity exception to exception with detail text.
It handles DbEntityValidationException
, DbUpdateException
, datetime2
range errors (MS SQL), and include key of invalid entity in message (useful when savind many entities at one SaveChanges
call).
First, override SaveChanges
in DbContext class:
public class AppDbContext : DbContext
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException dbEntityValidationException)
{
throw ExceptionHelper.CreateFromEntityValidation(dbEntityValidationException);
}
catch (DbUpdateException dbUpdateException)
{
throw ExceptionHelper.CreateFromDbUpdateException(dbUpdateException);
}
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
try
{
return await base.SaveChangesAsync(cancellationToken);
}
catch (DbEntityValidationException dbEntityValidationException)
{
throw ExceptionHelper.CreateFromEntityValidation(dbEntityValidationException);
}
catch (DbUpdateException dbUpdateException)
{
throw ExceptionHelper.CreateFromDbUpdateException(dbUpdateException);
}
}
ExceptionHelper class:
public class ExceptionHelper
{
public static Exception CreateFromEntityValidation(DbEntityValidationException ex)
{
return new Exception(GetDbEntityValidationMessage(ex), ex);
}
public static string GetDbEntityValidationMessage(DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
return exceptionMessage;
}
public static IEnumerable<Exception> GetInners(Exception ex)
{
for (Exception e = ex; e != null; e = e.InnerException)
yield return e;
}
public static Exception CreateFromDbUpdateException(DbUpdateException dbUpdateException)
{
var inner = GetInners(dbUpdateException).Last();
string message = "";
int i = 1;
foreach (var entry in dbUpdateException.Entries)
{
var entry1 = entry;
var obj = entry1.CurrentValues.ToObject();
var type = obj.GetType();
var propertyNames = entry1.CurrentValues.PropertyNames.Where(x => inner.Message.Contains(x)).ToList();
// check MS SQL datetime2 error
if (inner.Message.Contains("datetime2"))
{
var propertyNames2 = from x in type.GetProperties()
where x.PropertyType == typeof(DateTime) ||
x.PropertyType == typeof(DateTime?)
select x.Name;
propertyNames.AddRange(propertyNames2);
}
message += "Entry " + i++ + " " + type.Name + ": " + string.Join("; ", propertyNames.Select(x =>
string.Format("'{0}' = '{1}'", x, entry1.CurrentValues[x])));
}
return new Exception(message, dbUpdateException);
}
}
Some worthwhile subtleties...
\33[2K
erases the entire line your cursor is currently on
\033[A
moves your cursor up one line, but in the same column i.e. not to the start of the line
\r
brings your cursor to the beginning of the line (r is for carriage return N.B. carriage returns do not include a newline so cursor remains on the same line) but does not erase anything
In xterm specifically, I tried the replies mentioned above and the only way I found to erase the line and start again at the beginning is the sequence (from the comment above posted by @Stephan202 as well as @vlp and @mantal) \33[2K\r
On an implementation note, to get it to work properly for example in a countdown scenario since I wasn't using a new line character '\n'
at the end of each fprintf()
, so I had to fflush()
the stream each time (to give you some context, I started xterm using a fork on a linux machine without redirecting stdout, I was just writing to the buffered FILE pointer fdfile
with a non-blocking file descriptor I had sitting on the pseudo terminal address which in my case was /dev/pts/21
):
fprintf(fdfile, "\33[2K\rT minus %d seconds...", i);
fflush(fdfile);
Note that I used both the \33[2K sequence to erase the line followed by the \r
carriage return sequence to reposition the cursor at the beginning of the line. I had to fflush()
after each fprintf()
because I don't have a new line character at the end '\n'
. The same result without needing fflush() would require the additional sequence to go up a line:
fprintf(fdfile, "\033[A\33[2K\rT minus %d seconds...\n", i);
Note that if you have something on the line immediately above the line you want to write on, it will get over-written with the first fprintf(). You would have to leave an extra line above to allow for the first movement up one line:
i = 3;
fprintf(fdfile, "\nText to keep\n");
fprintf(fdfile, "Text to erase****************************\n");
while(i > 0) { // 3 second countdown
fprintf(fdfile, "\033[A\33[2KT\rT minus %d seconds...\n", i);
i--;
sleep(1);
}
Strictly stated you must check all of the following: defined, not empty AND not None.
For "normal" variables it makes a difference if defined and set or not set. See foo
and bar
in the example below. Both are defined but only foo
is set.
On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz
and xyz.msg
in the example below:
cat > test.yml <<EOF
- hosts: 127.0.0.1
vars:
foo: "" # foo is defined and foo == '' and foo != None
bar: # bar is defined and bar != '' and bar == None
tasks:
- debug:
msg : ""
register: xyz # xyz is defined and xyz != '' and xyz != None
# xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "foo is defined and foo == '' and foo != None"
when: foo is defined and foo == '' and foo != None
- debug:
msg: "bar is defined and bar != '' and bar == None"
when: bar is defined and bar != '' and bar == None
- debug:
msg: "xyz is defined and xyz != '' and xyz != None"
when: xyz is defined and xyz != '' and xyz != None
- debug:
msg: "{{ xyz }}"
- debug:
msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml
PostgreSQL 13 supports natively gen_random_uuid ():
PostgreSQL includes one function to generate a UUID:
gen_random_uuid () ? uuid
This function returns a version 4 (random) UUID. This is the most commonly used type of UUID and is appropriate for most applications.
encodeURIComponent()
Converts the input into a URL-encoded string
encodeURI()
URL-encodes the input, but assumes a full URL is given, so returns a valid URL by not encoding the protocol (e.g. http://) and host name (e.g. www.stackoverflow.com).
decodeURIComponent()
and decodeURI()
are the opposite of the above
Simple workaround:
Just create a invisible element with tabindex=1 ... This will not focus the datepicker ...
eg.:
<a href="" tabindex="1"></a>
...
Here comes the input element
The <TouchableHighlight>
element is the source of the error. The <TouchableHighlight>
element must have a child element.
Try running the code like this:
render() {
const {height, width} = Dimensions.get('window');
return (
<View style={styles.container}>
<Image
style={{
height:height,
width:width,
}}
source={require('image!foo')}
resizeMode='cover'
/>
<TouchableHighlight style={styles.button}>
<Text> This text is the target to be highlighted </Text>
</TouchableHighlight>
</View>
);
}
In Dart 2 int.tryParse is available.
It returns null for invalid inputs instead of throwing. You can use it like this:
int val = int.tryParse(text) ?? defaultValue;
Use Date convert to compare with date: Try This:
select * from table
where TO_DATE(to_char(timespanColumn,'YYYY-MM-DD'),'YYYY-MM-DD') = to_timestamp('2018-03-26', 'YYYY-MM-DD')
I tried many ways mentioned here, especially the preference - editor - general - code completion - show documentation popup in.. isn't working in version 2019.2.2
Finally, i am just using F1
while caret is on the type/method and it displays the documentation nicely. This is not ideal but helpful.
If you are using PHP 5.3, it is because you need to set the default time zone:
date_default_timezone_set()
The problem is that your anonymous object property data-icon
has an invalid name. C# properties cannot have dashes in their names. There are two ways you can get around that:
Use an underscore instead of dash (MVC will automatically replace the underscore with a dash in the emitted HTML):
@Html.ActionLink("Edit", "edit", "markets",
new { id = 1 },
new {@class="ui-btn-right", data_icon="gear"})
Use the overload that takes in a dictionary:
@Html.ActionLink("Edit", "edit", "markets",
new { id = 1 },
new Dictionary<string, object> { { "class", "ui-btn-right" }, { "data-icon", "gear" } });
Following up on Sergey's suggestion, you can define and reuse a whole Style (with various property setters, including Margin) instead of just a Thickness object:
<Style x:Key="MyStyle" TargetType="SomeItemType">
<Setter Property="Margin" Value="0,5,0,5" />
...
</Style>
...
<StackPanel>
<StackPanel.Resources>
<Style TargetType="SomeItemType" BasedOn="{StaticResource MyStyle}" />
</StackPanel.Resources>
...
</StackPanel>
Note that the trick here is the use of Style Inheritance for the implicit style, inheriting from the style in some outer (probably merged from external XAML file) resource dictionary.
Sidenote:
At first, I naively tried to use the implicit style to set the Style property of the control to that outer Style resource (say defined with the key "MyStyle"):
<StackPanel>
<StackPanel.Resources>
<Style TargetType="SomeItemType">
<Setter Property="Style" Value={StaticResource MyStyle}" />
</Style>
</StackPanel.Resources>
</StackPanel>
which caused Visual Studio 2010 to shut down immediately with CATASTROPHIC FAILURE error (HRESULT: 0x8000FFFF (E_UNEXPECTED)), as described at https://connect.microsoft.com/VisualStudio/feedback/details/753211/xaml-editor-window-fails-with-catastrophic-failure-when-a-style-tries-to-set-style-property#
"Should I clone the list first?"
That will be the easiest solution, remove from the clone, and copy the clone back after removal.
An example from my rummikub game:
SuppressWarnings("unchecked")
public void removeStones() {
ArrayList<Stone> clone = (ArrayList<Stone>) stones.clone();
// remove the stones moved to the table
for (Stone stone : stones) {
if (stone.isOnTable()) {
clone.remove(stone);
}
}
stones = (ArrayList<Stone>) clone.clone();
sortStones();
}
If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:
import csv
csv.register_dialect('skip_space', skipinitialspace=True)
with open(my_file, 'r') as f:
reader=csv.reader(f , delimiter=' ', dialect='skip_space')
for item in reader:
print(item)
Manage Jenkins/ configure system /GitHub Servers
On jenkins job / git credentials and Branch Specifier (give the branch you want to look for pushes)
With the following code:
$flag = true;
foreach($find_letters as $letter)
if(false===strpos($string, $letter)) {
$flag = false;
break;
}
Then check the value of $flag
. If it is true
, all letters have been found. If not, it's false
.
Try this:
$(document).ready(function(){
var yourArray = [];
$("span.HOEnZb").find("div").each(function(){
if(($.trim($(this).text()).length>0)){
yourArray.push($(this).text());
}
});
});
As mentioned in other answers, you can use set
to list all the environment variables or use
set [environment_variable]
to get a specific variable with its value.
set [environment_variable]=
can be used to remove a variable from the workspace.
use debugbar package
composer require "barryvdh/laravel-debugbar": "2.3.*"
As written, your function accepts only two ranges as arguments.
To allow for a variable number of ranges to be used in the function, you need to declare a ParamArray variant array in your argument list. Then, you can process each of the ranges in the array in turn.
For example,
Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
Dim elem As Variant
Dim i As Long
For Each elem In Arg1
myAdd = myAdd + elem.Value
Next elem
For i = LBound(Args2) To UBound(Args2)
For Each elem In Args2(i)
myAdd = myAdd + elem.Value
Next elem
Next i
End Function
This function could then be used in the worksheet to add multiple ranges.
For your function, there is the question of which of the ranges (or cells) that can passed to the function are 'Sessions' and which are 'Customers'.
The easiest case to deal with would be if you decided that the first range is Sessions and any subsequent ranges are Customers.
Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
'This function accepts a single Sessions range and one or more Customers
'ranges
Dim i As Long
Dim sessElem As Variant
Dim custElem As Variant
For Each sessElem In Sessions
'do something with sessElem.Value, the value of each
'cell in the single range Sessions
Debug.Print "sessElem: " & sessElem.Value
Next sessElem
'loop through each of the one or more ranges in Customers()
For i = LBound(Customers) To UBound(Customers)
'loop through the cells in the range Customers(i)
For Each custElem In Customers(i)
'do something with custElem.Value, the value of
'each cell in the range Customers(i)
Debug.Print "custElem: " & custElem.Value
Next custElem
Next i
End Function
If you want to include any number of Sessions ranges and any number of Customers range, then you will have to include an argument that will tell the function so that it can separate the Sessions ranges from the Customers range.
This argument could be set up as the first, numeric, argument to the function that would identify how many of the following arguments are Sessions ranges, with the remaining arguments implicitly being Customers ranges. The function's signature would then be:
Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)
Or it could be a "guard" argument that separates the Sessions ranges from the Customers ranges. Then, your code would have to test each argument to see if it was the guard. The function would look like:
Function calculateIt(ParamArray Args() As Variant)
Perhaps with a call something like:
calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)
The program logic might then be along the lines of:
Function calculateIt(ParamArray Args() As Variant) As Double
...
'loop through Args
IsSessionArg = True
For i = lbound(Args) to UBound(Args)
'only need to check for the type of the argument
If TypeName(Args(i)) = "String" Then
IsSessionArg = False
ElseIf IsSessionArg Then
'process Args(i) as Session range
Else
'process Args(i) as Customer range
End if
Next i
calculateIt = <somevalue>
End Function
Those are unicode escapes. The general unicode escapes looks like \uxxxx
where xxxx
are the hexadecimal digits of the ASCI characters. They are used mainly to insert special characters inside a javascript string.
Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Add
Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
AddDays
Returns a new DateTime that adds the specified number of days to the value of this instance.
AddHours
Returns a new DateTime that adds the specified number of hours to the value of this instance.
AddMilliseconds
Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
AddMinutes
Returns a new DateTime that adds the specified number of minutes to the value of this instance.
AddMonths
Returns a new DateTime that adds the specified number of months to the value of this instance.
AddSeconds
Returns a new DateTime that adds the specified number of seconds to the value of this instance.
AddTicks
Returns a new DateTime that adds the specified number of ticks to the value of this instance.
AddYears
Returns a new DateTime that adds the specified number of years to the value of this instance.
What are the situations where "yield from" is useful?
Every situation where you have a loop like this:
for x in subgenerator:
yield x
As the PEP describes, this is a rather naive attempt at using the subgenerator, it's missing several aspects, especially the proper handling of the .throw()
/.send()
/.close()
mechanisms introduced by PEP 342. To do this properly, rather complicated code is necessary.
What is the classic use case?
Consider that you want to extract information from a recursive data structure. Let's say we want to get all leaf nodes in a tree:
def traverse_tree(node):
if not node.children:
yield node
for child in node.children:
yield from traverse_tree(child)
Even more important is the fact that until the yield from
, there was no simple method of refactoring the generator code. Suppose you have a (senseless) generator like this:
def get_list_values(lst):
for item in lst:
yield int(item)
for item in lst:
yield str(item)
for item in lst:
yield float(item)
Now you decide to factor out these loops into separate generators. Without yield from
, this is ugly, up to the point where you will think twice whether you actually want to do it. With yield from
, it's actually nice to look at:
def get_list_values(lst):
for sub in [get_list_values_as_int,
get_list_values_as_str,
get_list_values_as_float]:
yield from sub(lst)
Why is it compared to micro-threads?
I think what this section in the PEP is talking about is that every generator does have its own isolated execution context. Together with the fact that execution is switched between the generator-iterator and the caller using yield
and __next__()
, respectively, this is similar to threads, where the operating system switches the executing thread from time to time, along with the execution context (stack, registers, ...).
The effect of this is also comparable: Both the generator-iterator and the caller progress in their execution state at the same time, their executions are interleaved. For example, if the generator does some kind of computation and the caller prints out the results, you'll see the results as soon as they're available. This is a form of concurrency.
That analogy isn't anything specific to yield from
, though - it's rather a general property of generators in Python.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
have a look at the rtrim function
rtrim ($string , ",");
the above line will remove a char if the last char is a comma
This is a simple solution where you clone the lists options and keep them in an object for recovery later. The scripts cleans out the list and add only the options that contains the input text. This should also work cross browser. I got some help from this post: https://stackoverflow.com/a/5748709/542141
Html
<input id="search_input" placeholder="Type to filter">
<select id="theList" class="List" multiple="multiple">
or razor
@Html.ListBoxFor(g => g.SelectedItem, Model.items, new { @class = "List", @id = "theList" })
script
<script type="text/javascript">
$(document).ready(function () {
//copy options
var options = $('#theList option').clone();
//react on keyup in textbox
$('#search_input').keyup(function () {
var val = $(this).val();
$('#theList').empty();
//take only the options containing your filter text or all if empty
options.filter(function (idx, el) {
return val === '' || $(el).text().indexOf(val) >= 0;
}).appendTo('#theList');//add it to list
});
});
</script>
You can achieve this with DateTime
extension, which will also work for number of minutes that is larger than one day (>= 1440
):
$minutes = 250;
$zero = new DateTime('@0');
$offset = new DateTime('@' . $minutes * 60);
$diff = $zero->diff($offset);
echo $diff->format('%a Days, %h Hours, %i Minutes');
Building off of Vaali's solution:
def sparse_cosine_similarity(sparse_matrix):
out = (sparse_matrix.copy() if type(sparse_matrix) is csr_matrix else
sparse_matrix.tocsr())
squared = out.multiply(out)
sqrt_sum_squared_rows = np.array(np.sqrt(squared.sum(axis=1)))[:, 0]
row_indices, col_indices = out.nonzero()
out.data /= sqrt_sum_squared_rows[row_indices]
return out.dot(out.T)
This takes a sparse matrix (preferably a csr_matrix) and returns a csr_matrix. It should do the more intensive parts using sparse calculations with pretty minimal memory overhead. I haven't tested it extensively though, so caveat emptor (Update: I feel confident in this solution now that I've tested and benchmarked it)
Also, here is the sparse version of Waylon's solution in case it helps anyone, not sure which solution is actually better.
def sparse_cosine_similarity_b(sparse_matrix):
input_csr_matrix = sparse_matrix.tocsr()
similarity = input_csr_matrix * input_csr_matrix.T
square_mag = similarity.diagonal()
inv_square_mag = 1 / square_mag
inv_square_mag[np.isinf(inv_square_mag)] = 0
inv_mag = np.sqrt(inv_square_mag)
return similarity.multiply(inv_mag).T.multiply(inv_mag)
Both solutions seem to have parity with sklearn.metrics.pairwise.cosine_similarity
:-D
Update:
Now I have tested both solutions against my existing Cython implementation: https://github.com/davidmashburn/sparse_dot/blob/master/test/benchmarks_v3_output_table.txt and it looks like the first algorithm performs the best of the three most of the time.
Use getElementById()
if it's available.
Also, here's an easy way to do it with jQuery:
if ($('#elementId').length > 0) {
// Exists.
}
And if you can't use third-party libraries, just stick to base JavaScript:
var element = document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// Exists.
}
The difference is in the subsystem that each executable targets.
java.exe
targets the CONSOLE
subsystem.javaw.exe
targets the WINDOWS
subsystem.There is always a reason why the nested method roll back. If you don't see the reason, you need to change your logger level to debug, where you will see the more details where transaction failed. I changed my logback.xml by adding
<logger name="org.springframework.transaction" level="debug"/>
<logger name="org.springframework.orm.jpa" level="debug"/>
then I got this line in the log:
Participating transaction failed - marking existing transaction as rollback-only
So I just stepped through my code to see where this line is generated and found that there is a catch block which did not throw anything.
private Student add(Student s) {
try {
Student retval = studentRepository.save(s);
return retval;
} catch (Exception e) {
}
return null;
}
add_index :table_name, :column_name, unique: true
To index multiple columns together, you pass an array of column names instead of a single column name.
Well, there are more OS's than Unix and Windows (Portable devices, etc), and Java is known for its portability. The best practice is to use it, so the JVM could determine which one is the best for that OS.
netcat
(nc.exe
) is the right tool. I have a feeling that any tool that does what you want it to do will have exactly the same problem with your antivirus software. Just flag this program as "OK" in your antivirus software (how you do this will depend on what type of antivirus software you use).
Of course you will also need to configure your sysadmin to accept that you're not trying to do anything illegal...
If you want a list of columns of a certain type, you can use groupby
:
>>> df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>> df
A B C D E
0 1 2.3456 c d 78
[1 rows x 5 columns]
>>> df.dtypes
A int64
B float64
C object
D object
E int64
dtype: object
>>> g = df.columns.to_series().groupby(df.dtypes).groups
>>> g
{dtype('int64'): ['A', 'E'], dtype('float64'): ['B'], dtype('O'): ['C', 'D']}
>>> {k.name: v for k, v in g.items()}
{'object': ['C', 'D'], 'int64': ['A', 'E'], 'float64': ['B']}
My preferred way is canvas.toBlob()
But anyhow here is yet another way to convert base64 to a blob using fetch ^^,
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="_x000D_
_x000D_
fetch(url)_x000D_
.then(res => res.blob())_x000D_
.then(blob => {_x000D_
var fd = new FormData()_x000D_
fd.append('image', blob, 'filename')_x000D_
_x000D_
console.log(blob)_x000D_
_x000D_
// Upload_x000D_
// fetch('upload', {method: 'POST', body: fd})_x000D_
})
_x000D_
Add another option, maybe not the most lightweight.
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
_x000D_
Try putting it in quotes:
find . -name '*test.c'
keep you Project(not app) Build.gradle dependncies classpath version code is new
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0-beta01'
classpath 'com.novoda:bintray-release:0.8.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
Your question is already answered here :
Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file
Also, a good link on what happens if we try to include our class file in rt.jar.
In Visual Studio 2005 Pro:
Ctrl + E, Ctrl + W
Or menu Edit ? Advanced ? Word Wrap.
Try this as root (maybe you can use sudo
or su
):
/etc/init.d/postgresql restart
Without any argument the script also gives you a hint on how to restart a specific version
[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]
Similarly, in case you have it, you can also use the service
tool:
[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]
Please, pay attention to the optional [version ...]
trailing argument.
That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.
Finally, in case you are running systemd, then you can use systemctl
like this:
[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...
You can replace status
with stop
, start
or restart
as well as other actions. Please refer to the documentation for full details.
In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12
and reload v13
you can run:
systemctl stop postgresql-12.service
systemctl reload postgresql-13.service
Thanks to @Jojo for pointing me to this very one.
Finally Keep in mind that root
permissions may be needed for non-informative tasks as in the other cases seen earlier.
I faced the same problem and below is the workaround I came up with:
public boolean checkForPermission(final String[] permissions, final int permRequestCode, int msgResourceId) {
final List<String> permissionsNeeded = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
final String perm = permissions[i];
if (ContextCompat.checkSelfPermission(getActivity(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(permissions[i])) {
final AlertDialog dialog = AlertDialog.newInstance( getResources().getString(R.string.permission_title), getResources().getString(msgResourceId) );
dialog.setPositiveButton("OK", new View.OnClickListener() {
@Override
public void onClick(View view) {
// add the request.
permissionsNeeded.add(perm);
dialog.dismiss();
}
});
dialog.show( getActivity().getSupportFragmentManager(), "HCFAlertDialog" );
} else {
// add the request.
permissionsNeeded.add(perm);
}
}
}
if (permissionsNeeded.size() > 0) {
// go ahead and request permissions
requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
return false;
} else {
// no permission need to be asked so all good...we have them all.
return true;
}
}
And you call the above method like this:
if ( checkForPermission( new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA}, REQUEST_PERMISSION_EXTERNAL_STORAGE_RESULT, R.string.permission_image) ) {
// DO YOUR STUFF
}
div height=100% in table cell will work only when table has height attribute itself.
<table border="1" style="height:300px; width: 100px;">
<tr><td>cell1</td><td>cell2</td></tr>
<tr>
<td style="height: 100%">
<div style="height: 100%; width: 100%; background-color:pink;"></div>
</td>
<td>long text long text long text long text long text long text</td>
</tr>
</table>
_x000D_
UPD in FireFox you should also set height=100%
value to the parent TD
element
This is an article about your problem. Adding a thousands-seperator is not built in to JavaScript, so you'll have to write your own function like this (example taken from the linked page):
function addSeperator(nStr){
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Just use DateValue(Now)
if you want the result to be of DateTime
data type.
I would use something like (with Scala [the code in old "good" Java 8 may be similar to this]):
object SeleniumFacade {
def getElement(bySelector: By, maybeParent: Option[WebElement] = None, withIndex: Int = 0)(implicit driver: RemoteWebDriver): Option[WebElement] = {
val elements = maybeParent match {
case Some(parent) => parent.findElements(bySelector).asScala
case None => driver.findElements(bySelector).asScala
}
if (elements.nonEmpty) {
Try { Some(elements(withIndex)) } getOrElse None
} else None
}
...
}
so then,
val maybeHeaderLink = SeleniumFacade getElement(By.xpath(".//a"), Some(someParentElement))
You can use a resource key like this:
<UserControl.Resources>
<SolidColorBrush x:Key="{x:Static local:Foo.MyKey}">Blue</SolidColorBrush>
</UserControl.Resources>
<Grid Background="{StaticResource {x:Static local:Foo.MyKey}}" />
public partial class Foo : UserControl
{
public Foo()
{
InitializeComponent();
var brush = (SolidColorBrush)FindResource(MyKey);
}
public static ResourceKey MyKey { get; } = CreateResourceKey();
private static ComponentResourceKey CreateResourceKey([CallerMemberName] string caller = null)
{
return new ComponentResourceKey(typeof(Foo), caller); ;
}
}
First of all, that is the resolution you would want to use, 1650,1080
.
Now add:
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
If you have issues with the components on the JFrame, then after you have added all the components using the frame.add(component)
method, add the following statement.
frame.pack();
Starting with AspNetCore 2.0, it's recommended to use ContentResult
instead of the Produce
attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885
This doesn't rely on serialization nor on content negotiation.
[HttpGet]
public ContentResult Index() {
return new ContentResult {
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
Content = "<html><body>Hello World</body></html>"
};
}
For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.
However, if you attempt to do the above using a dispatch_sync()
and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:
. As I mention there, I created a helper function:
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:
runOnMainQueueWithoutDeadlocking(^{
//Do stuff
});
Go to:
Settings -> Preferences You will see a dialog box. There click the Auto-completion tab where you can set the auto complete option.See image below:
If your code not detected automatically then you choose your coding language form Language menu
This example demonstrates the difference between the mousemove, mouseenter and mouseover events:
https://jsfiddle.net/z8g613yd/
HTML:
<div onmousemove="myMoveFunction()">
<p>onmousemove: <br> <span id="demo">Mouse over me!</span></p>
</div>
<div onmouseenter="myEnterFunction()">
<p>onmouseenter: <br> <span id="demo2">Mouse over me!</span></p>
</div>
<div onmouseover="myOverFunction()">
<p>onmouseover: <br> <span id="demo3">Mouse over me!</span></p>
</div>
CSS:
div {
width: 200px;
height: 100px;
border: 1px solid black;
margin: 10px;
float: left;
padding: 30px;
text-align: center;
background-color: lightgray;
}
p {
background-color: white;
height: 50px;
}
p span {
background-color: #86fcd4;
padding: 0 20px;
}
JS:
var x = 0;
var y = 0;
var z = 0;
function myMoveFunction() {
document.getElementById("demo").innerHTML = z += 1;
}
function myEnterFunction() {
document.getElementById("demo2").innerHTML = x += 1;
}
function myOverFunction() {
document.getElementById("demo3").innerHTML = y += 1;
}
onmousemove
: occurs every time the mouse pointer is moved over the div element.onmouseenter
: only occurs when the mouse pointer enters the div element.onmouseover
: occurs when the mouse pointer enters the div element,
and its child elements (p and span).I was also developing a similar application. I was also getting not found error even though the file was there. This solve my problem. I mention my download folder in 'static_folder':
app = Flask(__name__,static_folder='pdf')
My code for the download is as follows:
@app.route('/pdf/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory='pdf', filename=filename)
This is how I am calling my file from html.
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.pdf target="_blank" style="margin-right: 5px;">Download pdf </a>
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.png target="_blank" style="margin-right: 5px;">Download png </a>
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
I had the same problem when trying to load Hadoop project in eclipse. I tried the solutions above, and I believe it might have worked in Eclipse Kepler... not even sure anymore (tried too many things).
With all the problems I was having, I decided to move on to Eclipse Luna, and the solutions above did not work for me.
There was another post that recommended changing the ... tag to package. I started doing that, and it would "clear" the errors... However, I start to think that the changes would bite me later - I am not an expert on Maven.
Fortunately, I found out how to remove all the errors. Go to Window->Preferences->Maven-> Error/Warnings and change "Plugin execution not covered by lifecycle..." option to "Ignore". Hope it helps.