Another cause might be the fact that you're pointing to the wrong port.
Make sure you are actually pointing to the right SQL server. You may have a default installation of MySQL running on 3306 but you may actually be needing a different MySQL instance.
Check the ports and run some query against the db.
Step 1:
cd /etc/postgresql/12/main/
open file named postgresql.conf
sudo nano postgresql.conf
add this line to that file
listen_addresses = '*'
then open file named pg_hba.conf
sudo nano pg_hba.conf
and add this line to that file
host all all 0.0.0.0/0 md5
It allows access to all databases for all users with an encrypted password
restart your server
sudo /etc/init.d/postgresql restart
Here's my solution if you know the aspect ratio, which you can either get from the image metadata or prior knowledge. This fills the whole width of the screen, but that, of course, can be adjusted.
function imageStyle(aspect)
{
//Include any other style requirements in your returned object.
return {alignSelf: "stretch", aspectRatio: aspect, resizeMode: 'stretch'}
}
This looks a bit nicer than contain
, and takes less finessing with sizes, and it will adjust the height to maintain the proper aspect ratio so your images don't look skewed. Using contain will preserve the aspect ratio but will scale it to fit your other style requirements, which may drastically shrink the image.
"Allocation Failure" is a cause of GC cycle to kick in.
"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.
Older JVM were not printing GC cause for minor GC cycles.
"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark
is enabled).
I have the error of system.typeintialzationException, which is due to when I tried to move the file like:
File.Move(DestinationFilePath, SourceFilePath)
That error was due to I had swapped the path actually, correct one is:
File.Move(SourceFilePath, DestinationFilePath)
Try to wrap wsdlLocation in wsdlUrls
<wsdlUrls>
<wsdlLocation>http://url</wsdlLocation>
</wsdlUrls>
SIMPLE..
First check with the closing tag of project. It should be placed after all the dependency tags are closed.This way I solved my error. --Sush happy coding :)
Take a look at the JavaDoc for RestTemplate.
There is the corresponding getForObject
methods that are the HTTP GET equivalents of postForObject
, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.
Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange
methods allow you to provide an HttpEntity
object representing the details of the request (including headers). The execute
methods allow you to specify a RequestCallback
from which you can add the headers upon its invocation.
Tomcat usually does not add classes in src/test/java
to the classpath. They are missing if you run tomcat in scope test. To order tomcat to respect classes in test, use -Dmaven.tomcat.useTestClasspath=true
or add
<properties>
<maven.tomcat.useTestClasspath>true</maven.tomcat.useTestClasspath>
</properties>
To your pom.xml
.
Just use only required dependency, not all :))). For me, for normal work of logging process you need this dependency exclude others from pom.xml
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.8</version>
</dependency>
Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.
Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.
The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error
Today, I would recommend using Task.CompletedTask to accomplish this.
Pre .net 4.6:
Using Task.FromResult(0)
or Task.FromResult<object>(null)
will incur less overhead than creating a Task
with a no-op expression. When creating a Task
with a result pre-determined, there is no scheduling overhead involved.
Remove
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
slf4j-log4j12
is the log4j binding for slf4j
you dont need to add another log4j dependency.
Added
Provide the log4j configuration in log4j.properties
and add it to your class path. There are sample configurations here
or you can change your binding to
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
</dependency>
if you are configuring slf4j due to some dependencies requiring it.
You haven't specify version in your maven dependency file may be thats why it is not picking the latest jar
As well as you need another deppendency with slf4j-log4j12
artifact id.
Include this in your pom file
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
Let me know if error is still not resolved
I also recomend you to see this link
An other solution rm(list=ls(pattern="temp"))
, remove all objects matching the pattern.
Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.
often this is due to missing permissions. The windows account the local IIS Application Pool is running with may not have the permission to write to the applications directory. You could create a directory somewhere, give everyone permission to write in it and point your log4net config to that directory. If then a log file is created there, you can modify the permissions for your desired log directory so that the app pool can write to it.
Another reason could be an uninitialized log4net. In a winforms app, you usually configure log4net upon application start. In a web app, you can do this either dynamically (in your logging component, check if you can create a specific Ilog logger using its name, if not -> call configure()) or again upon application start in global.asax.cs.
put file slf4j-log4j12-1.6.4.jar
in the classpath will do the trick.
Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.
A common convention is to put the result of a build into a build
, target
or bin
directory.
The Jenkins archiver can use globs (target/*.jar
) to easily pick up the right file even if you have a unique name per build.
Typically, you can read the declaration of the variable from right to left. Therefore in the case of int *ptr;
, it means that you have a Pointer *
to an Integer variable int
. Also when it's declared int **ptr2;
, it is a Pointer variable *
to a Pointer variable *
pointing to an Integer variable int
, which is the same as "(int *)* ptr2;"
Now, following the syntax by declaring int*& rPtr;
, we say it's a Reference &
to a Pointer *
that points to a variable of type int
. Finally, you can apply again this approach also for int**& rPtr2;
concluding that it signifies a Reference &
to a Pointer *
to a Pointer *
to an Integer int
.
The following configuration taken from MSDN can be applied to enable tracing on your WCF service.
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true" >
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="myUserTraceSource"
switchValue="Information, ActivityTracing">
<listeners>
<add name="xml"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="Error.svclog" />
</sharedListeners>
</system.diagnostics>
</configuration>
To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".
If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:
You don't have to install the entire thing, just the ".NET Development / Tools" part.
When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.
i had the same error while working with hibernate, i had added below dependency in my pom.xml that solved the problem
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
</dependency>
reference https://mvnrepository.com/artifact/org.slf4j/slf4j-api
I recently ran into the same problem, and found a workaround though it'll only be useful if you can change the html code to suit.
I used tables to achieve my padded layout, so to create the equivalent of a div with internal padding I made a table with 3 columns/3 rows and put the content in the centre row/column. The first and last columns/rows are used for the padding.
eg.
<table>
<tr>
<td width="10"> </td>
<td> </td>
<td width="10"> </td>
</tr>
<tr>
<td> </td>
<td>content goes here</td>
<td> </td>
</tr>
<tr>
<td width="10"> </td>
<td> </td>
<td width="10"> </td>
</tr>
</table>
Hope that helps.
Joe
Is m_cRedundencyManager
able to use member functions? Most callbacks are set up to use regular functions or static member functions. Take a look at this page at C++ FAQ Lite for more information.
Update: The function declaration you provided shows that m_cRedundencyManager
is expecting a function of the form: void yourCallbackFunction(int, void *)
. Member functions are therefore unacceptable as callbacks in this case. A static member function may work, but if that is unacceptable in your case, the following code would also work. Note that it uses an evil cast from void *
.
// in your CLoggersInfra constructor:
m_cRedundencyManager->Init(myRedundencyManagerCallBackHandler, this);
// in your CLoggersInfra header:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr);
// in your CLoggersInfra source file:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr)
{
((CLoggersInfra *)CLoggersInfraPtr)->RedundencyManagerCallBack(i);
}
The _
character is also a wildcard, BTW, but I'm not sure why this wasn't working for you:
CREATE TRIGGER
[dbo].[SystemParameterInsertUpdate]
ON
[dbo].[SystemParameter]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
INSERT INTO SystemParameterHistory
(
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
)
SELECT
I.Attribute,
I.ParameterValue,
I.ParameterDescription,
I.ChangeDate
FROM Inserted AS I
WHERE I.Attribute NOT LIKE 'NoHist[_]%'
END
Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join.
I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround.
BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4.
--
i hope this helps
$("#dialog-yesno").dialog({
autoOpen: false,
resizable: false,
closeOnEscape: false,
height:180,
width:350,
modal: true,
show: "blind",
open: function() {
$(document).unbind('keydown.dialog-overlay');
},
buttons: {
"Delete": function() {
$(this).dialog("close");
var dir = $(this).data('link').href;
var arr=dir.split("-");
delete(arr[1]);
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
<a href="product-002371" onclick="$( '#dialog-yesno' ).data('link', this).dialog( 'open' ); return false;">Delete</a>
If you transferred these files through disk or other means, it is likely they were not saved properly.
Disable pretty listing. It is the option that re-formats what you are doing. I had the same discomfort with it and after doing it, my code stays how i want and it doesn't go back to previous settings.
I use:
int myint = 0;
long double myLD = 0.0;
string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();
It works on my Windows and Linux g++ compilers.
Here's a solution where security checking is disabled (for example, conversing with the localhost) Also, some of the solutions I've seen now contain deprecated methods and such.
/**
* @param configFilePath
* @param ipAddress
* @param userId
* @param password
* @throws MalformedURLException
*/
public Upgrade(String aConfigFilePath, String ipAddress, String userId, String password) {
configFilePath = aConfigFilePath;
baseUri = "https://" + ipAddress + ":" + PORT + "/";
restTemplate = new RestTemplate(createSecureTransport(userId, password, ipAddress, PORT));
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
}
ClientHttpRequestFactory createSecureTransport(String username,
String password, String host, int port) {
HostnameVerifier nullHostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);
HttpClient client = HttpClientBuilder.create()
.setSSLHostnameVerifier(nullHostnameVerifier)
.setSSLContext(createContext())
.setDefaultCredentialsProvider(credentialsProvider).build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(client);
return requestFactory;
}
private SSLContext createContext() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
} };
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
SSLContext.setDefault(sc);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return sc;
} catch (Exception e) {
}
return null;
}
Since version 1.3.0
AngularJS introduced extra filter parameter timezone
, like following:
{{ date_expression | date : format : timezone}}
But in versions 1.3.x
only supported timezone is UTC
, which can be used as following:
{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}
Since version 1.4.0-rc.0
AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):
{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}
Here you can find documentation of AngularJS date filters.
NOTE: this is working only with Angular 1.x
Here's working example
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
Allthough your src = encodeURI
should work, I would have gone a different way:
var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
As this has no x-domain restraints and is completely done via the iframe
handle, you may access and manipulate the contents of the frame later on. All you need to make sure of is, that the contents have been rendered, which will (depending on browser type) start during/after the .write command is issued - but not nescessarily done when close()
is called.
A 100% compatible way of doing a callback could be this approach:
<html><body onload="parent.myCallbackFunc(this.window)"></body></html>
Iframes has the onload event, however. Here is an approach to access the inner html as DOM (js):
iframe.onload = function() {
var div=iframe.contentWindow.document.getElementById('mydiv');
};
You should write textcolor in xml as
android:textColor="@color/text_color"
or
android:textColor="#FFFFFF"
You have your arguments to the remote add
command reversed:
git remote add <NAME> <PATH>
So:
git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git
See git remote --help
for more information.
function printdiv(printdivname) {
var headstr = "<html><head><title>Booking Details</title></head><body>";
var footstr = "</body>";
var newstr = document.getElementById(printdivname).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
This will print the div
area you want and set the content back to as it was. printdivname
is the div
to be printed.
You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.
Another might be using CDATA
tags.
Example using CDATA
:
<xml>
<title>Your HTML title</title>
<htmlData><![CDATA[<html>
<head>
<script/>
</head>
<body>
Your HTML's body
</body>
</html>
]]>
</htmlData>
</xml>
Please note:
CDATA's opening character sequence: <![CDATA[
CDATA's closing character sequence: ]]>
Set following style to set all textbox to uppercase
input {text-transform: uppercase;}
For me, it crashed because getBackground
returned a GradientDrawable
instead of a ShapeDrawable
.
So i modified it like this:
((GradientDrawable)someView.getBackground()).setColor(someColor);
If the result of, 'searchResult.Properties [ "user" ] [ 0 ]', is a string:
if ( ( searchResult.Properties [ "user" ].Count > 0 ) ) {
profile.User = System.Text.Encoding.UTF8.GetString ( searchResult.Properties [ "user" ] [ 0 ].ToCharArray ().Select ( character => ( byte ) character ).ToArray () );
}
The key point being that converting a string to a byte [] can be done using LINQ:
.ToCharArray ().Select ( character => ( byte ) character ).ToArray () )
And the inverse:
.Select ( character => ( char ) character ).ToArray () )
Using this you can check at least one checkbox is selected or not in different checkbox groups or multiple checkboxes.
Reference : Link
<label class="control-label col-sm-4">Check Box 1</label>
<input type="checkbox" name="checkbox1" id="checkbox1" value=Male /> Male<br />
<input type="checkbox" name="checkbox1" id="checkbox1" value=Female /> Female<br />
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<label class="control-label col-sm-4">Check Box 3</label>
<input type="checkbox" name="checkbox3" id="checkbox3" value=ck3 /> ck3<br />
<input type="checkbox" name="checkbox3" id="checkbox3" value=ck4 /> ck4<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox1]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 1 can not be null";
return false;
}
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
if (!$('input[name=checkbox3]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
On Window machine install any version of Git. I installed
Git-2.14.1-64-bit.exe
. Got to search program and search for git.exe. The file can be located under
C:\Users\sd\AppData\Local\Programs\Git\bin\git.exe
.
Open Intelli IDEA>Settings>Version Control>Git. On Path To Git executable add the path. Click on Test button. It will show a message as
Git executed successfully
Now click on Apply and Save. This will solve the issue. .
Eric Lippert wrote a detailed blog post about this subject a while back (additionally comparing it to VBScript). More accurately, he wrote about JScript, which is Microsoft's own implementation of ECMAScript, although very similar to JavaScript. I would imagine that you can assume the vast majority of behaviour would be the same for the JavaScript engine of Internet Explorer. Of course, the implementation will vary from browser to browser, though I suspect you could take a number of the common principles and apply them to other browsers.
Quoted from that page:
JScript uses a nongenerational mark-and-sweep garbage collector. It works like this:
Every variable which is "in scope" is called a "scavenger". A scavenger may refer to a number, an object, a string, whatever. We maintain a list of scavengers -- variables are moved on to the scav list when they come into scope and off the scav list when they go out of scope.
Every now and then the garbage collector runs. First it puts a "mark" on every object, variable, string, etc – all the memory tracked by the GC. (JScript uses the VARIANT data structure internally and there are plenty of extra unused bits in that structure, so we just set one of them.)
Second, it clears the mark on the scavengers and the transitive closure of scavenger references. So if a scavenger object references a nonscavenger object then we clear the bits on the nonscavenger, and on everything that it refers to. (I am using the word "closure" in a different sense than in my earlier post.)
At this point we know that all the memory still marked is allocated memory which cannot be reached by any path from any in-scope variable. All of those objects are instructed to tear themselves down, which destroys any circular references.
The main purpose of garbage collection is to allow the programmer not to worry about memory management of the objects they create and use, though of course there's no avoiding it sometimes - it is always beneficial to have at least a rough idea of how garbage collection works.
Historical note: an earlier revision of the answer had an incorrect reference to the delete
operator. In JavaScript the delete
operator removes a property from an object, and is wholly different to delete
in C/C++.
The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:
JavaScript:
// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false"
to disable the deprecated Bootstrap load function):
<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
Launch Modal
</a>
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try it yourself: https://jsfiddle.net/ednon5d1/
Your problem is not getting the directory (fso.GetAbsolutePathName(".")
resolves the current working directory just fine). Even if you wanted the script directory instead of the current working directory, you could easily determine that as Jakob Sternberg described in his answer.
What does not work in your code is building a path from the directory and your executable. This is invalid syntax:
Directory =
CurrentDirectory\attribute.exe
If you want to build a path from a variable and a file name, the file name must be specified as a string (or a variable containing a string) and either concatenated with the variable directory variable:
Directory = CurrentDirectory & "\attribute.exe"
or (better) you construct the path using the BuildPath method:
Directory = fso.BuildPath(CurrentDirectory, "attribute.exe")
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );
Working Solution :
For Resize image with size lower then 100Kb
WriteableBitmap bitmap = new WriteableBitmap(140,140);
bitmap.SetSource(dlg.File.OpenRead());
image1.Source = bitmap;
Image img = new Image();
img.Source = bitmap;
WriteableBitmap i;
do
{
ScaleTransform st = new ScaleTransform();
st.ScaleX = 0.3;
st.ScaleY = 0.3;
i = new WriteableBitmap(img, st);
img.Source = i;
} while (i.Pixels.Length / 1024 > 100);
More Reference at http://net4attack.blogspot.com/
For me I had indicated max-height
instead of max-width
.
If that is you, go change it !
@media screen and (max-width: 350px) { // Not max-height
.letter{
font-size:20px;
}
}
For me docker system prune
did the trick. I`m running mac os.
Add a second });
.
When properly indented, your code reads
$(function() {
$("#mewlyDiagnosed").hover(function() {
$("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
}, function() {
$("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
});
MISSING!
You never closed the outer $(function() {
.
use href
with indexof
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("added-to-cart=555") > -1) {
alert("your url contains the added-to-cart=555");
}
});
</script>
I would avoid using SELECT *
. Specify columns you actually want even though it may be all of them.
SQL Server 2005+
SELECT col1, col2
FROM (
SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
FROM MyTable
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow
SQL Server 2000
Efficiently Paging Through Large Result Sets in SQL Server 2000
A More Efficient Method for Paging Through Large Result Sets
Modify your Jquery in following way:
$.ajax({
url: someurl,
contentType: 'application/json',
data: JSONObject,
headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
dataType: 'json',
type: 'POST',
success: function (Data) {....}
});
I'm not sure the default hashcode is the address - I read the OpenJDK source for hashcode generation a while ago, and I remember it being something a bit more complicated. Still not something that guarantees a good distribution, perhaps. However, that is to some extent moot, as few classes you'd use as keys in a hashmap use the default hashcode - they supply their own implementations, which ought to be good.
On top of that, what you may not know (again, this is based in reading source - it's not guaranteed) is that HashMap stirs the hash before using it, to mix entropy from throughout the word into the bottom bits, which is where it's needed for all but the hugest hashmaps. That helps deal with hashes that specifically don't do that themselves, although i can't think of any common cases where you'd see that.
Finally, what happens when the table is overloaded is that it degenerates into a set of parallel linked lists - performance becomes O(n). Specifically, the number of links traversed will on average be half the load factor.
Instead of using jQuery, use css property text-overflow:ellipsis
. It will automatically truncate the string.
.truncated { display:inline-block;
max-width:100px;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
I would like to add this, I used this in laravel to just index my table:
My Code:
@foreach($resultsPerCountry->first()->studies as $result)
<tr>
<td>{{ ++$loop->index}}</td>
</tr>
@endforeach
There's also concat, but it doesn't get used much
select concat('a','b') from dual;
In getUserById
you shouldn't create a new object (user1) which isn't used. Just assign it to the already (but null) initialized user
. Otherwise Hibernate.initialize(user);
is actually Hibernate.initialize(null);
Here's the new getUserById
(I haven't tested this ;)):
public User getUserById(Long user_id) {
Session session = null;
Object user = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
user = (User)session.load(User.class, user_id);
Hibernate.initialize(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return user;
}
Another way to specify the popover content in a reusable way is to create a new data attribute like data-popover-content
and use it like this:
HTML:
<!-- Popover #1 -->
<a class="btn btn-primary" data-placement="top" data-popover-content="#a1" data-toggle="popover" data-trigger="focus" href="#" tabindex="0">Popover Example</a>
<!-- Content for Popover #1 -->
<div class="hidden" id="a1">
<div class="popover-heading">
This is the heading for #1
</div>
<div class="popover-body">
This is the body for #1
</div>
</div>
JS:
$(function(){
$("[data-toggle=popover]").popover({
html : true,
content: function() {
var content = $(this).attr("data-popover-content");
return $(content).children(".popover-body").html();
},
title: function() {
var title = $(this).attr("data-popover-content");
return $(title).children(".popover-heading").html();
}
});
});
This can be useful when you have a lot of html to place into your popovers.
Here is an example fiddle: http://jsfiddle.net/z824fn6b/
An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).
np.mean
always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result).
np.average
can compute a weighted average if the weights
parameter is supplied.
I am using Primefaces 6.0 and in order to remove borders from my panel grid i use this style class "ui-noborder" as follow:
<p:panelGrid columns="3" styleClass="ui-noborder">
<!--panel grid contents -->
</p:panelGrid>
It uses a css file named "components" in primefaces lib
You might want to have a look at joda time, which is a little easier to use than the java native date tools, and provides many common date patterns pre-built.
In response to comments, more detail:
To do this using Joda time, you need two DateTimeFormatters - one for your input format to parse your input and one for your output format to print your output. Your input format is an ISO standard format, so Joda time's ISODateTimeFormat class has a static method with a parser for it already: dateHourMinuteSecondMillis. Your output format isn't one they have a pre-built formatter for, so you'll have to make one yourself using DateTimeFormat. I think DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS");
should do the trick. Once you have your two formatters, call the parseDateTime()
method on the input format and the print
method on the output format to get your result, as a string.
Putting it together should look something like this (warning, untested):
DateTimeFormatter input = ISODateTimeFormat.dateHourMinuteSecondMillis();
DateTimeFormatter output = DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS");
String outputFormat = output.print( input.parseDate(inputFormat) );
You can redirect stdout into a file "output.txt":
import sys
sys.stdout = open('output.txt','wt')
print ("Hello stackoverflow!")
print ("I have a question.")
In Python2, input
is evaluated, input()
is equivalent to eval(raw_input())
. When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.
Use raw_input
to get a string from the user in Python2.
Demo 1: klj
is not defined:
>>> input()
klj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined
Demo 2: klj
is defined:
>>> klj = 'hi'
>>> input()
klj
'hi'
Demo 3: getting a string with raw_input
:
>>> raw_input()
klj
'klj'
I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.
Regarding displaying embedded (inline) images, here's what's on their documentation:
Inline Attachments
There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with
<img src="cid:my-photo" alt="my-photo" />
.In detail, here is the function to add an inline attachment:
$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');
To give you a more complete example of how it would work:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->Port = 25; // set the SMTP port
$mail->SetFrom('[email protected]', 'First Last');
$mail->AddAddress('[email protected]', 'John Doe');
$mail->Subject = 'PHPMailer Test';
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';
$mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.
One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.
For example:
You can replace the line that send the email:
$mail->Send();
With this:
$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want
Hope that helps. Let me know if you run into trouble using it.
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
We don't know what server.properties file is that, we neither know what SimocoPoolSize means (do you?)
Let's guess you are using some custom pool of database connections. Then, I guess the problem is that your pool is configured to open 100 or 120 connections, but you Postgresql server is configured to accept MaxConnections=90
. These seem conflictive settings. Try increasing MaxConnections=120
.
But you should first understand your db layer infrastructure, know what pool are you using, if you really need so many open connections in the pool. And, specially, if you are gracefully returning the opened connections to the pool
Another approach is to use an object for initial storage of the array information. Then convert back. For example:
var arr = ['0','1','1','2','3','3','3'];
var obj = {};
for(var i in arr)
obj[i] = true;
arr = [];
for(var i in obj)
arr.push(i);
Variable "arr" now contains ["0", "1", "2", "3", "4", "5", "6"]
I tried to update the user, and it worked. See the command below.
USE ComparisonData// databaseName
EXEC sp_change_users_login @Action='update_one', @UserNamePattern='ftool',@LoginName='ftool';
Just replace user('ftool')
accordingly.
a whole div links to another page when clicked without javascript and with valid code, is this possible?
Pedantic answer: No.
As you've already put on another comment, it's invalid to nest a div
inside an a
tag.
However, there's nothing preventing you from making your a
tag behave very similarly to a div
, with the exception that you cannot nest other block tags inside it. If it suits your markup, set display:block
on your a
tag and size / float it however you like.
If you renege on your question's premise that you need to avoid javascript, as others have pointed our you can use the onClick event handler. jQuery is a popular choice for making this easy and maintainable.
Update:
In HTML5, placing a <div>
inside an <a>
is valid.
See http://dev.w3.org/html5/markup/a.html#a-changes (thanks Damien)
You can use the ??
test operator:
This checks if the attribute of the object is not null:
<#if object.attribute??></#if>
This checks if object or attribute is not null:
<#if (object.attribute)??></#if>
Source: FreeMarker Manual
I wouldn't bother doing it in Linq2SQL. Create a stored Procedure for the query you want and understand and then create the object to the stored procedure in the framework or just connect direct to it.
Assuming you mean "file on a local filesystem" when you say .json file.
You'll need to save the json data formatted as jsonp, and use a file:// url
to access it.
Your HTML will look like this:
<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
function updateMe(){
var x = 0;
var activity=jsonstr;
foreach (i in activity) {
date = document.getElementById(i.date).innerHTML = activity.date;
event = document.getElementById(i.event).innerHTML = activity.event;
}
}
</script>
And the file c:\data\activity.jsonp contains the following line:
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
I have a same problem with google/google-api-php-client v2.0.0-RC7 and after search for 1 hours, i solved this problem using json_encode like this:
if ($client->isAccessTokenExpired()) {
$newToken = json_decode(json_encode($client->getAccessToken()));
$client->refreshToken($newToken->refresh_token);
file_put_contents(storage_path('app/client_id.txt'), json_encode($client->getAccessToken()));
}
This is my benchmark results
test 4,267,740 ops/sec ±1.32% (60 runs sampled)
exec 3,649,719 ops/sec ±2.51% (60 runs sampled)
match 3,623,125 ops/sec ±1.85% (62 runs sampled)
indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)
test method is faster than the match method, but the fastest method is the indexOf
Try this SQL statement:
update Table set Column =( Column - your val )
I have taken Vlad's idea and changed it a little bit. Instead of
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null
Which yields
sed: couldn't edit /dev/null: not a regular file
I'm doing in 3 different connections to the remote server
touch deleteme
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' ./deleteme
rm deleteme
Although this is less elegant and requires 2 more connections to the server (maybe there's a way to do it all in one line) it does the job efficiently as well
I think you can use
sys.exit(0)
You may check it here in the python 2.7 doc:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.
Differences:
1) Implicit wait is set for the entire duration of the webDriver object. Suppose , you want to wait for a certain duration, let's say 5 seconds before each element or a lot of elements on the webpage load. Now, you wouldn't want to write the same code again and again. Hence, implicit wait. However, if you want to wait for only one element, use explicit.
2) You not only need web element to show up but also to be clickable or to satisfy certain other property of web elements. Such kind of flexibility can be provided by explicit wait only. Specially helpful if dynamic data is being loaded on webpage. You can wait for that element to be developed (not just show up on DOM) using explicit wait.
String filepath="/tmp/employee.csv";
FileWriter sw = new FileWriter(new File(filepath));
CSVWriter writer = new CSVWriter(sw);
writer.writeAll(allRows);
String[] header= new String[]{"ErrorMessage"};
writer.writeNext(header);
List<String[]> errorData = new ArrayList<String[]>();
for(int i=0;i<1;i++){
String[] data = new String[]{"ErrorMessage"+i};
errorData.add(data);
}
writer.writeAll(errorData);
writer.close();
As always with reference types, there are two notions of "copy". I'm sure you know them, but for completeness.
You want the latter. If this is one of your own objects, you need simply adopt the protocol NSCopying and implement -(id)copyWithZone:(NSZone *)zone. You're free to do whatever you want; though the idea is you make a real copy of yourself and return it. You call copyWithZone on all your fields, to make a deep copy. A simple example is
@interface YourClass : NSObject <NSCopying>
{
SomeOtherObject *obj;
}
// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
// We'll ignore the zone for now
YourClass *another = [[YourClass alloc] init];
another.obj = [obj copyWithZone: zone];
return another;
}
GCC compiles a C/C++ program into executable in 4 steps.
For example, gcc -o hello hello.c
is carried out as follows:
Preprocessing via the GNU C Preprocessor (cpp.exe
), which includes
the headers (#include
) and expands the macros (#define
).
cpp hello.c > hello.i
The resultant intermediate file "hello.i" contains the expanded source code.
The compiler compiles the pre-processed source code into assembly code for a specific processor.
gcc -S hello.i
The -S option specifies to produce assembly code, instead of object code. The resultant assembly file is "hello.s".
The assembler (as.exe
) converts the assembly code into machine code in the object file "hello.o".
as -o hello.o hello.s
Finally, the linker (ld.exe
) links the object code with the library code to produce an executable file "hello".
ld -o hello hello.o ...libraries...
I real all the solution but there is not a standard solution...
JUST REMOVE NODEJS AND INSTALL THE LATEST VERSION OF NODEJS
instead of many bad shortcut solutions.
Using the indexOf function was not cutting it on my collection of REST resources.
I had to create a function that retrieves the array index of a resource sitting in a collection of resources:
factory.getResourceIndex = function(resources, resource) {
var index = -1;
for (var i = 0; i < resources.length; i++) {
if (resources[i].id == resource.id) {
index = i;
}
}
return index;
}
$scope.unassignedTeams.splice(CommonService.getResourceIndex($scope.unassignedTeams, data), 1);
I try to use a union to combine two queries to format the returns you want:
SELECT recordid, startdate, enddate FROM tmp
Where enddate is null
UNION
SELECT recordid, MIN(startdate), MAX(enddate) FROM tmp GROUP BY recordid
But I have no idea if the Union would have great impact on the performance
I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader
's fault. Try measuring this:
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing
I think you'll find it's almost exactly the same time as when you're parsing the text.
Note that you should also give InputStreamReader
an appropriate encoding - the platform default encoding is almost certainly not what you should be using.
By default the @Transactional
attribute works only when calling an annotated method on a reference obtained from applicationContext.
public class Bean {
public void doStuff() {
doTransactionStuff();
}
@Transactional
public void doTransactionStuff() {
}
}
This will open a transaction:
Bean bean = (Bean)appContext.getBean("bean");
bean.doTransactionStuff();
This will not:
Bean bean = (Bean)appContext.getBean("bean");
bean.doStuff();
Spring Reference: Using @Transactional
Note: In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with
@Transactional
!Consider the use of AspectJ mode (see below) if you expect self-invocations to be wrapped with transactions as well. In this case, there won't be a proxy in the first place; instead, the target class will be 'weaved' (i.e. its byte code will be modified) in order to turn
@Transactional
into runtime behavior on any kind of method.
Try this code,
public void ConnectToAccess()
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= C:\Documents and Settings\username\" +
@"My Documents\AccessFile.mdb";
try
{
conn.Open();
// Insert code to process data.
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}
http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx
It may be useful for someone, so I'll post it here.
I was missing this dependency on my pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
string[] str = new string[]{"1","2"};
string[] str = new string[4];
You can save the current cookies as a Python object using pickle. For example:
import pickle
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
And later to add them back:
import pickle
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
Building on the most highly voted answer, here is a function to wait for two ports to be open, with a timeout as well. Note the two ports that mus be open, 8890 and 1111, as well as the max_attempts (1 per second).
function wait_for_server_to_boot()
{
echo "Waiting for server to boot up..."
attempts=0
max_attempts=30
while ( nc 127.0.0.1 8890 < /dev/null || nc 127.0.0.1 1111 < /dev/null ) && [[ $attempts < $max_attempts ]] ; do
attempts=$((attempts+1))
sleep 1;
echo "waiting... (${attempts}/${max_attempts})"
done
}
Thanks for this thread -- it helped me a lot too.
I learned something about .join() today.
These threads run in parallel:
d.start()
t.start()
d.join()
t.join()
and these run sequentially (not what I wanted):
d.start()
d.join()
t.start()
t.join()
In particular, I was trying to clever and tidy:
class Kiki(threading.Thread):
def __init__(self, time):
super(Kiki, self).__init__()
self.time = time
self.start()
self.join()
This works! But it runs sequentially. I can put the self.start() in __ init __, but not the self.join(). That has to be done after every thread has been started.
join() is what causes the main thread to wait for your thread to finish. Otherwise, your thread runs all by itself.
So one way to think of join() as a "hold" on the main thread -- it sort of de-threads your thread and executes sequentially in the main thread, before the main thread can continue. It assures that your thread is complete before the main thread moves forward. Note that this means it's ok if your thread is already finished before you call the join() -- the main thread is simply released immediately when join() is called.
In fact, it just now occurs to me that the main thread waits at d.join() until thread d finishes before it moves on to t.join().
In fact, to be very clear, consider this code:
import threading
import time
class Kiki(threading.Thread):
def __init__(self, time):
super(Kiki, self).__init__()
self.time = time
self.start()
def run(self):
print self.time, " seconds start!"
for i in range(0,self.time):
time.sleep(1)
print "1 sec of ", self.time
print self.time, " seconds finished!"
t1 = Kiki(3)
t2 = Kiki(2)
t3 = Kiki(1)
t1.join()
print "t1.join() finished"
t2.join()
print "t2.join() finished"
t3.join()
print "t3.join() finished"
It produces this output (note how the print statements are threaded into each other.)
$ python test_thread.py
32 seconds start! seconds start!1
seconds start!
1 sec of 1
1 sec of 1 seconds finished!
21 sec of
3
1 sec of 3
1 sec of 2
2 seconds finished!
1 sec of 3
3 seconds finished!
t1.join() finished
t2.join() finished
t3.join() finished
$
The t1.join() is holding up the main thread. All three threads complete before the t1.join() finishes and the main thread moves on to execute the print then t2.join() then print then t3.join() then print.
Corrections welcome. I'm also new to threading.
(Note: in case you're interested, I'm writing code for a DrinkBot, and I need threading to run the ingredient pumps concurrently rather than sequentially -- less time to wait for each drink.)
You have to change the mamp Mysql Database port into 8889.
A class for splitting strings I came up with. A short test is provided at the end.
SplitStringUtils.smartSplitToShorterStrings(String str, int maxLen, int maxParts)
will split by spaces without breaking words, if possible, and if not, will split by indexes according to maxLen.
Other methods provided to control how it is split: bruteSplitLimit(String str, int maxLen, int maxParts)
, spaceSplit(String str, int maxLen, int maxParts)
.
public class SplitStringUtils {
public static String[] smartSplitToShorterStrings(String str, int maxLen, int maxParts) {
if (str.length() <= maxLen) {
return new String[] {str};
}
if (str.length() > maxLen*maxParts) {
return bruteSplitLimit(str, maxLen, maxParts);
}
String[] res = spaceSplit(str, maxLen, maxParts);
if (res != null) {
return res;
}
return bruteSplitLimit(str, maxLen, maxParts);
}
public static String[] bruteSplitLimit(String str, int maxLen, int maxParts) {
String[] bruteArr = bruteSplit(str, maxLen);
String[] ret = Arrays.stream(bruteArr)
.limit(maxParts)
.collect(Collectors.toList())
.toArray(new String[maxParts]);
return ret;
}
public static String[] bruteSplit(String name, int maxLen) {
List<String> res = new ArrayList<>();
int start =0;
int end = maxLen;
while (end <= name.length()) {
String substr = name.substring(start, end);
res.add(substr);
start = end;
end +=maxLen;
}
String substr = name.substring(start, name.length());
res.add(substr);
return res.toArray(new String[res.size()]);
}
public static String[] spaceSplit(String str, int maxLen, int maxParts) {
List<Integer> spaceIndexes = findSplitPoints(str, ' ');
List<Integer> goodSplitIndexes = new ArrayList<>();
int goodIndex = -1;
int curPartMax = maxLen;
for (int i=0; i< spaceIndexes.size(); i++) {
int idx = spaceIndexes.get(i);
if (idx < curPartMax) {
goodIndex = idx;
} else {
goodSplitIndexes.add(goodIndex+1);
curPartMax = goodIndex+1+maxLen;
}
}
if (goodSplitIndexes.get(goodSplitIndexes.size()-1) != str.length()) {
goodSplitIndexes.add(str.length());
}
if (goodSplitIndexes.size()<=maxParts) {
List<String> res = new ArrayList<>();
int start = 0;
for (int i=0; i<goodSplitIndexes.size(); i++) {
int end = goodSplitIndexes.get(i);
if (end-start > maxLen) {
return null;
}
res.add(str.substring(start, end));
start = end;
}
return res.toArray(new String[res.size()]);
}
return null;
}
private static List<Integer> findSplitPoints(String str, char c) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
list.add(i);
}
}
list.add(str.length());
return list;
}
}
Simple test code:
public static void main(String[] args) {
String [] testStrings = {
"123",
"123 123 123 1123 123 123 123 123 123 123",
"123 54123 5123 513 54w567 3567 e56 73w45 63 567356 735687 4678 4678 u4678 u4678 56rt64w5 6546345",
"1345678934576235784620957029356723578946",
"12764444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444",
"3463356 35673567567 3567 35 3567 35 675 653 673567 777777777777777777777777777777777777777777777777777777777777777777"
};
int max = 35;
int maxparts = 2;
for (String str : testStrings) {
System.out.println("TEST\n |"+str+"|");
printSplitDetails(max, maxparts);
String[] res = smartSplitToShorterStrings(str, max, maxparts);
for (int i=0; i< res.length;i++) {
System.out.println(" "+i+": "+res[i]);
}
System.out.println("===========================================================================================================================================================");
}
}
static void printSplitDetails(int max, int maxparts) {
System.out.print(" X: ");
for (int i=0; i<max*maxparts; i++) {
if (i%max == 0) {
System.out.print("|");
} else {
System.out.print("-");
}
}
System.out.println();
}
Not certain what the HTML looks like (that would help with answers). If it's
<div class="testimonials content">stuff</div>
then simply remove the space in your css. A la...
.testimonials.content { css here }
UPDATE:
Okay, after seeing HTML see if this works...
.testimonials .wrapper .content { css here }
or just
.testimonials .wrapper { css here }
or
.desc-container .wrapper { css here }
all 3 should work.
If you don't want to group, then use the following method:
db.collection.aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $count: 'count' }
] );
you can define a route in web.php
Route::get('/clear/route', 'ConfigController@clearRoute');
and make ConfigController.php like this
class ConfigController extends Controller
{
public function clearRoute()
{
\Artisan::call('route:clear');
}
}
and go to that route on server example http://your-domain/clear/route
You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:
import sys
sys.path.append('/home/user/python-libs')
Use curl
instead of file_get_contents
:
$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=India";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
echo $lat = $response_a->results[0]->geometry->location->lat;
echo "<br />";
echo $long = $response_a->results[0]->geometry->location->lng;
You could fill the C Column with variations on the following formula:
=IF(ISERROR(MATCH(A1,$B:$B,0)),"",A1)
Then C would only contain values that were in A and C.
Bootstrap V3:
Once i was searching for laravel features then i got to know this amazing form validation. Later on, i amended glyphicon icon features. Now, it looks great.
<div class="col-md-12">
<div class="form-group has-error has-feedback">
<input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Email field is required.</p></span>
</div>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<div class="form-group has-error has-feedback">
<input id="account_holder_name" name="name" type="text" placeholder="Name" class="form-control ">
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Name field is required.</p></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-error has-feedback">
<input id="check_np" name="check_no" type="text" placeholder="Check no" class="form-control ">
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Check No. field is required.</p></span>
</div>
</div>
Once i completed it i thought i should implement it in Codeigniter as well. So here is the Codeigniter-3 validation with Bootstrap:
Controller
function addData()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|max_length[128]');
if($this->form_validation->run() == FALSE)
{
//validation fails. Load your view.
$this->loadViews('Load your view','pass your data to view if any');
}
else
{
//validation pass. Your code here.
}
}
View
<div class="col-md-12">
<?php
$email_error = (form_error('email') ? 'has-error has-feedback' : '');
if(!empty($email_error)){
$emailData = '<span class="help-block">'.form_error('email').'</span>';
$emailClass = $email_error;
$emailIcon = '<span class="glyphicon glyphicon-remove form-control-feedback"></span>';
}
else{
$emailClass = $emailIcon = $emailData = '';
}
?>
<div class="form-group <?= $emailClass ?>">
<input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
<?= $emailIcon ?>
<?= $emailData ?>
</div>
</div>
I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.
This one does not use SendKeys.
Let me know if this helps! JFV
Based on the warning message, the component ReactTooltip renders an HTML that might look like this:
<p>
<div>...</div>
</p>
According to this document, a <p></p>
tag can only contain inline elements. That means putting a <div></div>
tag inside it should be improper, since the div
tag is a block element. Improper nesting might cause glitches like rendering extra tags, which can affect your javascript and css.
If you want to get rid of this warning, you might want to customize the ReactTooltip component, or wait for the creator to fix this warning.
You must search date defend on how you insert that game_date data on your database.. for example if you inserted date value on long date or short.
SELECT * FROM hockey_stats WHERE game_date >= "6/11/2018" AND game_date <= "6/17/2018"
You can also use BETWEEN:
SELECT * FROM hockey_stats WHERE game_date BETWEEN "6/11/2018" AND "6/17/2018"
simple as that.
Maybe some folk are making the same mistake I did? Which was... I had set a width for the input boxes, because they were mostly of type 'text' , but then forgotten to over-ride that width for checkboxes - so my checkbox was trying to occupy a lot of excess width and so it was tough to align a label beside it.
.checkboxlabel {
width: 100%;
vertical-align: middle;
}
.checkbox {
width: 20px !important;
}
<label for='acheckbox' class='checkboxlabel'>
<input name="acheckbox" id='acheckbox' type="checkbox" class='checkbox'>Contact me</label>
Gives clickable labels and and proper alignment as far back as IE6 (using a class selector) and in late versions of Firefox, Safari and Chrome
If you want to create a new A
you can use INTO
;
select * into A from dbo.myView
I was just having the same problem. Here's what I found... I had copied my data from a website (loan payment information), pasted into Excel and then couldn't get it to sort appropriately by date and my calculation formulas wouldn't work. I copied the date columns and pasted as plain text in Word then turned on the formatting characters and found extra characters, namely the one that looks like a degree symbol. Same thing with my currency columns. So I used find and replace to get rid of the extra characters, then copy & paste back in to Excel. Boom! Everything worked the way it should.
You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.
I want columns One and Two to shrink/grow to fit rather than being fixed.
Have you tried: flex-basis: auto
or this:
flex: 1 1 auto
, which is short for:
flex-grow: 1
(grow proportionally)flex-shrink: 1
(shrink proportionally)flex-basis: auto
(initial size based on content size)or this:
main > section:first-child {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:nth-child(2) {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:last-child {
flex: 20 1 auto;
display: flex;
flex-direction: column;
}
Related:
Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r
: r"Hello\tWorld\nHello World"
.
>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World
Also, \s
is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.
The usage of yield is similar to the keyword return, except that it will return a generator. And the generator object will only traverse once.
yield has two benefits:
There is another clear explanation maybe help you.
Make use of jquery toggle function which do the task for you
.toggle() - Display or hide the matched elements.
$('#myelement').click(function(){
$('#another-element').toggle('slow');
});
I think better to used
$result->isEmpty();
The isEmpty method returns true if the collection is empty; otherwise, false is returned.
I had this info message "No Spring WebApplicationInitializer types detected on classpath" while deploying a WAR with spring integration beans in WebLogic server. Actually, I could observe that the servlet URL returned 404 Not Found and beside that info message with a negative tone "No Spring ...etc" in Server logs, nothing else was seemingly in error in my spring config; no build or deployment errors, no complaints. Indeed, I suspected that the beans.xml (spring context XML) was actually not picked up at all and that was bound to the very specific organizing of artefacts in Oracle's jDeveloper. The solution is to play carefully with the 'contributors' and 'filters' for the WEB-INF/classes category when you edit your deployment profile under the 'deployment' topic in project properties.
Precisely, I would advise to name your spring context by the jDeveloper default "beans.xml" and place it side by side to the WEB-INF subdirectory itself (under your web Apllication source path, e.g. like <...your project path>/public_html/). Then in the WEB-INF/classes category (when editing the deployment profile) your can check the Project HTML root directory in the 'contributor' list, and then select the beans.xml in filters, and then ensure your web.xml features a context-param value like classpath:beans.xml.
Once that was fixed, I was able to progress and after some more bean config changes and implementations, the message "No Spring WebApplicationInitializer types detected on classpath" came back! Actually, I did not notice when and why exactly it came back. This second time, I added a
public class HttpGatewayInit implements WebApplicationInitializer { ... }
which implements empty inherited methods, and the whole application works fine!
...If you feel that java EE development has been getting a bit too crazy with cascades of XML configuration files (some edited manually, others through wizards) intepreted by cascades of variant initializers, let me insist that I fully share your point.
Basically you need to edit the JS and add (in this case, inside $('#featured-articles').slick({
), this:
variableWidth: true,
This will allow you to edit the width in your CSS where you can, generically use:
.slick-slide {
width: 100%;
}
or in this case:
.featured {
width: 100%;
}
About your command line:
root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
You are already authenticated as root
so sudo
is redundant there.
You are missing the -j
or --jump
just before the ACCEPT
parameter (just tought that was a typo and you are inserting it correctly).
About yout question:
If you are inserting the iptables
rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.
If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:
check your vmachine network settings and:
if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.
if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.
if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.
Hope this helps.
You might find this article of interest which is available at codeplex.com.
The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.
Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.
Similar to the suggestion to put everything on an SSD.
I run netbeans from freeBSD. The netbeans cache files were in my home directory in .netbeans. My home directory was mounted over nfs so access was very slow. Moving .netbeans to the local machine greatly improved performance. I added a softlink from .netbeans in my home directory to the local directory. Netbeans describes how to change the usedir and cachedir here and lists this as a reason under item 4.
Prior to this I could write entire sentences in comments before the gui caught up and displayed them. After text appears as I type.
Just a quick update, timings using python 3:
#!/usr/local/bin python3
from timeit import Timer
a = set(range(1, 100000))
b = list(range(50000, 150000))
def one_by_one(s, l):
for i in l:
s.add(i)
def cast_to_list_and_back(s, l):
s = set(list(s) + l)
def update_set(s,l):
s.update(l)
results are:
one_by_one 10.184448844986036
cast_to_list_and_back 7.969255169969983
update_set 2.212590195937082
Actually Opera doesn't have 5MB limit. It offers to increase limit as applications requires more. User can even choose "Unlimited storage" for a domain.
You can easily test localStorage limits/quota yourself.
From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.
Usage looks like this:
using System.Linq;
// ...
public void My()
{
var myArray = new[] { "abc", "123", "zyx" };
List<string> myList = myArray.ToList();
}
PS. There's also ToArray()
method that works in other way.
I am here by separating both the usages by marking them as File Read(java.io) and Resource Read(ClassLoader.getResourceAsStream()).
File Read - 1. Works on local file system. 2. Tries to locate the file requested from current JVM launched directory as root 3. Ideally good when using files for processing in a pre-determined location like,/dev/files or C:\Data.
Resource Read - 1. Works on class path 2. Tries to locate the file/resource in current or parent classloader classpath. 3. Ideally good when trying to load files from packaged files like war or jar.
Adding up on EJP's answer; use this for more fluidity. Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:
int count;
byte[] bytes = new byte[4096];
try {
while ((count = is.read(bytes)) > 0) {
System.out.println(count);
bos.write(bytes, 0, count);
}
} catch ( Exception e )
{
//It will land here....
}
// Then continue from here
EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!
Hope this post solves any of your issues
It’s about time someone provides the modern answer. The modern solution uses java.time, the modern Java date and time API. The classes SimpleDateFormat
and Date
used in the question and in a couple of the other answers are poorly designed and long outdated, the former in particular notoriously troublesome. TimeZone
is poorly designed to. I recommend you avoid those.
ZoneId utc = ZoneId.of("Etc/UTC");
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy hh:mm:ss a zzz", Locale.ENGLISH);
String itsAlarmDttm = "2013-10-22T01:37:56";
ZonedDateTime utcDateTime = LocalDateTime.parse(itsAlarmDttm)
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(utc);
String formatterUtcDateTime = utcDateTime.format(targetFormatter);
System.out.println(formatterUtcDateTime);
When running in my time zone, Europe/Copenhagen, the output is:
10/21/2013 11:37:56 PM UTC
I have assumed that the string you got was in the default time zone of your JVM, a fragile assumption since that default setting can be changed at any time from another part of your program or another programming running in the same JVM. If you can, instead specify time zone explicitly, for example ZoneId.of("Europe/Podgorica")
or ZoneId.of("Asia/Kolkata")
.
I am exploiting the fact that you string is in ISO 8601 format, the format the the modern classes parse as their default, that is, without any explicit formatter.
I am using a ZonedDateTime
for the result date-time because it allows us to format it with UTC
in the formatted string to eliminate any and all doubt. For other purposes one would typically have wanted an OffsetDateTime
or an Instant
instead.
KOTLIN
Any Activity that restarts has its onResume() method executed first.
To use this method, do this:
override fun onResume() {
super.onResume()
// your code here
}
If the decimal separator is comma (eg : LC_NUMERIC=fr_FR.UTF-8, see here):
$ printf "%.0f" $(echo "scale=2;3/2" | bc)
bash: printf: 1.50: nombre non valable
0
Substitution is needed for ghostdog74 solution :
$ printf "%.0f" $(echo "scale=2;3/2" | bc | sed 's/[.]/,/')
2
or
$ printf "%.0f" $(echo "scale=2;3/2" | bc | tr '.' ',')
2
Here's another practical example from my CUDA Convolutional neural network library. I have the following class template:
template <class T> class Tensor
which is actually implements n-dimensional matrices manipulation. There's also a child class template:
template <class T> class TensorGPU : public Tensor<T>
which implements the same functionality but in GPU. Both templates can work with all basic types, like float, double, int, etc And I also have a class template (simplified):
template <template <class> class TT, class T> class CLayerT: public Layer<TT<T> >
{
TT<T> weights;
TT<T> inputs;
TT<int> connection_matrix;
}
The reason here to have template template syntax is because I can declare implementation of the class
class CLayerCuda: public CLayerT<TensorGPU, float>
which will have both weights and inputs of type float and on GPU, but connection_matrix will always be int, either on CPU (by specifying TT = Tensor) or on GPU (by specifying TT=TensorGPU).
You can directly specify the item's alignment, for example:
textright: {
alignSelf: 'flex-end',
},
if no luck with above try to it a class or even id something like textarea.foo and then your style. or try to !important
Run this:
init = tf.global_variables_initializer()
sess.run(init)
Or (depending on the version of TF that you have):
init = tf.initialize_all_variables()
sess.run(init)
Use explicit injection. No other approach will allow you for instance to run tests in parallel in the same JVM.
Patterns that use anything classloader wide like static log binder or messing with environmental thinks like logback.XML are bust when it comes to testing.
Consider the parallelized tests I mention , or consider the case where you want to intercept logging of component A whose construction is hidden behind api B. This latter case is easy to deal with if you are using a dependency injected loggerfactory from the top, but not if you inject Logger as there no seam in this assembly at ILoggerFactory.getLogger.
And its not all about unit testing either. Sometimes we want integration tests to emit logging. Sometimes we don't. Someone's we want some of the integration testing logging to be selectively suppressed, eg for expected errors that would otherwise clutter the CI console and confuse. All easy if you inject ILoggerFactory from the top of your mainline (or whatever di framework you might use)
So...
Either inject a reporter as suggested or adopt a pattern of injecting the ILoggerFactory. By explicit ILoggerFactory injection rather than Logger you can support many access/intercept patterns and parallelization.
mark a text area by mark command say ma and mb type command: :'a,'bg/(.*)/s////\1/
You can see an example of this kind of test manipulation at http://bknpk.ddns.net/my_web/VIM/vim_shell_cmd_on_block.html
try Integer.toString(integer value);
method as
ed = (EditText)findViewById(R.id.box);
int x = 10;
ed.setText(Integer.toString(x));
make sure your properties file exist in classpath directory but not in sub folder of your classpath directory. if it is exist in sub folder then write as below classpath:subfolder/idm.properties
Thanks to both sipwiz and MrEvil. We developed a PHP script that will parse the URL that the user enters and paste www
to the top of it. (e.g. if the customer enters kiragiannis.com, then it will redirect to www.kiragiannis.com). So our customer point their root (e.g. customer1.com
to A
record where our web redirector is) and then www
CNAME
to the real A
record managed by us.
Below the code in case you are interested for future us.
<?php
$url = strtolower($_SERVER["HTTP_HOST"]);
if(strpos($url, "//") !== false) { // remove http://
$url = substr($url, strpos($url, "//") + 2);
}
$urlPagePath = "";
if(strpos($url, "/") !== false) { // store post-domain page path to append later
$urlPagePath = substr($url, strpos($url, "/"));
$url = substr($url, 0, strpos($url,"/"));
}
$urlLast = substr($url, strrpos($url, "."));
$url = substr($url, 0, strrpos($url, "."));
if(strpos($url, ".") !== false) { // get rid of subdomain(s)
$url = substr($url, strrpos($url, ".") + 1);
}
$url = "http://www." . $url . $urlLast . $urlPagePath;
header( "Location:{$url}");
?>
There is a schema called INFORMATION_SCHEMA
schema which contains a set of views on tables from the SYS schema that you can query to get what you want.
A major upside of the INFORMATION_SCHEMA
is that the object names are very query friendly and user readable. The downside of the INFORMATION_SCHEMA
is that you have to write one query for each type of object.
The Sys schema may seem a little cryptic initially, but it has all the same information (and more) in a single spot.
You'd start with a table called SysObjects (each database has one) that has the names of all objects and their types.
One could search in a database as follows:
Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
and [Name] like '%YourObjectName%'
Now, if you wanted to restrict this to only search for tables and stored procs, you would do
Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
and [Name] like '%YourObjectName%'
and Type in ('U', 'P')
If you look up object types, you will find a whole list for views, triggers, etc.
Now, if you want to search for this in each database, you will have to iterate through the databases. You can do one of the following:
If you want to search through each database without any clauses, then use the sp_MSforeachdb as shown in an answer here.
If you only want to search specific databases, use the "USE DBName" and then search command.
You will benefit greatly from having it parameterized in that case. Note that the name of the database you are searching in will have to be replaced in each query (DatabaseOne, DatabaseTwo...). Check this out:
Declare @ObjectName VarChar (100)
Set @ObjectName = '%Customer%'
Select 'DatabaseOne' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseOne.Sys.Objects
Where 1=1
and [Name] like @ObjectName
and Type in ('U', 'P')
UNION ALL
Select 'DatabaseTwo' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseTwo.Sys.Objects
Where 1=1
and [Name] like @ObjectName
and Type in ('U', 'P')
UNION ALL
Select 'DatabaseThree' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseThree.Sys.Objects
Where 1=1
and [Name] like @ObjectName
and Type in ('U', 'P')
Dirty and quick hack:
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN Table2 ON Table1.Col1 = Table2.Col1
AND ((Table1.Col2 = Table2.Col2) OR (Table1.Col2 IS NULL AND Table2.Col2 IS NULL))
An entity manager can only be injected in classes running inside a transaction. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.
Since your TestService is not an EJB, the annotation @PersistenceContext is simply ignored. Not only that, in JavaEE 5, it's not possible to inject an EntityManager nor an EntityManagerFactory in a JAX-RS Service. You have to go with a JavaEE 6 server (JBoss 6, Glassfish 3, etc).
Here's an example of injecting an EntityManagerFactory:
package com.test.service;
import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;
@Path("/service")
public class TestService {
@PersistenceUnit(unitName = "test")
private EntityManagerFactory entityManagerFactory;
@GET
@Path("/get")
@Produces("application/json")
public List get() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
return entityManager.createQuery("from TestEntity").getResultList();
} finally {
entityManager.close();
}
}
}
The easiest way to go here is to declare your service as a EJB 3.1, assuming you're using a JavaEE 6 server.
Related question: Inject an EJB into JAX-RS (RESTful service)
Try this
//field "search";
var pattern = /[?&]search=/;
var URL = location.search;
if(pattern.test(URL))
{
alert("Found :)");
}else{
alert("Not found!");
}
sizeof
returns the size of the type of the variable in bytes. So in your case it's returning the size of your char[7]
which is 7 * sizeof(char)
. Since sizeof(char) = 1
, the result is 7.
Expanding this to another example:
int intArr[5];
printf("sizeof(intArr)=%u", sizeof(intArr));
would yield 5 * sizeof(int)
, so you'd get the result "20" (At least on a regular 32bit platform. On others sizeof(int)
might differ)
To return to your problem:
It seems like, that what you want to know is the length of the string which is contained inside your array and not the total array size.
By definition C-Strings have to be terminated with a trailing '\0' (0-Byte). So to get the appropriate length of the string contained within your array, you have to first terminate the string, so that you can tell when it's finished. Otherwise there would be now way to know.
All standard functions build upon this definition, so if you call strlen
to retrieve
the str ing len gth, it will iterate through the given array until it finds the first 0-byte, which in your case would be the very first element.
Another thing you might need to know that only because you don't fill the remaining elements of your char[7]
with a value, they actually do contain random undefined values.
Hope that helped.
Here's a quick, admittedly butchered response, but in a sentence:
1NF : Your table is organized as an unordered set of data, and there are no repeating columns.
2NF: You don't repeat data in one column of your table because of another column.
3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.
For more detail, see wikipedia...
For ones who wanna use scikit-learn, you can use
from sklearn.preprocessing import normalize
x = [1,2,3,4]
normalize([x]) # array([[0.18257419, 0.36514837, 0.54772256, 0.73029674]])
normalize([x], norm="l1") # array([[0.1, 0.2, 0.3, 0.4]])
normalize([x], norm="max") # array([[0.25, 0.5 , 0.75, 1.]])
If I understand your question correctly, is it the fact that the required
attribute appears to have default behaviour in Safari that's confusing you? If so, see: http://w3c.github.io/html/sec-forms.html#the-required-attribute
required
is not a custom attribute in HTML 5. It's defined in the spec, and is used in precisely the way you're presently using it.
EDIT: Well, not precisely. As ms2ger has pointed out, the required
attribute is a boolean attribute, and here's what the HTML 5 spec has to say about those:
Note: The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
See: http://w3c.github.io/html/infrastructure.html#sec-boolean-attributes
This approach works for me in Node.js, Is there any problem with this one?
File 'include.js':
fs = require('fs');
File 'main.js':
require('./include.js');
fs.readFile('./file.json', function (err, data) {
if (err) {
console.log('ERROR: file.json not found...')
} else {
contents = JSON.parse(data)
};
})
You have installed the library in a non-standard location ($HOME/zlib/
). That means the compiler will not know where your header files are and you need to tell the compiler that.
You can add a path to the list that the compiler uses to search for header files by using the -I
(upper-case i) option.
Also note that the LD_LIBRARY_PATH
is for the run-time linker and loader, and is searched for dynamic libraries when attempting to run an application. To add a path for the build-time linker use the -L
option.
All-together the command line should look like
$ c++ -I$HOME/zlib/include some_file.cpp -L$HOME/zlib/lib -lz
A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:
.clear { height: 50px; width: 25px; }
Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both;
attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:
.clear { clear: both; }
It looks like you're specifying both the EXE and its first argument in a single string e.g; '"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode'
. This won't work. In general you invoke a native command that has a space in its path like so:
& "c:\some path with spaces\foo.exe" <arguments go here>
That is &
expects to be followed by a string that identifies a command: cmdlet, function, native exe relative or absolute path.
Once you get just this working:
& "c:\some path with spaces\foo.exe"
Start working on quoting of the arguments as necessary. Although it looks like your arguments should be just fine (no spaces, no other special characters interpreted by PowerShell).
The preferred method for passing an array of values to a stored procedure in SQL server is to use table valued parameters.
First you define the type like this:
CREATE TYPE UserList AS TABLE ( UserID INT );
Then you use that type in the stored procedure:
create procedure [dbo].[get_user_names]
@user_id_list UserList READONLY,
@username varchar (30) output
as
select last_name+', '+first_name
from user_mstr
where user_id in (SELECT UserID FROM @user_id_list)
So before you call that stored procedure, you fill a table variable:
DECLARE @UL UserList;
INSERT @UL VALUES (5),(44),(72),(81),(126)
And finally call the SP:
EXEC dbo.get_user_names @UL, @username OUTPUT;
You can also, if you like use socket id to manage your player list like this.
io.on('connection', function(socket){
socket.on('disconnect', function() {
console.log("disconnect")
for(var i = 0; i < onlineplayers.length; i++ ){
if(onlineplayers[i].socket === socket.id){
console.log(onlineplayers[i].code + " just disconnected")
onlineplayers.splice(i, 1)
}
}
io.emit('players', onlineplayers)
})
socket.on('lobby_join', function(player) {
if(player.available === false) return
var exists = false
for(var i = 0; i < onlineplayers.length; i++ ){
if(onlineplayers[i].code === player.code){
exists = true
}
}
if(exists === false){
onlineplayers.push({
code: player.code,
socket:socket.id
})
}
io.emit('players', onlineplayers)
})
socket.on('lobby_leave', function(player) {
var exists = false
for(var i = 0; i < onlineplayers.length; i++ ){
if(onlineplayers[i].code === player.code){
onlineplayers.splice(i, 1)
}
}
io.emit('players', onlineplayers)
})
})
I seem to remember that Internet Explorer gets confused if the accept-charset encoding doesn't match the encoding specified in the content-type header. In your example, you claim the document is sent as UTF-8, but want form submits in ISO-8859-1. Try matching those and see if that solves your problem.
This is the shortest way.
var now = new Date().toLocaleTimeString();
console.log(now)
Here is also a way through string manipulation that was not mentioned.
var now = new Date()
console.log(now.toString().substr(16,8))
The easiest way is to convert to a date:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.
I would be inclined to use the following, just out of habit:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
Sometimes you don't want to create a html e-mail. I solved the problem this way :
Replace \n by \t\n
The tab will not be shown, but the newline will work.
I decide to add on, rather than posting my solution to another post. Below are the solution that I build, may not be perfect, but so far the output are good.
Important: it will pass through all the points!
If you have any idea, to make it better, please share to me. Thanks.
Here are the comparison of before after:
Save this code to HTML to test it out.
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<canvas id="myCanvas" width="1200" height="700" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>_x000D_
<script>_x000D_
var cv = document.getElementById("myCanvas");_x000D_
var ctx = cv.getContext("2d");_x000D_
_x000D_
function gradient(a, b) {_x000D_
return (b.y-a.y)/(b.x-a.x);_x000D_
}_x000D_
_x000D_
function bzCurve(points, f, t) {_x000D_
//f = 0, will be straight line_x000D_
//t suppose to be 1, but changing the value can control the smoothness too_x000D_
if (typeof(f) == 'undefined') f = 0.3;_x000D_
if (typeof(t) == 'undefined') t = 0.6;_x000D_
_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(points[0].x, points[0].y);_x000D_
_x000D_
var m = 0;_x000D_
var dx1 = 0;_x000D_
var dy1 = 0;_x000D_
_x000D_
var preP = points[0];_x000D_
for (var i = 1; i < points.length; i++) {_x000D_
var curP = points[i];_x000D_
nexP = points[i + 1];_x000D_
if (nexP) {_x000D_
m = gradient(preP, nexP);_x000D_
dx2 = (nexP.x - curP.x) * -f;_x000D_
dy2 = dx2 * m * t;_x000D_
} else {_x000D_
dx2 = 0;_x000D_
dy2 = 0;_x000D_
}_x000D_
ctx.bezierCurveTo(preP.x - dx1, preP.y - dy1, curP.x + dx2, curP.y + dy2, curP.x, curP.y);_x000D_
dx1 = dx2;_x000D_
dy1 = dy2;_x000D_
preP = curP;_x000D_
}_x000D_
ctx.stroke();_x000D_
}_x000D_
_x000D_
// Generate random data_x000D_
var lines = [];_x000D_
var X = 10;_x000D_
var t = 40; //to control width of X_x000D_
for (var i = 0; i < 100; i++ ) {_x000D_
Y = Math.floor((Math.random() * 300) + 50);_x000D_
p = { x: X, y: Y };_x000D_
lines.push(p);_x000D_
X = X + t;_x000D_
}_x000D_
_x000D_
//draw straight line_x000D_
ctx.beginPath();_x000D_
ctx.setLineDash([5]);_x000D_
ctx.lineWidth = 1;_x000D_
bzCurve(lines, 0, 1);_x000D_
_x000D_
//draw smooth line_x000D_
ctx.setLineDash([0]);_x000D_
ctx.lineWidth = 2;_x000D_
ctx.strokeStyle = "blue";_x000D_
bzCurve(lines, 0.3, 1);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
This is working well for me
public static class TaskHelper
{
public static void RunTaskSynchronously(this Task t)
{
var task = Task.Run(async () => await t);
task.Wait();
}
public static T RunTaskSynchronously<T>(this Task<T> t)
{
T res = default(T);
var task = Task.Run(async () => res = await t);
task.Wait();
return res;
}
}
Tuple can only allow adding tuple
to it. The best way to do it is:
mytuple =(u'2',)
mytuple +=(new.id,)
I tried the same scenario with the below data it all seems to be working fine.
>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')
Here's how to fix this error when launching Eclipse:
Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.
Go and install latest JDK
Make sure you have installed 64 bit Eclipse
Use this
DELETE FROM `articles`, `comments`
USING `articles`,`comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
or
DELETE `articles`, `comments`
FROM `articles`, `comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
In my case, Jay D is right. I have to add this before the call.
$.ajaxSetup({
async: false
});
In my previous code, I have this:
var jsonData= (function() {
var result;
$.ajax({
type:'GET',
url:'data.txt',
dataType:'json',
async:false,
success:function(data){
result = data;
}
});
return result;
})();
alert(JSON.stringify(jsonData));
It works find. Then I change to
var jsonData= (function() {
var result;
$.getJSON('data.txt', {}, function(data){
result = data;
});
return result;
})();
alert(JSON.stringify(jsonData));
The alert is undefined.
If I add those three lines, the alert shows the data again.
$.ajaxSetup({
async: false
});
var jsonData= (function() {
var result;
$.getJSON('data.txt', {}, function(data){
result = data;
});
return result;
})();
alert(JSON.stringify(jsonData));
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Now from docker client you can simply search your private registry directly without using the HTTP APIs or any extra tools:
e.g. searching for centos image:
docker search localhost:5000/centos
You can use the following tag
<body oncontextmenu="return false"><!-- your page body hear--></body>
OR you can create your own menu when right click:
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
The IPAddress Java library can accomplish what you are describing here.
IPv6 addresses are 16 bytes. Using that library, if you are starting with a 16-byte array you can construct the IPv6 address object:
IPv6Address addr = new IPv6Address(bytes); //bytes is byte[16]
From there you can check if the address is IPv4 mapped, IPv4 compatible, IPv4 translated, and so on (there are many possible ways IPv6 represents IPv4 addresses). In most cases, if an IPv6 address represents an IPv4 address, the ipv4 address is in the lower 4 bytes, and so you can get the derived IPv4 address as follows. Afterwards, you can convert back to bytes, which will be just 4 bytes for IPv4.
if(addr.isIPv4Compatible() || addr.isIPv4Mapped()) {
IPv4Address derivedIpv4Address = addr.getEmbeddedIPv4Address();
byte ipv4Bytes[] = derivedIpv4Address.getBytes();
...
}
The javadoc is available at the link.
I dislike "Don't" answers, but... don't.
make
's variables are global and are supposed to be evaluated during makefile's "parsing" stage, not during execution stage.
In this case, as long as the variable local to a single target, follow @nobar's answer and make it a shell variable.
Target-specific variables, too, are considered harmful by other make implementations: kati, Mozilla pymake. Because of them, a target can be built differently depending on if it's built standalone, or as a dependency of a parent target with a target-specific variable. And you won't know which way it was, because you don't know what is already built.
You can read database value in to a variable and then set the variable as follows
$app_container->assign('checked_flag', $db_data=='0' ? '' : 'checked');
And in html you can just use the checked_flag variable as follows
<input type="checkbox" id="chk_test" name="chk_test" value="1" {checked_flag}>
What regex engine are you using? Most of them will support the following expression:
\{\d+:\d+\}
The \d
is actually shorthand for [0-9]
, but the important part is the addition of +
which means "one or more".
You should never use * + !important
. What if you want to change font in some parts your HTML document? You should always use body without important. Use !important
only if there is no other option.
My favorite...
Url.Content(Request.Url.PathAndQuery)
or just...
Url.Action()
Or, just as easy:
string assyGuid = Assembly.GetExecutingAssembly().GetCustomAttribute<GuidAttribute>().Value.ToUpper();
It works for me...
To get the latest tag only on the current branch/tag name that prefixes with current branch, I had to execute the following
BRANCH=`git rev-parse --abbrev-ref HEAD` && git describe --tags --abbrev=0 $BRANCH^ | grep $BRANCH
Branch master:
git checkout master
BRANCH=`git rev-parse --abbrev-ref HEAD` && git describe --tags
--abbrev=0 $BRANCH^ | grep $BRANCH
master-1448
Branch custom:
git checkout 9.4
BRANCH=`git rev-parse --abbrev-ref HEAD` && git describe --tags
--abbrev=0 $BRANCH^ | grep $BRANCH
9.4-6
And my final need to increment and get the tag +1 for next tagging.
BRANCH=`git rev-parse --abbrev-ref HEAD` && git describe --tags --abbrev=0 $BRANCH^ | grep $BRANCH | awk -F- '{print $NF}'
When the other solutions did not work for you (Changing JVM version on Compiler settings and adding jvmTarget
into your build.gradle
), because of your .iml
files trying to force their configurations you can change the target platform from Project Settings.
File > Project Structure
Facets
under Project Settings
+
buttonTarget Platform
to JVM 1.8
(also it's better to check Use project settings
option)First, you need to have a clear understanding of scope
and behaviour of this
keyword in the context of scope
.
this
& scope
:
there are two types of scope in javascript. They are :
1) Global Scope
2) Function Scope
in short, global scope refers to the window object.Variables declared in a global scope are accessible from anywhere.On the other hand function scope resides inside of a function.variable declared inside a function cannot be accessed from outside world normally.this
keyword in global scope refers to the window object.this
inside function also refers to the window object.So this
will always refer to the window until we find a way to manipulate this
to indicate a context of our own choosing.
--------------------------------------------------------------------------------
- -
- Global Scope -
- ( globally "this" refers to window object) -
- -
- function outer_function(callback){ -
- -
- // outer function scope -
- // inside outer function"this" keyword refers to window object - -
- callback() // "this" inside callback also refers window object -
- } -
- -
- function callback_function(){ -
- -
- // function to be passed as callback -
- -
- // here "THIS" refers to window object also -
- -
- } -
- -
- outer_function(callback_function) -
- // invoke with callback -
--------------------------------------------------------------------------------
Different ways to manipulate this
inside callback functions:
Here I have a constructor function called Person. It has a property called name
and four method called sayNameVersion1
,sayNameVersion2
,sayNameVersion3
,sayNameVersion4
. All four of them has one specific task.Accept a callback and invoke it.The callback has a specific task which is to log the name property of an instance of Person constructor function.
function Person(name){
this.name = name
this.sayNameVersion1 = function(callback){
callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
callback()
}
this.sayNameVersion3 = function(callback){
callback.call(this)
}
this.sayNameVersion4 = function(callback){
callback.apply(this)
}
}
function niceCallback(){
// function to be used as callback
var parentObject = this
console.log(parentObject)
}
Now let's create an instance from person constructor and invoke different versions of sayNameVersionX
( X refers to 1,2,3,4 ) method with niceCallback
to see how many ways we can manipulate the this
inside callback to refer to the person
instance.
var p1 = new Person('zami') // create an instance of Person constructor
What bind do is to create a new function with the this
keyword set to the provided value.
sayNameVersion1
and sayNameVersion2
use bind to manipulate this
of the callback function.
this.sayNameVersion1 = function(callback){
callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
callback()
}
first one bind this
with callback inside the method itself.And for the second one callback is passed with the object bound to it.
p1.sayNameVersion1(niceCallback) // pass simply the callback and bind happens inside the sayNameVersion1 method
p1.sayNameVersion2(niceCallback.bind(p1)) // uses bind before passing callback
The first argument
of the call
method is used as this
inside the function that is invoked with call
attached to it.
sayNameVersion3
uses call
to manipulate the this
to refer to the person object that we created, instead of the window object.
this.sayNameVersion3 = function(callback){
callback.call(this)
}
and it is called like the following :
p1.sayNameVersion3(niceCallback)
Similar to call
, first argument of apply
refers to the object that will be indicated by this
keyword.
sayNameVersion4
uses apply
to manipulate this
to refer to person object
this.sayNameVersion4 = function(callback){
callback.apply(this)
}
and it is called like the following.Simply the callback is passed,
p1.sayNameVersion4(niceCallback)
This is the correct way:
You should declare the length of the array after "="
Veicle[] cars = new Veicle[N];
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
Based on this viedo: VB.net-Auto generate row number to datagridview in windows application-winforms, you can set the DataSource and this code puts the rows numbers, works like a charm.
private void DataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// Add row number
(sender as DataGridView).Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex+1).ToString();
}
I just encountered a case of needing to revert just one file to previous revision, right after I had done commit and push. Shorthand syntax for specifying these revisions isn't covered by the other answers, so here's command to do that
hg revert path/to/file -r-2
That -2
will revert to the version before last commit, using -1
would just revert current uncommitted changes.
Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).
Try this:
@keyframe in {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframe out {
from {
transform: rotate(360deg);
}
to {
transform: rotate(0deg);
}
}
supported in Firefox 5+, IE 10+, Chrome, Safari 4+, Opera 12+
A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.
An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478
(1) Set the tabindex
attribute:
<div id="mydiv" tabindex="0" />
(2) Bind to keydown:
$('#mydiv').on('keydown', function(event) {
//console.log(event.keyCode);
switch(event.keyCode){
//....your actions for the keys .....
}
});
To set the focus on start:
$(function() {
$('#mydiv').focus();
});
To remove - if you don't like it - the div
focus border, set outline: none
in the CSS.
See the table of keycodes for more keyCode
possibilities.
All of the code assuming you use jQuery.
#Using Array.prototype.includes()
method to remove duplicates:
(function() {
const array = [1, 1, 2, 2, 3, 5, 5, 2];
let uniqueValues = [];
array.map(num => {
if (Number.isInteger(num) && !uniqueValues.includes(num)) {
uniqueValues.push(num)
}
});
console.log(uniqueValues)
}());
I think zeroclipboard is great. this version work with latest Flash 11: http://www.itjungles.com/javascript/javascript-easy-cross-browser-copy-to-clipboard-solution.
Use message tracing/logging.
You can always use Fiddler to see the HTTP requests and response.
Use System.Net tracing.
Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator
It can also happen when drawing a new (other) table. I solved this by first removing the previous table:
$("#prod_tabel_ph").remove();
Warning, bug in Android 3 (Honeycomb) and Android 4.0 (Ice Cream Sandwich)
Androids versions: 3.1 - 4.04 have a bug, that setTextSize() inside of TextView works only for the first time (first invocation).
The bug is described in Issue 22493: TextView height bug in Android 4.0 and Issue 17343: button's height and text does not return to its original state after increase and decrease the text size on HoneyComb.
The workaround is to add a newline character to text assigned to TextView before changing size:
final String DOUBLE_BYTE_SPACE = "\u3000";
textView.append(DOUBLE_BYTE_SPACE);
I use it in my code as follow:
final String DOUBLE_BYTE_SPACE = "\u3000";
AutoResizeTextView textView = (AutoResizeTextView) view.findViewById(R.id.aTextView);
String fixString = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1
&& android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
fixString = DOUBLE_BYTE_SPACE;
}
textView.setText(fixString + "The text" + fixString);
I add this "\u3000" character on left and right of my text, to keep it centered. If you have it aligned to left then append to the right only. Of course it can be also embedded with AutoResizeTextView widget, but I wanted to keep fix code outside.
You can mark source directory as a source root like so:
You can use these following lines in your main urls.py
you can add the text in the quotes to be displayed
To replace the text Django admin use admin.site.site_header = ""
To replace the text Site Administration use admin.site.site_title = ""
To replace the site name you can use admin.site.index_title = ""
To replace the url of the view site button you can use admin.site.site_url = ""
EDIT: don't use vc80 / Visual Studio 2005, but Visual Studio 2008 / vc90 versions of the CGAL library (maybe from here).
You could also compile with /Z7, so the pdb doesn't need to be used, or remove the /DEBUG linker option if you do not have .pdb files for the objects you are linking.
You can try to use this function if you need to round down to a specific number of decimal places
function roundDown(number, decimals) {
decimals = decimals || 0;
return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) );
}
examples
alert(roundDown(999.999999)); // 999
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990
Of course ios7 prohibits creating fake locations on real device.
For testing purpose there are two approches:
1) while device is connected to xcode, use the simulator and let it play a gpx track.
2) for real world testing, not connected to simu, one possibility is that your app, has a special modus built in, where you set it to "playback" mode. In that mode the app has to create the locations itself, using a timer of 1s, and creating a new CLLocation object.
3) A third possibility is described here: https://blackpixel.com/writing/2013/05/simulating-locations-with-xcode.html
The examples in the Python documentation show how to write Unicode CSV files: http://docs.python.org/2/library/csv.html#examples
(can't copy the code here because it's protected by copyright)
I found another relatively easy solution for your question.
As you can see from the FragmentPagerAdapter source code, the fragments managed by FragmentPagerAdapter
store in the FragmentManager
under the tag generated using:
String tag="android:switcher:" + viewId + ":" + index;
The viewId
is the container.getId()
, the container
is your ViewPager
instance. The index
is the position of the fragment. Hence you can save the object id to the outState
:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("viewpagerid" , mViewPager.getId() );
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
if (savedInstanceState != null)
viewpagerid=savedInstanceState.getInt("viewpagerid", -1 );
MyFragmentPagerAdapter titleAdapter = new MyFragmentPagerAdapter (getSupportFragmentManager() , this);
mViewPager = (ViewPager) findViewById(R.id.pager);
if (viewpagerid != -1 ){
mViewPager.setId(viewpagerid);
}else{
viewpagerid=mViewPager.getId();
}
mViewPager.setAdapter(titleAdapter);
If you want to communicate with this fragment, you can get if from FragmentManager
, such as:
getSupportFragmentManager().findFragmentByTag("android:switcher:" + viewpagerid + ":0")
Your main fun will call firstFun then on complete of it your next fun will call.
async firstFunction() {
const promise = new Promise((resolve, reject) => {
for (let i = 0; i < 5; i++) {
// do something
console.log(i);
if (i == 4) {
resolve(i);
}
}
});
const result = await promise;
}
second() {
this.firstFunction().then( res => {
// third function call do something
console.log('Gajender here');
});
}
Generic Object Oriented Solution
For people like me that use frameworks like angular that don't allow manipulating DOM directly, I created a function that takes a string and returns an array of url
/plainText
objects that can be used to create any UI representation that you want.
URL regex
For URL matching I used (slightly adapted) h0mayun
regex: /(?:(?:https?:\/\/)|(?:www\.))[^\s]+/g
My function also drops punctuation characters from the end of a URL like .
and ,
that I believe more often will be actual punctuation than a legit URL ending (but it could be! This is not rigorous science as other answers explain well) For that I apply the following regex onto matched URLs /^(.+?)([.,?!'"]*)$/
.
Typescript code
export function urlMatcherInText(inputString: string): UrlMatcherResult[] {
if (! inputString) return [];
const results: UrlMatcherResult[] = [];
function addText(text: string) {
if (! text) return;
const result = new UrlMatcherResult();
result.type = 'text';
result.value = text;
results.push(result);
}
function addUrl(url: string) {
if (! url) return;
const result = new UrlMatcherResult();
result.type = 'url';
result.value = url;
results.push(result);
}
const findUrlRegex = /(?:(?:https?:\/\/)|(?:www\.))[^\s]+/g;
const cleanUrlRegex = /^(.+?)([.,?!'"]*)$/;
let match: RegExpExecArray;
let indexOfStartOfString = 0;
do {
match = findUrlRegex.exec(inputString);
if (match) {
const text = inputString.substr(indexOfStartOfString, match.index - indexOfStartOfString);
addText(text);
var dirtyUrl = match[0];
var urlDirtyMatch = cleanUrlRegex.exec(dirtyUrl);
addUrl(urlDirtyMatch[1]);
addText(urlDirtyMatch[2]);
indexOfStartOfString = match.index + dirtyUrl.length;
}
}
while (match);
const remainingText = inputString.substr(indexOfStartOfString, inputString.length - indexOfStartOfString);
addText(remainingText);
return results;
}
export class UrlMatcherResult {
public type: 'url' | 'text'
public value: string
}
SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
By way of illustration here are few calls and their appropriate home with commentary.
getUser(User);
This is a rest operation as you are accessing a resource (data).
switchCategory(User, OldCategory, NewCategory)
REST permits many different data formats where as SOAP only permits XML. While this may seem like it adds complexity to REST because you need to handle multiple formats, in my experience it has actually been quite beneficial. JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to it’s support for JSON.
With the last update of Androd Studio I have two versions of the IDE's launcher
One is called studio.exe and the other studio64.exe they are both on:
C:\Users\myUserName\AppData\Local\Android\android-studio\bin
You have to launch the one that matches your Java version 64 or 32 bit
I don't know if it helps, but using jQuery, to hide an email address, I did :
$(function() {
// planque l'adresse mail
var mailSplitted
= ['mai', 'to:mye', 'mail@', 'addre', 'ss.fr'];
var link = mailSplitted.join('');
link = '<a href="' + link + '"</a>';
$('mytag').wrap(link);
});
I hope it helps.
There should be a script named mvim in the root of the .bz2 file. Copy this somewhere into your $PATH ( /usr/local/bin would be good ) and you should be sorted.
Modern BASH has support for regular expressions:
while read -r line; do
if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
echo "${BASH_REMATCH[1]}"
fi
done
You don't need awk for this...
echo aaa0.bbb.ccc | cut -d. -f1
cut -d. -f1 <<< aaa0.bbb.ccc
echo aaa0.bbb.ccc | { IFS=. read a _ ; echo $a ; }
{ IFS=. read a _ ; echo $a ; } <<< aaa0.bbb.ccc
x=aaa0.bbb.ccc; echo ${x/.*/}
Heavier options:
sed:
echo aaa0.bbb.ccc | sed 's/\..*//'
sed 's/\..*//' <<< aaa0.bbb.ccc
awk:
echo aaa0.bbb.ccc | awk -F. '{print $1}'
awk -F. '{print $1}' <<< aaa0.bbb.ccc
What you could do, is to make sure to pass the parent form as the owner when showing the child form:
Form newForm = new ChildForm();
newForm.Show(this);
Then, in the child form, set up event handlers for the Activated
and Deactivate
events:
private void Form_Activated(object sender, System.EventArgs e)
{
if (this.Owner != null)
{
this.Owner.Enabled = false;
}
}
private void Form_Deactivate(object sender, System.EventArgs e)
{
if (this.Owner != null)
{
this.Owner.Enabled = true;
}
}
However, this will result in a truly wierd behaviour; while you will not be able to go back and interact with the parent form immediately, activating any other application will enable it, and then the user can interact with it.
If you want to make the child form modal, use ShowDialog
instead:
Form newForm = new ChildForm();
newForm.ShowDialog(this);
Different way of counting by using bisect module:
>>> from bisect import bisect
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> j.sort()
>>> b = 5
>>> index = bisect(j,b) #Find that index value
>>> print len(j)-index
3
Android complete source code for adding events and reminders with start and end time format.
/** Adds Events and Reminders in Calendar. */
private void addReminderInCalendar() {
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(true) + "events");
ContentResolver cr = getContentResolver();
TimeZone timeZone = TimeZone.getDefault();
/** Inserting an event in calendar. */
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.TITLE, "Sanjeev Reminder 01");
values.put(CalendarContract.Events.DESCRIPTION, "A test Reminder.");
values.put(CalendarContract.Events.ALL_DAY, 0);
// event starts at 11 minutes from now
values.put(CalendarContract.Events.DTSTART, cal.getTimeInMillis() + 11 * 60 * 1000);
// ends 60 minutes from now
values.put(CalendarContract.Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.HAS_ALARM, 1);
Uri event = cr.insert(EVENTS_URI, values);
// Display event id
Toast.makeText(getApplicationContext(), "Event added :: ID :: " + event.getLastPathSegment(), Toast.LENGTH_SHORT).show();
/** Adding reminder for event added. */
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(true) + "reminders");
values = new ContentValues();
values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
values.put(CalendarContract.Reminders.METHOD, Reminders.METHOD_ALERT);
values.put(CalendarContract.Reminders.MINUTES, 10);
cr.insert(REMINDERS_URI, values);
}
/** Returns Calendar Base URI, supports both new and old OS. */
private String getCalendarUriBase(boolean eventUri) {
Uri calendarURI = null;
try {
if (android.os.Build.VERSION.SDK_INT <= 7) {
calendarURI = (eventUri) ? Uri.parse("content://calendar/") : Uri.parse("content://calendar/calendars");
} else {
calendarURI = (eventUri) ? Uri.parse("content://com.android.calendar/") : Uri
.parse("content://com.android.calendar/calendars");
}
} catch (Exception e) {
e.printStackTrace();
}
return calendarURI.toString();
}
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
I know this is a two year old question, but this is a quick answer for those searching for a 'how to'.
If you don't want to have to put quotes around anything you can simply write a block of text to a file, and escape variables you want to export as text (for instance for use in a script) and not escape one's you want to export as the value of the variable.
#!/bin/bash
FILE_NAME="test.txt"
VAR_EXAMPLE="\"string\""
cat > ${FILE_NAME} << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} in ${FILE_NAME}
EOF
Will write "${VAR_EXAMPLE}="string" in test.txt" into test.txt
This can also be used to output blocks of text to the console with the same rules by omitting the file name
#!/bin/bash
VAR_EXAMPLE="\"string\""
cat << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} to console
EOF
Will output "${VAR_EXAMPLE}="string" to console" to the console
I have found this guide from VP https://knowhow.visual-paradigm.com/technical-support/running-vp-in-android-studio/ created on September 8, 2015.
Good to know - it is possible to integrate VP into Android studio (in my case 1.5.1) now. Do not forget to backup your Android Studio settings (you can find them in Users%userName/.AndroidStudioX.X on Windows) ahead of installation.
I was trying to make it work, but created vp project did not contain any diagrams. Maybe someone else will have more luck.
I was using this manual http://www.visual-paradigm.com/support/documents/vpuserguide/2381/2385/66578_creatingauml.html to make Visual Paradigm working in Android studio, but action in 2. did not invoke dialogue in 3. So I Have asked Visual Paradigm support for help and they replied that Android Studio integration is not supported right now.
Reply from Visual paradigm reply from Apr 17 2015:
Thank you for your inquiry and I'm very sorry that at the moment we only support integrate with the standard IntelliJ IDEA, but not integrate with the Android Studio. We may consider to support it in our future release, and I'll keep you post once there any update on this topics. Feel free to contact me for any questions and wish you have a good day!
This post was deleted, so I will try to make it more clear.
As such I am considering previous answers as misleading and not useful. Therefore I thing that it is important for others to know that, before they lose their time trying to make it working.
There is always parsing by hand
>>> import re
>>> ts = ['00:00:00,000', '00:00:10,000', '00:01:04,000', '01:01:09,000']
>>> for t in ts:
... times = map(int, re.split(r"[:,]", t))
... print t, times[0]*3600+times[1]*60+times[2]+times[3]/1000.
...
00:00:00,000 0.0
00:00:10,000 10.0
00:01:04,000 64.0
01:01:09,000 3669.0
>>>
Though I wouldn't consider this as a valid answer to OP's question, I'd still emphasize that the best way to deploy Jenkins (and likely most if not all libraries/packages/software) on Ubuntu is to leverage aptitude (or apt-get) management system.
It is documented here: https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+Ubuntu (notice that if you want to use the LTS build, hit on this repo http://pkg.jenkins-ci.org/debian-stable/)
So if by any chance you actually did use this approach, you'd simply do a apt-get upgrade jenkins
What about sign bit?
For example:
Hex value 0xADFE74A5
represents unsigned 2919134373
and signed -1375832923
.
Currect value must be signed (sign bit = 1) but python converts it as unsigned and we have an incorrect hash value after translation from 64 to 32 bit.
Be careful using:
def hash32(value):
return hash(value) & 0xffffffff
class Test {
public function yo() {
return 'yoes';
}
}
$var = 'Test';
$obj = new $var();
echo $obj->yo(); //yoes
The logging
module has everything you could want. It may seem excessive at first, but only use the parts you need. I'd recommend using logging.basicConfig
to toggle the logging level to stderr
and the simple log methods, debug
, info
, warning
, error
and critical
.
import logging, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logging.debug('A debug message!')
logging.info('We processed %d records', len(processed_records))
Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:
$('td').click(function(){
var row_index = $(this).closest("tr").index();
var col_index = $(this).index();
});
If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:
First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.
package financialdocuments;
import java.lang.*;
import java.util.HashMap;
/**
*
* @author Administrator
*/
public class Document {
private int document_number;
private boolean document_type;
private boolean document_status;
private StringBuilder document_date;
private StringBuilder document_statement;
private int document_code_number;
private int document_employee_number;
private int document_client_number;
private String document_employee_name;
private String document_client_name;
private long document_amount;
private long document_payment_amount;
HashMap<Integer,Activity> document_activity_hashmap;
public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){
document_date = new StringBuilder(dd);
document_date.setLength(10);
document_date.setCharAt(4, '.');
document_date.setCharAt(7, '.');
document_statement = new StringBuilder(dst);
document_statement.setLength(50);
document_number = dn;
document_type = dt;
document_status = ds;
document_code_number = dcon;
document_employee_number = den;
document_client_number = dcln;
document_amount = da;
document_employee_name = dena;
document_client_name = dcna;
document_payment_amount = 0;
document_activity_hashmap = new HashMap<>();
}
public Document(int dn,boolean dt,boolean ds, long dpa){
document_number = dn;
document_type = dt;
document_status = ds;
document_payment_amount = dpa;
document_activity_hashmap = new HashMap<>();
}
// Print document information
public void printDocumentInformation (){
System.out.println("Document Number:" + document_number);
System.out.println("Document Date:" + document_date);
System.out.println("Document Type:" + document_type);
System.out.println("Document Status:" + document_status);
System.out.println("Document Statement:" + document_statement);
System.out.println("Document Code Number:" + document_code_number);
System.out.println("Document Client Number:" + document_client_number);
System.out.println("Document Employee Number:" + document_employee_number);
System.out.println("Document Amount:" + document_amount);
System.out.println("Document Payment Amount:" + document_payment_amount);
System.out.println("Document Employee Name:" + document_employee_name);
System.out.println("Document Client Name:" + document_client_name);
}
}
Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.
package financialdocuments;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class DataBase {
/**
*
* Defining parameters and strings that are going to be used
*
*/
//Connection connect;
// Tables which their datas are extracted at the beginning
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;
// Resultset Returned by queries
private ResultSet result;
// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
public DataBase(){
code_table = new HashMap<>();
activity_table = new HashMap<>();
client_table = new HashMap<>();
employee_table = new HashMap<>();
Initialize();
}
/**
* Set variables and objects for this class.
*/
private void Initialize(){
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Get tables' information
selectCodeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printCodeTableQueryArray();
selectActivityTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printActivityTableQueryArray();
selectClientTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printClientTableQueryArray();
selectEmployeeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printEmployeeTableQueryArray();
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
/**
* Write Queries
* @param s
* @return
*/
public boolean insertQuery(String s){
boolean ret = false;
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Set tables' information
try {
Statement st = connect.createStatement();
int val = st.executeUpdate(s);
if(val==1){
System.out.print("Successfully inserted value");
ret = true;
}
else{
System.out.print("Unsuccessful insertion");
ret = false;
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
return ret;
}
/**
* Query needed to get code table's data
* @param c
* @return
*/
private void selectCodeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM code;");
while (res.next()) {
int id = res.getInt("code_number");
String msg = res.getString("code_statement");
code_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printCodeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectActivityTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM activity;");
while (res.next()) {
int id = res.getInt("activity_number");
String msg = res.getString("activity_statement");
activity_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printActivityTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get client table's data
* @param c
* @return
*/
private void selectClientTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM client;");
while (res.next()) {
int id = res.getInt("client_number");
String msg = res.getString("client_full_name");
client_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printClientTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectEmployeeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee;");
while (res.next()) {
int id = res.getInt("employee_number");
String msg = res.getString("employee_full_name");
employee_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printEmployeeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
}
I hope this could be a little help.
The most portable solution I have found is the getconf
command:
getconf _NPROCESSORS_ONLN
This works on both Linux and Mac OS X. Another benefit of this over some of the other approaches is that getconf has been around for a long time. Some of the older Linux machines I have to do development on don't have the nproc
or lscpu
commands available, but they have getconf
.
Editor's note: While the getconf
utility is POSIX-mandated, the specific _NPROCESSORS_ONLN
and _NPROCESSORS_CONF
values are not.
That said, as stated, they work on Linux platforms as well as on macOS; on FreeBSD/PC-BSD, you must omit the leading _
.
This exact question is answered on mySql workbench-faq:
Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.
That means hover over an acronym in the mySql Workbench table editor.
I use both Clang and GCC, I find Clang has some useful warnings, but for my own ray-tracing benchmarks - its consistently 5-15% slower then GCC (take that with grain of salt of course, but attempted to use similar optimization flags for both).
So for now I use Clang static analysis and its warnings with complex macros: (though now GCC's warnings are pretty much as good - gcc4.8 - 4.9).
Some considerations:
***** - these areas are in active development and may soon be supported
in the "Ouput Window". you can usually do CTRL-ALT-O to make it visible. Or through menus using View->Output.
My default dir was system32 when starting CMD. I then created a batch file in that directory to change dir to the one I was after.
This caused me to always call that bat when starting CMD every time. So I made a reg file & put this inside:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"Autorun"="cd C:\\Users\\Me\\SomeFolder"
After saving it, I opened the file, clicked ok to merge with registry, and since then every time I open CMD, I get my dir
This regular expression handles floats as well
import re
re_float = re.compile(r'\d*\.?\d+')
You could also add a group to the expression that catches your weight units.
re_banana = re.compile(r'(?P<number>\d*\.?\d+)\s?(?P<uni>[a-zA-Z]+)')
You can access the named groups like this re_banana.match("200 kgm").group('number')
.
I think this should help you getting started.
Some times there are problems with funtion/features that do not interact with the DOM
try to change the value sharply and then assign the $scope
document.getElementById ("textWidget") value = "<NewVal>";
$scope.widget.title = "<NewVal>";