Do you need to rewind the buffer, perhaps?
Also, this might happen if the stride (in bytes) of the bitmap is greater than the row length in pixels * bytes/pixel. Make the length of bytes b.remaining() instead of size.
What is the value range? Is it 0 through 10? If so, then try:
SELECT REPLICATE('0',2-LEN(@t)) + CAST(@t AS VARCHAR)
That handles 0 through 9 as well as 10 through 99.
Now, tinyint can go up to the value of 255. If you want to handle > 99 through 255, then try this solution:
declare @t TINYINT
set @t =233
SELECT ISNULL(REPLICATE('0',2-LEN(@t)),'') + CAST(@t AS VARCHAR)
To understand the solution, the expression to the left of the + calculates the number of zeros to prefix to the string.
In case of the value 3, the length is 1. 2 - 1 is 1. REPLICATE Adds one zero. In case of the value 10, the length is 2. 2 - 2 is 0. REPLICATE Adds nothing. In the case of the value 100, the length is -1 which produces a NULL. However, the null value is handled and set to an empty string.
Now if you decide that because tinyint can contain up to 255 and you want your formatting as three characters, just change the 2-LEN to 3-LEN in the left expression and you're set.
select VALUE from TABLE1 where TIME =
(select max(TIME) from TABLE1 where DATE=
(select max(DATE) from TABLE1 where CRITERIA=CRITERIA))
I'll add my solution, even thought his thread is old. Maybe this will help someone anyway.
First, I need to generate the PDF. I use XeLaTeX for that:
xelatex test.tex
Now, ImageMagick and GraphicMagic both parse parameters from left to right, so the leftmost parameter, will be executed first. I ended up using this sequence for optimal processing:
gm convert -trim -transparent white -background transparent -density 1200x1200 -resize 25% test.pdf test.png
It gives nice graphics on transparent background, trimmed to what is actually on the page. The -density
and -resize
parameters, give a better granularity, and increase overall resolution.
I suggest checking if the density can be decreased for you. It'll cut down converting time.
fmin
and fmax
, of fminl
and fmaxl
could be preferred when comparing signed and unsigned integers - you can take advantage of the fact that the entire range of signed and unsigned numbers and you don't have to worry about integer ranges and promotions.
unsigned int x = 4000000000;
int y = -1;
int z = min(x, y);
z = (int)fmin(x, y);
I ran into this problem as well, and figured out that the problem is in the browser. When you refresh the browser is re-populating the form with the same values as before, ignoring the checked field. If you view source, you'll see the checked value is correct. Or put your cursor in your browser's URL field and hit enter. That will re-load the form from scratch.
Use java.text.Normalizer
to handle this for you.
string = Normalizer.normalize(string, Normalizer.Form.NFD);
// or Normalizer.Form.NFKD for a more "compatable" deconstruction
This will separate all of the accent marks from the characters. Then, you just need to compare each character against being a letter and throw out the ones that aren't.
string = string.replaceAll("[^\\p{ASCII}]", "");
If your text is in unicode, you should use this instead:
string = string.replaceAll("\\p{M}", "");
For unicode, \\P{M}
matches the base glyph and \\p{M}
(lowercase) matches each accent.
Thanks to GarretWilson for the pointer and regular-expressions.info for the great unicode guide.
Parse to your string to a decimal first.
Hope this helps:
- (void)textViewDidChange:(UITextView *)textView {
CGSize textSize = textview.contentSize;
if (textSize != textView.frame.size)
textView.frame.size = textSize;
}
same as adamb but I would add a dynamic variable num
num = $('.menuFlotante').offset().top;
to get the exact offset or position inside the window to avoid finding the right position.
$(window).bind('scroll', function() {
if ($(window).scrollTop() > num) {
$('.menu').addClass('fixed');
}
else {
num = $('.menuFlotante').offset().top;
$('.menu').removeClass('fixed');
}
});
The simplest solution is create a JavaScript function and call it for the Ajax success
callback.
function callServerAsync(){
$.ajax({
url: '...',
success: function(response) {
successCallback(response);
}
});
}
function successCallback(responseObj){
// Do something like read the response and show data
alert(JSON.stringify(responseObj)); // Only applicable to JSON response
}
function foo(callback) {
$.ajax({
url: '...',
success: function(response) {
return callback(null, response);
}
});
}
var result = foo(function(err, result){
if (!err)
console.log(result);
});
Semicolons can be used to one line two or more commands. They don't have to be used, but they aren't restricted.
The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block.
http://www.tutorialspoint.com/python/python_basic_syntax.htm
if A:
will prove false if A is 0, False, empty string, empty list or None, which can lead to undesired results.
Most of the methods explained here did not solved the problem for me.
Finally, I fixed the problem by applying the following steps:
1. Close Visual Studio.
2. Delete all the contents in the bin folders of each project.
3. Open solution and rebuild.
Hope this helps.
VSCode comes with in-built color themes which can be used to change the colors of the editor and the terminal.
ctrl+k+t
in windows/ubuntu or cmd+k+t
on mac.ctrl+shift+p
in windows/ubuntu or cmd+shift+p
on mac and type color
. Select preferences: color theme
from the options, to select your favourite color.category:themes
to install your favourite themes. (If you need to sort the themes by installs search category:themes @sort:installs
)Edit - for manually editing colors in terminal
VSCode team have removed customizing colors from user settings page. Currently using the themes is the only way to customize terminal colors in VSCode. For more information check out issue #6766
Hosting a nodejs site through apache can be organized with apache proxy module.
It's better to start nodejs server on localhost with default port 1337
Enable proxy with a command:
sudo a2enmod proxy proxy_http
Do not enable proxying with ProxyRequests until you have secured your server. Open proxy servers are dangerous both to your network and to the Internet at large. Setting ProxyRequests to Off does not disable use of the ProxyPass directive.
Configure /etc/apche2/sites-availables with
<VirtualHost *:80>
ServerAdmin [email protected]
ServerName site.com
ServerAlias www.site.com
ProxyRequests off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
<Location />
ProxyPass http://localhost:1337/
ProxyPassReverse http://localhost:1337/
</Location>
</VirtualHost>
and restart apache2 service.
Label label1 = new System.Windows.Forms.Label
//label1.Text = "test";
if (Request.QueryString["ID"] != null)
{
string test = Request.QueryString["ID"];
label1.Text = "Du har nu lånat filmen:" + test;
}
else
{
string test = Request.QueryString["ID"];
label1.Text = "test";
}
This should make it
The computed columns make the problem.
Do not use SELECT *
. You must specify each fields after SELECT except computed fields
First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):
=DATE(1970,1,1)+(A1/86400000)
If your cell is properly formatted, you should see a human-readable date/time.
The easiest way to forget this page and never return to it is to learn the Get-Variable
:
Get-Variable | where {$_.Name -Like '*version*'} | %{$_[0].Value}
There is no need to remember every variable. Just Get-Variable
is enough (and "There should be something about version").
Update
Mongoose 5.7.1 was release and seems to fix the issue, so setting up the useUnifiedTopology
option work as expected.
mongoose.connect(mongoConnectionString, {useNewUrlParser: true, useUnifiedTopology: true});
Original answer
I was facing the same issue and decided to deep dive on Mongoose code: https://github.com/Automattic/mongoose/search?q=useUnifiedTopology&unscoped_q=useUnifiedTopology
Seems to be an option added on version 5.7 of Mongoose and not well documented yet. I could not even find it mentioned in the library history https://github.com/Automattic/mongoose/blob/master/History.md
According to a comment in the code:
- @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to
true
to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine.
There is also an issue on the project GitHub about this error: https://github.com/Automattic/mongoose/issues/8156
In my case I don't use Mongoose in a replica set or sharded cluster and though the option should be false. But if false it complains the setting should be true. Once is true it still don't work, probably because my database does not run on a replica set or sharded cluster.
I've downgraded to 5.6.13 and my project is back working fine. So the only option I see for now is to downgrade it and wait for the fix to update for a newer version.
It worked to me:
String javaHome = System.getProperty("java.home");
File f = new File(javaHome);
f = new File(f, "bin");
f = new File(f, "javaw.exe"); //or f = new File(f, "javaws.exe"); //work too
System.out.println(f + " exists: " + f.exists());
Chris pretty much sums up what w3wp is. In order to disable the warning, go to this registry key:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger
And set the value DisableAttachSecurityWarning
to 1.
Here's a gitHub project that does just that.
It records audio from the browser in mp3 format, and it automatically saves it to the webserver. https://github.com/Audior/Recordmp3js
You can also view a detailed explanation of the implementation: http://audior.ec/blog/recording-mp3-using-only-html5-and-javascript-recordmp3-js/
I didn't think it would be that simple! go to this link: https://www.codeproject.com/Articles/18399/Localizing-System-MessageBox
Download the source. Take the MessageBoxManager.cs file, add it to your project. Now just register it once in your code (for example in the Main() method inside your Program.cs file) and it will work every time you call MessageBox.Show():
MessageBoxManager.OK = "Alright";
MessageBoxManager.Yes = "Yep!";
MessageBoxManager.No = "Nope";
MessageBoxManager.Register();
See this answer for the source code here for MessageBoxManager.cs.
There are several options.
The easiest is likely the exec plugin.
You can also generate a jar containing all the dependencies using the assembly plugin.
Lastly, you can generate a file with the classpath in it using the dependency:classpath
goal.
Arrays can only be passed by reference, actually:
void foo(double (&bar)[10])
{
}
This prevents you from doing things like:
double arr[20];
foo(arr); // won't compile
To be able to pass an arbitrary size array to foo
, make it a template and capture the size of the array at compile time:
template<typename T, size_t N>
void foo(T (&bar)[N])
{
// use N here
}
You should seriously consider using std::vector
, or if you have a compiler that supports c++11, std::array
.
yes
and no
, where no
is the default value.standalone="yes"
means that the XML processor must use the DTD for validation only. In that case it will not be used for:
standalone="yes"
may add validity constraints if the document uses an external DTD. When the document contains things that would require modification of the XML, such as default values for attributes, and standalone="yes"
is used then the document is invalid.standalone="yes"
may help to optimize performance of document processing.Source: The standalone pseudo-attribute is only relevant if a DTD is used
Had the same issue today and found another option with knitr 1.16
when knitting to PDF (which requires that you have pandoc installed):
![Image Title](path/to/your/image){width=70%}
This method may require that you do a bit of trial and error to find the size that works for you. It is especially convenient because it makes putting two images side by side a prettier process. For example:
![Image 1](path/to/image1){width=70%}![Image 2](path/to/image2){width=30%}
You can get creative and stack a couple of these side by side and size them as you see fit. See https://rpubs.com/RatherBit/90926 for more ideas and examples.
I was not satisfied, so I finally used this:
>>> a=numpy.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> tuple(a.reshape(1, -1)[0])
(1, 2, 3, 4, 5, 6)
I don't know if it's quicker, but it looks more effective ;)
Text to speech is built into Android 1.6+. Here is a simple example of how to do it.
TextToSpeech tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("Text to say aloud", TextToSpeech.QUEUE_ADD, null);
More info: http://android-developers.blogspot.com/2009/09/introduction-to-text-to-speech-in.html
Here are instructions on how to download sample code from the Android SDK Manager:
Launch the Android SDK Manager.
a. On Windows, double-click the SDK Manager.exe file at the root of the Android SDK directory.
b. On Mac or Linux, open a terminal to the tools/ directory in the Android SDK, then execute android sdk.
Expand the list of packages for the latest Android platform.
/sdk/samples/android-version/
(i.e. \android-sdk-windows\samples\android-16\ApiDemos\src\com\example\android\apis\app\TextToSpeechActivity.java)
As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub
. The simplest way is to change location
to str(location)
when using re.sub
. It wouldn't hurt to do it anyways even if it's already a str
.
letters_only = re.sub("[^a-zA-Z]", # Search for all non-letters
" ", # Replace all non-letters with spaces
str(location))
Some context: Recently for graduate school I researched UML tools for usability and UML comprehension in general for an independent project. I also model/architect for a living.
The previous posts have too many answers and not enough questions. A common misunderstanding is that UML is about creating diagrams. Sure, diagrams are important, but really you are creating a model. Here are the questions that should be answered as each vendor product/solution does some things better than others. Note: The listed answers are my view as the best even if other products support a given feature or need.
Detailed Examples: IBM Rational Software Architect did not implement UML 2.0 all the way when it comes to realizes type relationships when creating a UML profile, but Visual Paradigm and Sparx got it right.
Ok, that was way too detailed, so a simpler example would be ArgoUML, which has no code generation features and focuses on drawing more than the modeling aspect of UML.
Sparx and Visual Paradigm do UML really well and generate code well, however, hooking into project lifecycles and other process is where RSM/RSA is strong.
Watch out for closed or product specific code generation processes or frameworks as you could end up stuck with that product.
This is a straight brain dump so a couple details may not be perfect, however, this should provide a general map to the questions and solutions to looking into.
NEW - Found a good list of many UML tools with descriptions. Wiki UML Tool List
As an update to Joe's answer, in that you can script the creation of the repository using the API, only the API call I needed was different. This may be because we are using bitbucket server, and not bitbucket cloud.
To create a new repo within a project on our server, I used:
curl -X POST -v -u USER:PASSWORD -H "Content-Type: application/json" \
http://SERVER/rest/api/1.0/projects/PROJECTNAME/repos/ \
-d '{"scmid":"git", "name":"REPONAME"}'
where USER
, PASSWORD
, SERVER
, PROJECTNAME
and REPONAME
were of course the desired/required values.
The call is documented in the API reference.
/rest/api/1.0/projects/{projectKey}/repos
Create a new repository. Requires an existing project in which this repository will be created. The only parameters which will be used are name and scmId.
The authenticated user must have PROJECT_ADMIN permission for the context project to call this resource.
The direct solution would be to invoke ifPresent(consumer)
on the Optional returned by findFirst()
. This consumer will be invoked when the optional is not empty. The benefit also is that it won't throw an exception if the find operation returned an empty optional, like your current code would do; instead, nothing will happen.
If you want to return the removed value, you can map
the Optional
to the result of calling remove
:
producersProcedureActive.stream()
.filter(producer -> producer.getPod().equals(pod))
.findFirst()
.map(p -> {
producersProcedureActive.remove(p);
return p;
});
But note that the remove(Object)
operation will again traverse the list to find the element to remove. If you have a list with random access, like an ArrayList
, it would be better to make a Stream over the indexes of the list and find the first index matching the predicate:
IntStream.range(0, producersProcedureActive.size())
.filter(i -> producersProcedureActive.get(i).getPod().equals(pod))
.boxed()
.findFirst()
.map(i -> producersProcedureActive.remove((int) i));
With this solution, the remove(int)
operation operates directly on the index.
Use request.get_data()
to get the raw data, regardless of content type. The data is cached and you can subsequently access request.data
, request.json
, request.form
at will.
If you access request.data
first, it will call get_data
with an argument to parse form data first. If the request has a form content type (multipart/form-data
, application/x-www-form-urlencoded
, or application/x-url-encoded
) then the raw data will be consumed. request.data
and request.json
will appear empty in this case.
Given the Class loader sussystem actions:
This is an article that helped me a lot to understand the difference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html
If an error occurs during class loading, then an instance of a subclass of LinkageError must be thrown at a point in the program that (directly or indirectly) uses the class or interface being loaded.
If the Java Virtual Machine ever attempts to load a class C during verification (§5.4.1) or resolution (§5.4.3) (but not initialization (§5.5)), and the class loader that is used to initiate loading of C throws an instance of ClassNotFoundException, then the Java Virtual Machine must throw an instance of NoClassDefFoundError whose cause is the instance of ClassNotFoundException.
So a ClassNotFoundException is a root cause of NoClassDefFoundError.
And a NoClassDefFoundError is a special case of type loading error, that occurs at Linking step.
<Scatter
data={data}
// style={{ width: "50%", height: "50%" }}
options={{
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Probability",
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Hours",
},
},
],
},
}}
/>
You need to create a StringWriter, and pass that to the XmlWriter.
The string overload of the XmlWriter.Create is for a filename.
E.g.
using (var sw = new StringWriter()) {
using (var xw = XmlWriter.Create(sw)) {
// Build Xml with xw.
}
return sw.ToString();
}
import {Router, ActivatedRoute, Params} from '@angular/router';
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.paramMap
.subscribe( params => {
let id = +params.get('id');
console.log('id' + id);
console.log(params);
id12
ParamsAsMap {params: {…}}
keys: Array(1)
0: "id"
length: 1
__proto__: Array(0)
params:
id: "12"
__proto__: Object
__proto__: Object
}
)
}
if you will include
System.Windows.forms
as namespace then it will conflict . Use
btn_click()
{
System.Windows.Forms.MessageBox.Show("Hello");
}
Posting parameters Using POST:-
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
The part which you missed is in the the following... i.e., as follows..
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();
The rest of the thing you can do it.
While the accepted solution works, it is not complete. By far.
If you want to get all the keys, you need to take into consideration 2 more things:
x86 & x64 applications do not have access to the same registry. Basically x86 cannot normally access x64 registry. And some applications only register to the x64 registry.
and
some applications actually install into the CurrentUser registry instead of the LocalMachine
With that in mind, I managed to get ALL installed applications using the following code, WITHOUT using WMI
Here is the code:
List<string> installs = new List<string>();
List<string> keys = new List<string>() {
@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
};
// The RegistryView.Registry64 forces the application to open the registry as x64 even if the application is compiled as x86
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64), keys, installs);
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64), keys, installs);
installs = installs.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
installs.Sort(); // The list of ALL installed applications
private void FindInstalls(RegistryKey regKey, List<string> keys, List<string> installed)
{
foreach (string key in keys)
{
using (RegistryKey rk = regKey.OpenSubKey(key))
{
if (rk == null)
{
continue;
}
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
try
{
installed.Add(Convert.ToString(sk.GetValue("DisplayName")));
}
catch (Exception ex)
{ }
}
}
}
}
}
Sure we can get all HTML source code with this script below in Selenium Python:
elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")
If you you want to save it to file:
with open('c:/html_source_code.html', 'w') as f:
f.write(source_code.encode('utf-8'))
I suggest saving to a file because source code is very very long.
If you want to put a view in the center of parent, you can do with following code..
public class myLayout extends LinearLayout {
public myLayout(Context context) {
super(context);
RelativeLayout vi = (RelativeLayout) ((LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.activity_main, null);
LinearLayout.LayoutParams cc = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
cc.gravity = Gravity.CENTER;
this.setGravity(Gravity.CENTER);
this.addView(vi);
}
}
these code section make LinearLayout put the first view elements in the center of parent. So, we system don't consider the initial width and high to arrange view in the center . I do the code section well.
Dart Version:
double latRad(double lat) {
final double sin = math.sin(lat * math.pi / 180);
final double radX2 = math.log((1 + sin) / (1 - sin)) / 2;
return math.max(math.min(radX2, math.pi), -math.pi) / 2;
}
double getMapBoundZoom(LatLngBounds bounds, double mapWidth, double mapHeight) {
final LatLng northEast = bounds.northEast;
final LatLng southWest = bounds.southWest;
final double latFraction = (latRad(northEast.latitude) - latRad(southWest.latitude)) / math.pi;
final double lngDiff = northEast.longitude - southWest.longitude;
final double lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
final double latZoom = (math.log(mapHeight / 256 / latFraction) / math.ln2).floorToDouble();
final double lngZoom = (math.log(mapWidth / 256 / lngFraction) / math.ln2).floorToDouble();
return math.min(latZoom, lngZoom);
}
You can call:
arr.slice(Math.max(arr.length - 5, 1))
If you don't want to exclude the first element, use
arr.slice(Math.max(arr.length - 5, 0))
I could see $.ajax
is removed from jQuery slim 3.2.1
From the jQuery docs
You can also use the slim build, which excludes the ajax and effects modules
Below is the comment from the slim version with the features removed
/*! jQuery v3.2.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */
In general, a wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. These are useful by providing a level of abstraction from the implementation of the underlying class or component; for example, wrapper classes that wrap COM components can manage the process of invoking the COM component without bothering the calling code with it. They can also simplify the use of the underlying object by reducing the number interface points involved; frequently, this makes for more secure use of underlying components.
For Mac OS X, using TextEdit or the natural environmental editor for text:
git config --global core.editor "open -W -n"
Installing from RPM is generally better, because:
Red Hat has added through the EPEL repository:
sudo yum install -y epel-release
sudo yum install -y python34
# Install pip3
sudo yum install -y python34-setuptools # install easy_install-3.4
sudo easy_install-3.4 pip
You can create your virtualenv using pyvenv
:
pyvenv /tmp/foo
With CentOS7, pip3.6
is provided as a package :)
sudo yum install -y epel-release
sudo yum install -y python36 python36-pip
You can create your virtualenv using pyvenv
:
python3.6 -m venv /tmp/foo
If you use the pyvenv
script, you'll get a WARNING:
$ pyvenv-3.6 /tmp/foo
WARNING: the pyenv script is deprecated in favour of `python3.6 -m venv`
The IUS Community provides some up-to-date packages for RHEL & CentOS. The guys behind are from Rackspace, so I think that they are quite trustworthy...
Check the right repo for you here:
sudo yum install -y https://repo.ius.io/ius-release-el6.rpm
sudo yum install -y python36u python36u-pip
You can create your virtualenv using pyvenv
:
python3.6 -m venv /tmp/foo
sudo yum install -y https://repo.ius.io/ius-release-el7.rpm
sudo yum install -y python36u python36u-pip
You can create your virtualenv using pyvenv
:
python3.6 -m venv /tmp/foo
import paramiko
import time
ssh = paramiko.SSHClient()
#ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.106.104.24', port=22, username='admin', password='')
time.sleep(5)
print('connected')
stdin, stdout, stderr = ssh.exec_command(" ")
def execute():
stdin.write('xcommand SystemUnit Boot Action: Restart\n')
print('success')
execute()
In django 3.1, go to setting of your project and import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
my issue (fatal: The remote end hung up unexpectedly) has been resolved by checking repository permission and owner.
git repository files owner must be that user you want push/pull/clone with it.
The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.
#!/bin/bash -vx
##config file with ip addresses like 10.10.10.1:80
file=config.txt
while read line ; do
##this line is not correct, should strip :port and store to ip var
ip=$( echo "$line" |cut -d\: -f1 )
ping $ip
done < ${file}
You could write your top line as
for line in $(cat $file) ; do ...
(but not recommended).
You needed command substitution $( ... )
to get the value assigned to $ip
reading lines from a file is usually considered more efficient with the while read line ... done < ${file}
pattern.
I hope this helps.
Building on @Valentyn's answer a bit, here's one way to always automatically clear the cache whenever the ng-view content changes:
myApp.run(function($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function() {
$templateCache.removeAll();
});
});
In node, you can just say
console.log(aa)
and it will format it as it should.
If you need to use the resulting string you should use
JSON.stringify(aa)
GO is not a SQL keyword.
It's a batch separator used by client tools (like SSMS) to break the entire script up into batches
Answered before several times... example 1
HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.
The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.
This is a way to see if any XML-files exists in that folder, yes.
To check for specific files use File.Exists(path)
, which will return a boolean indicating wheter the file at path
exists.
To get a new line inside text-area, put an actual line-break there:
<textarea cols='60' rows='8'>This is my statement one._x000D_
This is my statement2</textarea>
_x000D_
<html>
<head>
<style type="text/css"><!--
body {
margin: 0px;
padding: 0px;
}
.wrapper {
margin: 0px auto;
padding: 0px;
width: 940px;
background-color: #EEE;
background-image: url("images/bg.png");
background-repeat: repeat-y;
padding: 0px 25px 4px 25px;
}
.header {
}
.headerIn {
width: 940px;
margin: 0 auto;
font-size: 14px;
}
.headerP1 {
width: 940px;
background: url("images/lines_tech.png") repeat;
margin: 0px auto;
height: 140px;
}
.container {
width: 940px;
margin: 0 auto;
font-size: 14px;
height: auto;
}
.footer {
width: 100%;
background: #EEE;
}
.footer {
width: 940px;
margin: 0 auto;
font-size: 12px;
font-family: Georgia, "Times New Roman", Times, serif;
/* background: url("images/footer_bg.png") center bottom no-repeat; */
}
.mainfooter {
width: 990px;
background: url("images/footer_bg.png") no-repeat;
margin-bottom: 50px;
margin: 0 auto;
}
.footer .footerContainer {
width: 940px;
margin: 0 auto;
font-size: 11px;
}
#tblbdr table, #tblbdr table td {
border-collapse: collapse;
border: solid 1px #CDCDCD;
padding: 5px 5px;
}
#tblbdr table, #tblbdr table td {
border-collapse: collapse;
border: solid 1px #CDCDCD;
padding: 5px 5px;
}
.input {
padding: 5px 5px;
margin: 0px 0px;
border: solid 1px #DEDEDE;
background-color: #F9F9F9;
font-size: 12px;
}
.tbl {
margin: 0 auto;
padding-bottom: 3px;
background: url("images/tblbtm.png") repeat-x bottom;
}
.tbl1 {
background: url("images/tblright.png") repeat-y right;
padding-right: 2px;
}
.button {
background: royalblue;
color: #FFF;
border: none;
padding: 5px 7px;
cursor: pointer;
}
ul {
list-style: square outside none;
}
ul li {
display: block;
height: auto;
line-height: 29px;
text-decoration: none;
background-color: #F6F6F6;
padding-left: 30px;
font-family: Verdana;
border-bottom: 1px solid #ebebeb;
background-image: url('images/arrowC.png');
background-repeat: no-repeat;
background-position: left -30px;
}
.DivTab1 {
width: 270px;
height: 199px;
}
.DivTab1 a {
background-image: url('images/nav_bg.jpg');
background-position: 0 0;
float: left;
display: block;
width: 85%;
height: 33px;
line-height: 40px;
padding-left: 40px;
color: #000;
}
.DivTab1 a:hover {
background-image: url('images/nav_bg.jpg');
background-position: left 33px;
float: left;
display: block;
width: 85%;
height: 33px;
line-height: 40px;
padding-left: 40px;
}
--></style>
</head>
<body>
<div class="wrapper">
<div class="header">
<div class="headerIn">
<div class="headerP1">Header</div>
</div>
</div>
<div class="container" id="tblbdr">
<div class="tblt" style="padding:10px;background:#fff; width:500px;margin:0px auto;">
<table border="0" align="center" cellpadding="0" cellspacing="0" width="500px">
<tr><td>Login</td></tr>
<tr><td><input type="text" class="input" /></td></tr>
<tr><td><input type="text" class="input" /></td></tr>
</table>
</div>
<br /><br />
<div class="tbl">
<div class="tbl1">
<table border="0" style="background:#fff;" align="center" cellpadding="0" cellspacing="0" width="100%">
<tbody><tr>
<td style="width: 79px">
State<span style="color: #ff0000">*</span></td>
<td style="width: 183px">
<select name="drpOwnerState" onchange="javascript:setTimeout('__doPostBack(\'drpOwnerState\',\'\')', 0)" id="drpOwnerState" class="input" style="width:173px;">
<option value="NA">Select</option>
<option selected="selected" value="AN">ANDAMAN AND NICOBAR ISLANDS</option>
<option value="AP">ANDHRA PRADESH</option>
<option value="AL">ARUNACHAL PRADESH</option>
</select>
</td>
<td style="width: 65px">
Division<span style="color: #ff0000"></span></td>
<td style="width: 187px">
<select name="drpOwnerDivision" onchange="javascript:setTimeout('__doPostBack(\'drpOwnerDivision\',\'\')', 0)" id="drpOwnerDivision" disabled="disabled" class="input" style="width:173px;">
<option selected="selected" value="NA">Select</option>
</select>
</td>
<td style="width: 56px">
District<span style="color: #ff0000"></span></td>
<td colspan="3">
<select name="drpOwnerDistrict" onchange="javascript:setTimeout('__doPostBack(\'drpOwnerDistrict\',\'\')', 0)" id="drpOwnerDistrict" disabled="disabled" class="input" style="width:173px;">
<option selected="selected" value="NA">Select</option>
</select></td>
</tr>
<tr>
<td colspan="3">
Type any detail about your nearest KIOSK:</td>
<td colspan="5">
<input name="txtSearch" type="text" maxlength="100" id="txtSearch" class="input" style="width:182px;"></td>
</tr>
<tr>
<td align="center" colspan="8" style="height: 23px">
<input type="submit" name="btnsearch" value="Search" onclick="return ListValidation();" id="btnsearch">
<input type="submit" class="button" name="lblExport" value="Export To Excel" id="lblExport"></td>
</tr>
</tbody>
</table>
</div>
</div>
<br /><br />
<div class="DivTab1" style="z-index: 750;">
<a href="/Portal/CitizenHome.aspx?servtypeid=1">Applications</a><a href="/Portal/CitizenHome.aspx?servtypeid=2">
Bill Payments</a> <a href="/Portal/CitizenHome.aspx?servtypeid=3">Counseling</a>
<a href="/Portal/CitizenHome.aspx?servtypeid=4">Assessment</a> <a href="/Portal/CitizenHome.aspx?servtypeid=5">
Religious</a> <a href="/Portal/CitizenHome.aspx?servtypeid=6">Reservation</a>
<a href="/Portal/CitizenHome.aspx?servtypeid=7">Universities</a>
</div>
<br /><br />
<div>
<ul>
<li><spn>This is testing code which may be more or less.</span></li>
<li>This is testing code which may be more or less. This is testing code which may be more or less.This is testing code which may be more or less. This is testing code which may be more or less.</li>
<li>This is testing code which may be more or less.</li>
<li>This is testing code which may be more or less.</li>
<li>This is testing code which may be more or less.</li>
</ul>
</div>
</div>
<div class="footer">
<div class="footerContainer">Footer</div>
</div>
</div>
<div class="mainfooter"> </div>
</body>
</html>
var module = angular.module("example", []);
module.controller("orderByController", function ($scope) {
$scope.orderByValue = function (value) {
return value;
};
$scope.items = ["c", "b", "a"];
$scope.objList = [
{
"name": "c"
}, {
"name": "b"
}, {
"name": "a"
}];
$scope.item = "b";
});
The short answer for old versions of Rails (see other answers for Rails 4+):
add_index :table_name, :column_name, unique: true
To index multiple columns together, you pass an array of column names instead of a single column name,
add_index :table_name, [:column_name_a, :column_name_b], unique: true
If you get "index name... is too long", you can add name: "whatever"
to the add_index method to make the name shorter.
For fine-grained control, there's a "execute
" method that executes straight SQL.
That's it!
If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.
Using a collection initializer
From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:
var human = new Human(1, "Address", "Name") {
ContactNumbers = new List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
}
}
Specializing the Human
constructor
You can change the constructor of the Human
class to provide a way to populate the ContactNumbers
property:
public class Human
{
public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
}
// Using the first constructor:
List<ContactNumber> numbers = List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
};
var human = new Human(1, "Address", "Name", numbers);
// Using the second constructor:
var human = new Human(1, "Address", "Name",
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
);
Bottom line
Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...
First quote your javascript:
onclick="hello();"
Also you can't call a php function from javascript; you need:
<script type="text/javascript">
function hello()
{
alert ("hello");
}
</script>
In reference to your comment after Ian Henry's answer, I'm not quite 100% sure I understand what you are asking.
If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example:
String theFirst = "Java Programming";
String ROM = "\"" + theFirst + "\"";
Or, if you want to do it with one String variable, it would be:
String ROM = "Java Programming";
ROM = "\"" + ROM + "\"";
Of course, this actually replaces the original ROM, since Java Strings are immutable.
If you are wanting to do something like turn the variable name into a String, you can't do that in Java, AFAIK.
Add to your .gitconfig
under [alias]
:
aliases = !git config --list | grep ^alias\\. | cut -c 7- | grep -Ei --color \"$1\" "#"
Then you can do
git aliases
- show ALL aliasesgit aliases commit
- only aliases containing "commit"Just use the result from the FOR
command. For example (inside a batch file):
for /F "delims=" %%I in ('dir /b /a-d /od FILESA*') do (echo %%I)
You can use the %%I
as the value you want. Just like this: %%I
.
And in advance the %%I
does not have any spaces or CR characters and can be used for comparisons!!
I had problems installing some Wordpress plugins on my local server running php56 on OSX10.11. They failed connection on the external API over SSL.
Installing openSSL didn't solved my problem. But then I figured out that CURL also needed to be reinstalled.
This solved my problem using Homebrew.
brew rm curl && brew install curl --with-openssl
brew uninstall php56 && brew install php56 --with-homebrew-curl --with-openssl
You can use "group by" + "orderby". See LINQ 101 for details
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
group x by x into g
let count = g.Count()
orderby count descending
select new {Value = g.Key, Count = count};
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
In response to this post (now deleted):
If you have a list of some custom objects then you need to use custom comparer or group by specific property.
Also query can't display result. Show us complete code to get a better help.
Based on your latest update:
You have this line of code:
group xx by xx into g
Since xx is a custom object system doesn't know how to compare one item against another. As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:
Note that I use Foo.Name as a key - i.e. objects will be grouped based on value of Name property.
There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.
//Using extension methods
var q = list.GroupBy(x => x.Name)
.Select(x => new {Count = x.Count(),
Name = x.Key,
ID = x.First().ID})
.OrderByDescending(x => x.Count);
//Using LINQ
var q = from x in list
group x by x.Name into g
let count = g.Count()
orderby count descending
select new {Name = g.Key, Count = count, ID = g.First().ID};
foreach (var x in q)
{
Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}
I'm not sure what was your original reason for running Travis locally, if you just wanted to play with it, then stop reading here as it's irrelevant for you.
If you already have experience with hosted Travis and you want to get the same experience in your own datacenter, read on.
Since Dec 2014 Travis CI offers an Enterprise on-premises version.
http://blog.travis-ci.com/2014-12-19-introducing-travis-ci-enterprise/
The pricing is part of the article as well:
The licensing is done per seats, where every license includes 20 users. Pricing starts at $6,000 per license, which includes 20 users and 5 concurrent builds. There's a premium option with unlimited builds for $8,500.
Use WebElement.send_keys
method to simulate key typing.
name
in the code (Username
, Password
) does not match actual name
of the elements (username
, password
).
username = browser.find_element_by_name('username')
username.send_keys('user1')
password = browser.find_element_by_name('password')
password.send_keys('secret')
form = browser.find_element_by_id('loginForm')
form.submit()
# OR browser.find_element_by_id('submit').click()
1. About onCreate() and onUpgrade()
onCreate(..)
is called whenever the app is freshly installed. onUpgrade
is called whenever the app is upgraded and launched and the database version is not the same.
2. Incrementing the db version
You need a constructor like:
MyOpenHelper(Context context) {
super(context, "dbname", null, 2); // 2 is the database version
}
IMPORTANT: Incrementing the app version alone is not enough for onUpgrade
to be called!
3. Don't forget your new users!
Don't forget to add
database.execSQL(DATABASE_CREATE_color);
to your onCreate() method as well or newly installed apps will lack the table.
4. How to deal with multiple database changes over time
When you have successive app upgrades, several of which have database upgrades, you want to be sure to check oldVersion
:
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
db.execSQL(DATABASE_CREATE_color);
// we want both updates, so no break statement here...
case 2:
db.execSQL(DATABASE_CREATE_someothertable);
}
}
This way when a user upgrades from version 1 to version 3, they get both updates. When a user upgrades from version 2 to 3, they just get the revision 3 update... After all, you can't count on 100% of your user base to upgrade each time you release an update. Sometimes they skip an update or 12 :)
5. Keeping your revision numbers under control while developing
And finally... calling
adb uninstall <yourpackagename>
totally uninstalls the app. When you install again, you are guaranteed to hit onCreate
which keeps you from having to keep incrementing the database version into the stratosphere as you develop...
based on drew010 example I made a working example for easy understanding.
imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data
function imagesaver($image_data){
list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating
if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
throw new \Exception('invalid image type');
}
$data = base64_decode($data);
if ($data === false) {
throw new \Exception('base64_decode failed');
}
} else {
throw new \Exception('did not match data URI with image data');
}
$fullname = time().$type;
if(file_put_contents($fullname, $data)){
$result = $fullname;
}else{
$result = "error";
}
/* it will return image name if image is saved successfully
or it will return error on failing to save image. */
return $result;
}
The first column actually refers to Text Field:
// Add the pet to our listview
ListViewItem lvi = new ListViewItem();
lvi.text = pet.Name;
lvi.SubItems.Add(pet.Type);
lvi.SubItems.Add(pet.Age);
listView.Items.Add(lvi);
Or you can use the Constructor
ListViewItem lvi = new ListViewItem(pet.Name);
lvi.SubItems.Add(pet.Type);
....
Yet another/simple alternative (model identifier reference found at https://www.theiphonewiki.com/wiki/Models):
Updated answer for Swift 3/4/5 including string trimming and simulator support:
func modelIdentifier() -> String {
if let simulatorModelIdentifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] { return simulatorModelIdentifier }
var sysinfo = utsname()
uname(&sysinfo) // ignore return value
return String(bytes: Data(bytes: &sysinfo.machine, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters)
}
Simple solution for HTML5 ready browsers...
function download(filename, text) {_x000D_
var element = document.createElement('a');_x000D_
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));_x000D_
element.setAttribute('download', filename);_x000D_
_x000D_
element.style.display = 'none';_x000D_
document.body.appendChild(element);_x000D_
_x000D_
element.click();_x000D_
_x000D_
document.body.removeChild(element);_x000D_
}
_x000D_
form * {_x000D_
display: block;_x000D_
margin: 10px;_x000D_
}
_x000D_
<form onsubmit="download(this['name'].value, this['text'].value)">_x000D_
<input type="text" name="name" value="test.txt">_x000D_
<textarea name="text"></textarea>_x000D_
<input type="submit" value="Download">_x000D_
</form>
_x000D_
Usage
download('test.txt', 'Hello world!');
How about using the Dynamic data template that comes with Visual Studio. This could be hosted on IIS.
From all my searching around, I strongly say that the most practical, accurate and free data source is provided by GeoNames.
You can access their data in 2 ways:
new mongoose.Schema({ description: { type: String, required: true, trim: true }, completed: { type: Boolean, default: false }, owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' } }, { timestamps: true });
Unfortunately the best way would be to check for that directory. I am not sure what you mean but "actually installed" as .NET 3.5 uses the same CLR as .NET 3.0 and .NET 2.0 so all new functionality is wrapped up in new assemblies that live in that directory. Basically, if the directory is there then 3.5 is installed.
Only thing I would add is to find the dir this way for maximum flexibility:
%windir%\Microsoft.NET\Framework\v3.5
sys.exit()
raises a SystemExit
exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit
A good way to force your CSS to reload is to:
<link href='styles.css?version=1' rel='stylesheet'></link>
And then just increment the version number as you change your CSS. The browser will then obey. I believe StackOverflow uses this technique.
I'm using this in swift 5 and worked for me
navigationItem.backBarButtonItem?.tintColor = UIColor(named: "uberRed")
Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.
fill_parent
(deprecated and renamed MATCH_PARENT
in API Level 8 and higher)
Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dockstyle of a Windows Form Control to Fill
.
Setting a top level layout or control to fill_parent will force it to take up the whole screen.
wrap_content
Setting a View's size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.
It's roughly the equivalent of setting a Windows Form Control's Autosize
property to True.
Online Documentation
There's some details in the Android code documentation here.
If supported by your browser, you may use CSS3 :read-only
selector:
input[type="text"]:read-only {
cursor: normal;
background-color: #f8f8f8;
color: #999;
}
based on javascript runtime prototype implementation you can use simple arithmetic to subtract dates as in bellow
var sep = new Date(2020, 07, 31, 23, 59, 59);
var today = new Date();
var diffD = Math.floor((sep - today) / (1000 * 60 * 60 * 24));
console.log('Day Diff: '+diffD);
the difference return answer as milliseconds, then you have to convert it by division:
Could you provide a whole makefile? But right now I can tell - you should check that "install" target already exists. So, check Makefile whether it contains a
install: (anything there)
line. If not, there is no such target and so make has right. Probably you should use just "make" command to compile and then use it as is or install yourself, manually.
Install is not any standard of make, it is just a common target, that could exists, but not necessary.
If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.
Here you go:
^[^<>]*$
This will test for string that has no <
and no >
If you want to test for a string that may have <
and >
, but must also have something other you should use just
[^<>] (or ^.*[^<>].*$)
Where [<>]
means any of <
or >
and [^<>]
means any that is not of <
or >
.
And of course the mandatory link.
There is no forumula, as street names and cities are essentially handed out randomly. The address needs to be looked up in a database. Alternatively, you can look up a zip code in a database for the region that the zip code is for.
You didn't mention a country, so I'm going to assume you just want addresses in the USA. There are numerous databases you can use, some free, some not.
You can also use the Google Maps API to have them look up an address in their database for you. That is probably the easiest solution, but requires your application to have a working internet connection at all times.
Font-awesome provides a great solution out of the box:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />_x000D_
_x000D_
<ul class='fa-ul'>_x000D_
<li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
<li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
</ul>
_x000D_
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}'
I don't believe you can, though I hope that someone will prove me wrong.
I know you can print the query and its toString method will show you the sql without the replacements. That can be handy if you're building complex query strings, but it doesn't give you the full query with values.
I came across this trying to add labels o some vertical radio boxes. I had to do this:
<%: Html.RadioButton("RadioGroup1", "Yes") %><label style="display:inline-block;padding-top:2px;">Yes</label><br />
<%: Html.RadioButton("RadioGroup1", "No") %><label style="display:inline-block;padding-top:3px;">No</label><br />
<%: Html.RadioButton("RadioGroup1", "Maybe") %><label style="display:inline-block;padding-top:4px;">Maybe</label><br />
This gets them to display properly, where the label is centered on the radio button, though I had to increment the top padding with each line, as you can see. The code isn't pretty, but the result is.
First you check your user agent OS Linux or windows or another. Then Your OS Windows Then this code use:
public function win_os(){
ob_start();
system('ipconfig-a');
$mycom=ob_get_contents(); // Capture the output into a variable
ob_clean(); // Clean (erase) the output buffer
$findme = "Physical";
$pmac = strpos($mycom, $findme); // Find the position of Physical text
$mac=substr($mycom,($pmac+36),17); // Get Physical Address
return $mac;
}
And your OS Linux Ubuntu or Linux then this code use:
public function unix_os(){
ob_start();
system('ifconfig -a');
$mycom = ob_get_contents(); // Capture the output into a variable
ob_clean(); // Clean (erase) the output buffer
$findme = "Physical";
//Find the position of Physical text
$pmac = strpos($mycom, $findme);
$mac = substr($mycom, ($pmac + 37), 18);
return $mac;
}
This code may be work OS X.
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
UPDATE 2018 FOR JQUERY 3 AND LATER
I know this is an old question but none of the above solutions worked for me. Here is the solution that worked:
//I only created this function as I am making many ajax calls with different urls and appending the result to different divs
function makeAjaxCall(requestType, urlTo, resultAreaId){
var jqxhr = $.ajax({
type: requestType,
url: urlTo
});
//this section is executed when the server responds with no error
jqxhr.done(function(){
});
//this section is executed when the server responds with error
jqxhr.fail(function(){
})
//this section is always executed
jqxhr.always(function(){
console.log("getting header " + jqxhr.getResponseHeader('testHeader'));
});
}
My one line solution:
hash.each { |key, array| puts "#{key}-----", array }
I think it is pretty easy to read.
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
If you want to check quietly via $? without the hassle of grep'ing wget's output you can use:
wget -q "http://blah.meh.com/my/path" -O /dev/null
Works even on URLs with just a path but has the disadvantage that something's really downloaded so this is not recommended when checking big files for existence.
Try iterating through each element of the list, then splitting it at the tab character and adding it to a new list.
for i in list:
newList.append(i.split('\t')[0])
The "-r" option is invalid on my systems. I had to use a different syntax for the "From" field.
-a "From: Foo Bar <[email protected]>"
For example, in your component before you declare your @Component
const en = require('../assets/en.json');
You will need GOPATH later, too. So add it to ~/.bashrc
.
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')
Edit Jan 2021: The React Native docs currently recommend React Native WebView:
<WebView
originWhitelist={['*']}
source={{ html: '<p>Here I am</p>' }}
/>
https://github.com/react-native-webview/react-native-webview
Edit March 2017: the html
prop has been deprecated. Use source
instead:
<WebView source={{html: '<p>Here I am</p>'}} />
https://facebook.github.io/react-native/docs/webview.html#html
Thanks to Justin for pointing this out.
Edit Feb 2017: the PR was accepted a while back, so to render HTML in React Native, simply:
<WebView html={'<p>Here I am</p>'} />
Original Answer:
I don't think this is currently possible. The behavior you're seeing is expected, since the Text component only outputs... well, text. You need another component that outputs HTML - and that's the WebView.
Unfortunately right now there's no way of just directly setting the HTML on this component:
https://github.com/facebook/react-native/issues/506
However I've just created this PR which implements a basic version of this feature so hopefully it'll land in some form soonish.
the syntax is CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3)
for example ::
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
the above example will work if you are writting it while you are creating the table for example ::
CREATE TABLE person (
P_Id int ,
............,
............,
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);
to add this constraint to an existing table you need to follow the following syntax
ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (P_Id,LastName)
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;
ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}
Yow can change the DropDownStyle in properties to DropDownList. This will not show the TextBox for filter.
(Screenshot provided by FUSION CHA0S.)
Your json string is wrapped within square brackets ([]
), hence it is interpreted as array instead of single RetrieveMultipleResponse
object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse
, for example :
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{
if (r > 2) r = 0;
if (r == 0) value[i] = 0;
if (r == 1)value[i] = 0;
if (r == 2)value[i] = 255;
r++;
}
$currentDateTime = $row['date'];
echo $newDateTime = date('l jS \of F Y h:i:s A', strtotime($currentDateTime));
IMO, you cannot create an empty Date(java.util)
. You can create a Date
object with null
value and can put a null check.
Date date = new Date(); // Today's date and current time
Date date2 = new Date(0); // Default date and time
Date date3 = null; //Date object with null as value.
if(null != date3) {
// do your work.
}
In Swift 5:
extension Int{
func expo(_ power: Int) -> Int {
var result = 1
var powerNum = power
var tempExpo = self
while (powerNum != 0){
if (powerNum%2 == 1){
result *= tempExpo
}
powerNum /= 2
tempExpo *= tempExpo
}
return result
}
}
Use like this
2.expo(5) // pow(2, 5)
Thanks to @Paul Buis's answer.
You can look in sys.types or use TYPE_ID:
IF TYPE_ID(N'MyType') IS NULL ...
Just a precaution: using type_id won't verify that the type is a table type--just that a type by that name exists. Otherwise gbn's query is probably better.
use lodash
GLOBAL.utils = require('lodash')
var arr1 = ['first' , 'second'];
var arr2 = ['second '];
var result = utils.difference(arr1 , arr2);
console.log ( "result :" + result );
font-weight: bold;
This answer is an attempt at a technical answer rather than opinion.
If we want to be POSIX purists, we define a line as:
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206
An incomplete line as:
A sequence of one or more non- <newline> characters at the end of the file.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_195
A text file as:
A file that contains characters organized into zero or more lines. The lines do not contain NUL characters and none can exceed {LINE_MAX} bytes in length, including the <newline> character. Although POSIX.1-2008 does not distinguish between text files and binary files (see the ISO C standard), many utilities only produce predictable or meaningful output when operating on text files. The standard utilities that have such restrictions always specify "text files" in their STDIN or INPUT FILES sections.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_397
A string as:
A contiguous sequence of bytes terminated by and including the first null byte.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_396
From this then, we can derive that the only time we will potentially encounter any type of issues are if we deal with the concept of a line of a file or a file as a text file (being that a text file is an organization of zero or more lines, and a line we know must terminate with a <newline>).
Case in point: wc -l filename
.
From the wc
's manual we read:
A line is defined as a string of characters delimited by a <newline> character.
What are the implications to JavaScript, HTML, and CSS files then being that they are text files?
In browsers, modern IDEs, and other front-end applications there are no issues with skipping EOL at EOF. The applications will parse the files properly. It has to since not all Operating Systems conform to the POSIX standard, so it would be impractical for non-OS tools (e.g. browsers) to handle files according to the POSIX standard (or any OS-level standard).
As a result, we can be relatively confident that EOL at EOF will have virtually no negative impact at the application level - regardless if it is running on a UNIX OS.
At this point we can confidently say that skipping EOL at EOF is safe when dealing with JS, HTML, CSS on the client-side. Actually, we can state that minifying any one of these files, containing no <newline> is safe.
We can take this one step further and say that as far as NodeJS is concerned it too cannot adhere to the POSIX standard being that it can run in non-POSIX compliant environments.
What are we left with then? System level tooling.
This means the only issues that may arise are with tools that make an effort to adhere their functionality to the semantics of POSIX (e.g. definition of a line as shown in wc
).
Even so, not all shells will automatically adhere to POSIX. Bash for example does not default to POSIX behavior. There is a switch to enable it: POSIXLY_CORRECT
.
Food for thought on the value of EOL being <newline>: https://www.rfc-editor.org/old/EOLstory.txt
Staying on the tooling track, for all practical intents and purposes, let's consider this:
Let's work with a file that has no EOL. As of this writing the file in this example is a minified JavaScript with no EOL.
curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o x.js
curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o y.js
$ cat x.js y.js > z.js
-rw-r--r-- 1 milanadamovsky 7905 Aug 14 23:17 x.js
-rw-r--r-- 1 milanadamovsky 7905 Aug 14 23:17 y.js
-rw-r--r-- 1 milanadamovsky 15810 Aug 14 23:18 z.js
Notice the cat
file size is exactly the sum of its individual parts. If the concatenation of JavaScript files is a concern for JS files, the more appropriate concern would be to start each JavaScript file with a semi-colon.
As someone else mentioned in this thread: what if you want to cat
two files whose output becomes just one line instead of two? In other words, cat
does what it's supposed to do.
The man
of cat
only mentions reading input up to EOF, not <newline>. Note that the -n
switch of cat
will also print out a non- <newline> terminated line (or incomplete line) as a line - being that the count starts at 1 (according to the man
.)
-n Number the output lines, starting at 1.
Now that we understand how POSIX defines a line , this behavior becomes ambiguous, or really, non-compliant.
Understanding a given tool's purpose and compliance will help in determining how critical it is to end files with an EOL. In C, C++, Java (JARs), etc... some standards will dictate a newline for validity - no such standard exists for JS, HTML, CSS.
For example, instead of using wc -l filename
one could do awk '{x++}END{ print x}' filename
, and rest assured that the task's success is not jeopardized by a file we may want to process that we did not write (e.g. a third party library such as the minified JS we curl
d) - unless our intent was truly to count lines in the POSIX compliant sense.
Conclusion
There will be very few real life use cases where skipping EOL at EOF for certain text files such as JS, HTML, and CSS will have a negative impact - if at all. If we rely on <newline> being present, we are restricting the reliability of our tooling only to the files that we author and open ourselves up to potential errors introduced by third party files.
Moral of the story: Engineer tooling that does not have the weakness of relying on EOL at EOF.
Feel free to post use cases as they apply to JS, HTML and CSS where we can examine how skipping EOL has an adverse effect.
strtok can be very dangerous. It is not thread safe. Its intended use is to be called over and over in a loop, passing in the output from the previous call. The strtok function has an internal variable that stores the state of the strtok call. This state is not unique to each thread - it is global. If any other code uses strtok in another thread, you get problems. Not the kind of problems you want to track down either!
I'd recommend looking for a regex implementation, or using sscanf to pull apart the string.
Try this:
char strprint[256];
char text[256];
strcpy(text, "My string to test");
while ( sscanf( text, "%s %s", strprint, text) > 0 ) {
printf("token: %s\n", strprint);
}
Note: The 'text' string is destroyed as it's separated. This may not be the preferred behaviour =)
If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE
command to CREATE DATABASE IF NOT EXISTS
in line22
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);
To keep the previous typeface
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)
Here is the crisp answer:
public String sendSMS(String phone, String token) {
WebClient webClient = WebClient.create(smsServiceUrl);
SMSRequest smsRequest = new SMSRequest();
smsRequest.setMessage(token);
smsRequest.setPhoneNo(phone);
smsRequest.setTokenId(smsServiceTokenId);
Mono<String> response = webClient.post()
.uri(smsServiceEndpoint)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(Mono.just(smsRequest), SMSRequest.class)
.retrieve().bodyToMono(String.class);
String deliveryResponse = response.block();
if (deliveryResponse.equalsIgnoreCase("success")) {
return deliveryResponse;
}
return null;
}
I've found a post here on Stackoverflow and implemented your design:
Here's the original post: https://stackoverflow.com/a/5768262/1368423
Is that what you're looking for?
HTML:
<div class="container-fluid wrapper">
<div class="row-fluid columns content">
<div class="span2 article-tree">
navigation column
</div>
<div class="span10 content-area">
content column
</div>
</div>
<div class="footer">
footer content
</div>
</div>
CSS:
html, body {
height: 100%;
}
.container-fluid {
margin: 0 auto;
height: 100%;
padding: 20px 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.columns {
background-color: #C9E6FF;
height: 100%;
}
.content-area, .article-tree{
background: #bada55;
overflow:auto;
height: 100%;
}
.footer {
background: red;
height: 20px;
}
Use This Query :
Select
S.name + '.' + T.name As TableName ,
SUM( P.rows ) As RowCont
From sys.tables As T
Inner Join sys.partitions As P On ( P.OBJECT_ID = T.OBJECT_ID )
Inner Join sys.schemas As S On ( T.schema_id = S.schema_id )
Where
( T.is_ms_shipped = 0 )
AND
( P.index_id IN (1,0) )
And
( T.type = 'U' )
Group By S.name , T.name
Order By SUM( P.rows ) Desc
Why cant we just use eval()?
def install():
print "In install"
New method
def installWithOptions(var1, var2):
print "In install with options " + var1 + " " + var2
And then you call the method as below
method_name1 = 'install()'
method_name2 = 'installWithOptions("a","b")'
eval(method_name1)
eval(method_name2)
This gives the output as
In install
In install with options a b
Arriving late to the party but in our case we were getting this issue in Safari & iOS when using ES6 back tick instead of String() to type cast
This was giving 'invalid date' error
const dateString = '2011-11-18';
const dateObj = new Date(`${dateString}`);
But this works
const dateObj = new Date(String(dateString));
If anybody else is facing this issue in Git for Windows and do not have curl-ca-bundle.crt
anywhere on your system even after reinstalling, this is the process I followed:
curl-**.**.*/lib
in the command line./mk-ca-bundle.prl
ca-bundle.crt
to your git path and update the config as listed in other answersShout out to this gist for helping me get the installation done.
If you want to use both the simple click and long click on list view items better way to implement that would be to use context menu for long click. Avoid using setItemLongClickListener especially if you have multiple row layouts for your listview.
In SQL Server, you can use this query:
USE Database_name
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='Table_Name';
And do not forget to replace Database_name
and Table_name
with the exact names of your database and table names.
You can pass as many arguments as you want, separating them by commas:
{{ path('_files_manage', {project: project.id, user: user.id}) }}
you can try to this , then you get a bitmap of selected image and then you can easily find it's native path from Device Default Gallery.
Bitmap roughBitmap= null;
try {
// Works with content://, file://, or android.resource:// URIs
InputStream inputStream =
getContentResolver().openInputStream(uri);
roughBitmap= BitmapFactory.decodeStream(inputStream);
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.Width, roughBitmap.Height);
RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
m.SetRectToRect(inRect, outRect, Matrix.ScaleToFit.Center);
float[] values = new float[9];
m.GetValues(values);
// resize bitmap if needed
Bitmap resizedBitmap = Bitmap.CreateScaledBitmap(roughBitmap, (int) (roughBitmap.Width * values[0]), (int) (roughBitmap.Height * values[4]), true);
string name = "IMG_" + new Java.Text.SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Java.Util.Date()) + ".png";
var sdCardPath= Environment.GetExternalStoragePublicDirectory("DCIM").AbsolutePath;
Java.IO.File file = new Java.IO.File(sdCardPath);
if (!file.Exists())
{
file.Mkdir();
}
var filePath = System.IO.Path.Combine(sdCardPath, name);
} catch (FileNotFoundException e) {
// Inform the user that things have gone horribly wrong
}
Make sure the settings are applied correctly in the config file.
vim /etc/postgresql/x.x/main/postgresql.conf
Try the following to see the logs and find your problem.
tail /var/log/postgresql/postgresql-x.x-main.log
Using git show $REV:$FILE
as it was already pointed out by others is probably the right answer. I'm posting another answer because when I tried this method, I sometimes got the following error from git:
fatal: path 'link/foo' exists on disk, but not in 'HEAD'
The problem occurs when parts of the path to the file are a symbolic link. In those cases, the git show $REV:$FILE
method will not work. Steps to reproduce:
$ git init .
$ mkdir test
$ echo hello > test/foo
$ ln -s test link
$ git add .
$ git commit -m "initial commit"
$ cat link/foo
hello
$ git show HEAD:link/foo
fatal: path 'link/foo' exists on disk, but not in 'HEAD'
The problem is, that utilities like realpath
don't help here, because the symlink might not exist in the current commit anymore. I don't know about a good general solution. In my case, I knew that the symlink could only exist in the first component of the path, so I solved the problem by using the git show $REV:$FILE
method twice. This works, because when git show $REV:$FILE
is used on a symlink, then its target gets printed:
$ git show HEAD:link
test
Whereas with directories, the command will output a header, followed by the directory content:
$ git show HEAD:test
tree HEAD:test
foo
So in my case, I just checked the output of the first call to git show $REV:$FILE
and if it was only a single line, then I replaced the first component of my path with the result to resolve the symlink through git.
In Swift, I've created the following helper function:
class func nsobjectToJSON(swiftObject: NSObject) {
var jsonCreationError: NSError?
let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(swiftObject, options: NSJSONWritingOptions.PrettyPrinted, error: &jsonCreationError)!
if jsonCreationError != nil {
println("Errors: \(jsonCreationError)")
}
else {
// everything is fine and we have our json stored as an NSData object. We can convert into NSString
let strJSON : NSString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
println("\(strJSON)")
}
}
The socket has been closed by the client (browser).
A bug in your code:
byte[] outputByte=new byte[4096];
while(in.read(outputByte,0,4096)!=-1){
output.write(outputByte,0,4096);
}
The last packet read, then write may have a length < 4096, so I suggest:
byte[] outputByte=new byte[4096];
int len;
while(( len = in.read(outputByte, 0, 4096 )) > 0 ) {
output.write( outputByte, 0, len );
}
It's not your question, but it's my answer... ;-)
The font tag has been deprecated for some time now.
That being said, the reason why both of your tables display with the same font size is that the 'size' attribute only accepts values ranging from 1 - 7. The smallest size is 1. The largest size is 7. The default size is 3. Any values larger than 7 will just display the same as if you had used 7, because 7 is the maximum value allowed.
And as @Alex H said, you should be using CSS for this.
You have a compareTo function already ... I would implement the Comparable interface.
May not really matter for whatever you're going to do with it though.
Can you change the if condition to this:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
Having a netconfig xml and assign it in the manifest.xml is the best work around. This will bypass the androids default https only contraint.
Try this :
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys("[email protected]");
I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.
Turns out it's very easy, there is a readfile step, and I should have rtfm:
env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"
Using either a float or a double value in a C expression will result in a value that is a double anyway, so printf can't tell the difference. Whereas a pointer to a double has to be explicitly signalled to scanf as distinct from a pointer to float, because what the pointer points to is what matters.
You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.
Rows("52:55").EntireRow.Hidden = False
becomes
activesheet.Rows("52:55").EntireRow.Hidden = False
i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,
Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub
That's it. Anytime you change something, it will run the macro test1.
For token validation, check for the token expiry time first and then the blacklist if token not expired.
For long session needs, there should be a mechanism for extending token expiry time.
You mean Selenium WebDriver? Huh....
Prerequisite: Install Python based on your OS
Install with following command
pip install -U selenium
And use this module in your code
from selenium import webdriver
You can also use many of the following as required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
I would recommend you to run script without IDE... Here is my approach
An example below shows login page automation
#ScriptName : Login.py
#---------------------
from selenium import webdriver
#Following are optional required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
baseurl = "http://www.mywebsite.com/login.php"
username = "admin"
password = "admin"
xpaths = { 'usernameTxtBox' : "//input[@name='username']",
'passwordTxtBox' : "//input[@name='password']",
'submitButton' : "//input[@name='login']"
}
mydriver = webdriver.Firefox()
mydriver.get(baseurl)
mydriver.maximize_window()
#Clear Username TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).clear()
#Write Username in Username TextBox
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)
#Clear Password TextBox if already allowed "Remember Me"
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).clear()
#Write Password in password TextBox
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)
#Click Login button
mydriver.find_element_by_xpath(xpaths['submitButton']).click()
There is an another way that you can find xpath of any object -
Run script -
python Login.py
You can also use a CSS selector instead of xpath. CSS selectors are slightly faster than xpath in most cases, and are usually preferred over xpath (if there isn't an ID attribute on the elements you're interacting with).
Firepath can also capture the object's locator as a CSS selector if you move your cursor to the object. You'll have to update your code to use the equivalent find by CSS selector method instead -
find_element_by_css_selector(css_selector)
If you are in Jupyter notebook, you could run the following code to interactively display the dataframe in a well formatted table.
This answer builds on the to_html('temp.html') answer above, but instead of creating a file displays the well formatted table directly in the notebook:
from IPython.display import display, HTML
display(HTML(df.to_html()))
Credit for this code due to example at: Show DataFrame as table in iPython Notebook
A good solution that uses generics:
template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }
Then simply call arraysize(_Array);
to get the length of the array.
If you don't want the controller to decide the return object type, you should set your method return type as System.Net.Http.HttpResponseMessage
and use the below code to return the XML.
public HttpResponseMessage Authenticate()
{
//process the request
.........
string XML="<note><body>Message content</body></note>";
return new HttpResponseMessage()
{
Content = new StringContent(XML, Encoding.UTF8, "application/xml")
};
}
This is the quickest way to always return XML from Web API.
You can use SimpleDateFormat for this.
SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
Hope this helps you.
for (var k in target){
if (target.hasOwnProperty(k)) {
alert("Key is " + k + ", value is " + target[k]);
}
}
hasOwnProperty
is used to check if your target
really has that property, rather than having inherited it from its prototype. A bit simpler would be:
for (var k in target){
if (typeof target[k] !== 'function') {
alert("Key is " + k + ", value is" + target[k]);
}
}
It just checks that k
is not a method (as if target
is array
you'll get a lot of methods alerted, e.g. indexOf
, push
, pop
,etc.)
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(10.0, 100.0, 300.0, 20.0);
[self.view addSubview:button];
Here's one way:
Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = theDialog.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
Modified from here:MSDN OpenFileDialog.OpenFile
EDIT Here's another way more suited to your needs:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
string filename = theDialog.FileName;
string[] filelines = File.ReadAllLines(filename);
List<Employee> employeeList = new List<Employee>();
int linesPerEmployee = 4;
int currEmployeeLine = 0;
//parse line by line into instance of employee class
Employee employee = new Employee();
for (int a = 0; a < filelines.Length; a++)
{
//check if to move to next employee
if (a != 0 && a % linesPerEmployee == 0)
{
employeeList.Add(employee);
employee = new Employee();
currEmployeeLine = 1;
}
else
{
currEmployeeLine++;
}
switch (currEmployeeLine)
{
case 1:
employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
break;
case 2:
employee.Name = filelines[a].Trim();
break;
case 3:
employee.Address = filelines[a].Trim();
break;
case 4:
string[] splitLines = filelines[a].Split(' ');
employee.Wage = Convert.ToDouble(splitLines[0].Trim());
employee.Hours = Convert.ToDouble(splitLines[1].Trim());
break;
}
}
//Test to see if it works
foreach (Employee emp in employeeList)
{
MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
emp.Name + Environment.NewLine +
emp.Address + Environment.NewLine +
emp.Wage + Environment.NewLine +
emp.Hours + Environment.NewLine);
}
}
}
To see of the curent time is greater or equal to 14:08:10 do this:
if (time() >= strtotime("14:08:10")) {
echo "ok";
}
Depending on your input sources, make sure to account for timezone.
See PHP time() and PHP strtotime()
cmd /c pause | out-null
(It is not the PowerShell way, but it's so much more elegant.)
Save trees. Use one-liners.
How about putting the checkbox
into the label
, making the label automatically "click sensitive" for the check box, and giving the checkbox a onchange
event?
<label ..... ><input type="checkbox" onchange="toggleCheckbox(this)" .....>
function toggleCheckbox(element)
{
element.checked = !element.checked;
}
This will additionally catch users using a keyboard to toggle the check box, something onclick
would not.
Yeah, for most cases, you don't need to create a class with getters and setters. Just create a new Dictionary and bind it to the data source. Here's an example in VB using a for loop to set the DisplayMember and ValueMember of a combo box from a list:
Dim comboSource As New Dictionary(Of String, String)()
cboMenu.Items.Clear()
For I = 0 To SomeList.GetUpperBound(0)
comboSource.Add(SomeList(I).Prop1, SomeList(I).Prop2)
Next I
cboMenu.DataSource = New BindingSource(comboSource, Nothing)
cboMenu.DisplayMember = "Value"
cboMenu.ValueMember = "Key"
Then you can set up a data grid view's rows according to the value or whatever you need by calling a method on click:
Private Sub cboMenu_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMenu.SelectionChangeCommitted
SetListGrid(cboManufMenu.SelectedValue)
End Sub
To ensure that this is backwards compatible with iOS 7, you should check whether the user is running iOS 8 or iOS 7. For example:
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
//In ViewDidLoad
if(IS_OS_8_OR_LATER) {
[self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation];
Not precisely what you're asking for, but I think it's good advice.
Learn another language, doesn't matter too much which. Each language has it's own ideas and conventions that you can learn from. Learn about the differences in the languages and more importantly why
they're different. Try a purely functional language like Haskell and see some of the benefits (and challenges) of functions free of side-effects. See how you can apply some of the things you learn from other languages to Python.
Here is a formula if you know the max and min values of a range, and you want to generate numbers inclusive in between the range:
r = (rand() % (max + 1 - min)) + min
If you're willing to "take this to the console", I'd recommend enca
. Unlike the rather simplistic mb_detect_encoding
, it uses "a mixture of parsing, statistical analysis, guessing and black magic to determine their encodings" (lol - see man page). However, you usually have to pass the language of the input file if you want to detect such country-specific encodings. (However, mb_detect_encoding
essentially has the same requirement, as the encoding would have to appear "in the right place" in the list of passed encodings for it to be detectable at all.)
enca
also came up here: How to find encoding of a file in Unix via script(s)
While the answers explaining the exact differences are fine, I want to show how the relational algebra is transformed to SQL and what the actual value of the 3 concepts is.
The key concept in your question is the idea of a join. To understand a join you need to understand a Cartesian Product (the example is based on SQL where the equivalent is called a cross join as onedaywhen points out);
This isn't very useful in practice. Consider this example.
Product(PName, Price)
====================
Laptop, 1500
Car, 20000
Airplane, 3000000
Component(PName, CName, Cost)
=============================
Laptop, CPU, 500
Laptop, hdd, 300
Laptop, case, 700
Car, wheels, 1000
The Cartesian product Product x Component will be - bellow or sql fiddle. You can see there are 12 rows = 3 x 4. Obviously, rows like "Laptop" with "wheels" have no meaning, this is why in practice the Cartesian product is rarely used.
| PNAME | PRICE | CNAME | COST |
--------------------------------------
| Laptop | 1500 | CPU | 500 |
| Laptop | 1500 | hdd | 300 |
| Laptop | 1500 | case | 700 |
| Laptop | 1500 | wheels | 1000 |
| Car | 20000 | CPU | 500 |
| Car | 20000 | hdd | 300 |
| Car | 20000 | case | 700 |
| Car | 20000 | wheels | 1000 |
| Airplane | 3000000 | CPU | 500 |
| Airplane | 3000000 | hdd | 300 |
| Airplane | 3000000 | case | 700 |
| Airplane | 3000000 | wheels | 1000 |
JOINs are here to add more value to these products. What we really want is to "join" the product with its associated components, because each component belongs to a product. The way to do this is with a join:
Product JOIN Component ON Pname
The associated SQL query would be like this (you can play with all the examples here)
SELECT *
FROM Product
JOIN Component
ON Product.Pname = Component.Pname
and the result:
| PNAME | PRICE | CNAME | COST |
----------------------------------
| Laptop | 1500 | CPU | 500 |
| Laptop | 1500 | hdd | 300 |
| Laptop | 1500 | case | 700 |
| Car | 20000 | wheels | 1000 |
Notice that the result has only 4 rows, because the Laptop has 3 components, the Car has 1 and the Airplane none. This is much more useful.
Getting back to your questions, all the joins you ask about are variations of the JOIN I just showed:
Natural Join = the join (the ON clause) is made on all columns with the same name; it removes duplicate columns from the result, as opposed to all other joins; most DBMS (database systems created by various vendors such as Microsoft's SQL Server, Oracle's MySQL etc. ) don't even bother supporting this, it is just bad practice (or purposely chose not to implement it). Imagine that a developer comes and changes the name of the second column in Product from Price to Cost. Then all the natural joins would be done on PName AND on Cost, resulting in 0 rows since no numbers match.
Theta Join = this is the general join everybody uses because it allows you to specify the condition (the ON clause in SQL). You can join on pretty much any condition you like, for example on Products that have the first 2 letters similar, or that have a different price. In practice, this is rarely the case - in 95% of the cases you will join on an equality condition, which leads us to:
Equi Join = the most common one used in practice. The example above is an equi join. Databases are optimized for this type of joins! The oposite of an equi join is a non-equi join, i.e. when you join on a condition other than "=". Databases are not optimized for this! Both of them are subsets of the general theta join. The natural join is also a theta join but the condition (the theta) is implicit.
Source of information: university + certified SQL Server developer + recently completed the MOO "Introduction to databases" from Stanford so I dare say I have relational algebra fresh in mind.
Use sorted TreeMap
:
Map<String, Float> map = new TreeMap<>(yourMap);
It will automatically put entries sorted by keys. I think natural String
ordering will be fine in your case.
Note that HashMap
due to lookup optimizations does not preserve order.
Instead of using a regular expression, just check if string.length > 25
You should use the =
operator for string comparison:
Sourcesystem="ABC"
if [ "$Sourcesystem" = "XYZ" ]; then
echo "Sourcesystem Matched"
else
echo "Sourcesystem is NOT Matched $Sourcesystem"
fi;
man test
says that you use -z
to match for empty strings.
In one line we can set image with this code
[buttonName setBackgroundImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];
First, I wouldn't use document.body. Instead add an empty container:
index.html:
<html>
<head></head>
<body>
<div id="app"></div>
</body>
</html>
Then opt to only render your <App />
element:
main.js:
var App = require('./App.js');
ReactDOM.render(<App />, document.getElementById('app'));
Within App.js
you can import your other components and ignore your DOM render code completely:
App.js:
var SampleComponent = require('./SampleComponent.js');
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component!</h1>
<SampleComponent name="SomeName" />
</div>
);
}
});
SampleComponent.js:
var SampleComponent = React.createClass({
render: function() {
return (
<div>
<h1>Sample Component!</h1>
</div>
);
}
});
Then you can programmatically interact with any number of components by importing them into the necessary component files using require
.
When you're using iOS >= 4
dispatch_async(dispatch_get_main_queue(), ^{
//Your main thread code goes in here
NSLog(@"Im on the main thread");
});
jQuery's $.now() is an alias of new Date().getTime(), an internal Javascript function.
http://api.jquery.com/jquery.now/
This returns the number of seconds elapsed since 1970, commonly referred to (not necessarily correctly) as Unix Time, Epoch or Timestamp, depending on the circles you fall in. It can be really handy for calculating the difference between dates/times using simple maths. It doesn't have any TimeZone information and is always UTC.
http://en.wikipedia.org/wiki/Unix_time
There is no need to use jQuery as other than this alias, it does little else to help with date/time manipulation.
If you are looking for a quick and dirty way of representing the time in text, the Javascript Date object has a "toString" prototype that will return an ISO formatted Date Time.
new Date().toString();
//returns "Thu Apr 30 2015 14:37:36 GMT+0100 (BST)"
More than likely though, you will want to customize your formatting. The Date object has the ability to pull out your relevant details so you can build your own string representation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var d = new Date(); //without params it defaults to "now"
var t = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
//Will return 14:37:36
However, as you have asked for a jQuery solution - it is perhaps likely that you are working with older browsers. If you want to do more specific things - especially interpreting strings into Date objects (useful for API responses), you might want to look at Moment.js.
This will ensure cross browser compatibility and has much improved formatting without having to concatenate lots of strings to together! For example:
moment().format('hh:mm:ss');
//Will return 14:37:36
You can try this:
var Enum = Object.freeze({
Role: Object.freeze({ Administrator: 1, Manager: 2, Supervisor: 3 }),
Color:Object.freeze({RED : 0, GREEN : 1, BLUE : 2 })
});
alert(Enum.Role.Supervisor);
alert(Enum.Color.GREEN);
var currentColor=0;
if(currentColor == Enum.Color.RED) {
alert('Its Red');
}
for WORDPRESS:
global $wpdb;
$your_table = $wpdb->prefix. 'My_Table_Name';
$your_column = 'My_Column_Name';
if (!in_array($your_column, $wpdb->get_col( "DESC " . $your_table, 0 ) )){ $result= $wpdb->query(
"ALTER TABLE $your_table ADD $your_column VARCHAR(100) CHARACTER SET utf8 NOT NULL " //you can add positioning phraze: "AFTER My_another_column"
);}
r
is a numpy (rec)array. So r["dt"] >= startdate
is also a (boolean)
array. For numpy arrays the &
operation returns the elementwise-and of the two
boolean arrays.
The NumPy developers felt there was no one commonly understood way to evaluate
an array in boolean context: it could mean True
if any element is
True
, or it could mean True
if all elements are True
, or True
if the array has non-zero length, just to name three possibilities.
Since different users might have different needs and different assumptions, the
NumPy developers refused to guess and instead decided to raise a ValueError
whenever one tries to evaluate an array in boolean context. Applying and
to
two numpy arrays causes the two arrays to be evaluated in boolean context (by
calling __bool__
in Python3 or __nonzero__
in Python2).
Your original code
mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[mask]
looks correct. However, if you do want and
, then instead of a and b
use (a-b).any()
or (a-b).all()
.
As others have said, the second approach is usually preferred.
The two code snippets are not exactly equivalent however: the first one actually sets window.opener
to the window object itself, whereas the second will leave it as it is, at least under Firefox.
There must be something wrong with the way you access the array's items. Here's how it's done:
for elem in "${files[@]}"
...
From the bash manpage:
Any element of an array may be referenced using ${name[subscript]}. ... If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word.
Of course, you should also use double quotes when accessing a single member
cp "${files[0]}" /tmp
You can use open(name, 'a')
However, when you enter filename, use inverted commas on both sides, otherwise ".txt"
cannot be added to filename
use
window.location.replace("login.php");
or simply window.location("login.php");
It is better than using window.location.href =,
because replace()
does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href
. If you want to simulate an HTTP redirect, use location.replace
.
Here's a solution for jQuery 1.4.x (unfortunately, the accepted answer didn't work for jquery 1.4.1)
$.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.bind(name, fn);
// Thanks to a comment by @Martin, adding support for
// namespaced events too.
var handlers = this.data('events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var copy = {1: null};
var last = 0, lastValue = null;
$.each(handlers, function(name, value) {
//console.log(name + ": " + value);
var isNumber = !isNaN(name);
if(isNumber) {last = name; lastValue = value;};
var key = isNumber ? (parseInt(name) + 1) : name;
copy[key] = value;
});
copy[1] = lastValue;
this.data('events')[name.split('.')[0]] = copy;
};
i know this is late , but you should try redirecting to a path and not to a file ha ha
Something along the lines:
<VirtualHost hostname:80>
...
SetEnv VARIABLE_NAME variable_value
...
</VirtualHost>
Use:
Write "Stuff to write" | Out-File Outputfile.txt -Append
One of alternatives is MSYS2 , in another words "MinGW-w64"/Git Bash. You can simply ssh to Unix machines and run most of linux commands from it. Also install tmux!
To install tmux in MSYS2:
run command pacman -S tmux
To run tmux on Git Bash:
install MSYS2 and copy tmux.exe
and msys-event-2-1-6.dll
from MSYS2 folder C:\msys64\usr\bin
to your Git Bash directory C:\Program Files\Git\usr\bin
.
Easiest way is used the Date Using Date() and getTime()
Date dte=new Date();
long milliSeconds = dte.getTime();
String strLong = Long.toString(milliSeconds);
System.out.println(milliSeconds)
Use a post-build action in your project, and add the commands to copy the offending DLL. The post-build action are written as a batch script.
The output directory can be referenced as $(OutDir)
. The project directory is available as $(ProjDir)
. Try to use relative pathes where applicable, so that you can copy or move your project folder without breaking the post-build action.
The uname command (http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/uname.1.html) with no parameters should tell you the operating system name. I'd use that, then make conditionals based on the return value.
Example
UNAME := $(shell uname)
ifeq ($(UNAME), Linux)
# do something Linux-y
endif
ifeq ($(UNAME), Solaris)
# do something Solaris-y
endif
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
You just add one line css:
.app a {
display: inline-block;
}
To count number of commits by a given author (or all authors) on a given branch you can use git-shortlog; see especially its --numbered
and --summary
options, e.g. when run on git repository:
$ git shortlog v1.6.4 --numbered --summary
6904 Junio C Hamano
1320 Shawn O. Pearce
1065 Linus Torvalds
692 Johannes Schindelin
443 Eric Wong
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
Im doing this in coffeescript
booking_module_time_clock_convert_id = () ->
if $('.booking_module_time_clock').length
idnumber = 1
for a in $('.booking_module_time_clock')
elementID = $(a).attr("id")
$(a).attr( 'id', "#{elementID}_#{idnumber}" )
idnumber++
There are many ways to get a page from the command line... but it also depends if you want the code source or the page itself:
If you need the code source:
with curl:
curl $url
with wget:
wget -O - $url
but if you want to get what you can see with a browser, lynx can be useful:
lynx -dump $url
I think you can find so many solutions for this little problem, maybe you should read all man pages for those commands. And don't forget to replace $url
by your URL :)
Good luck :)
You can use the following for an awk solution -
awk '/^#/ {sub(/#.*/,"");getline;}1' inputfile
A more elegant solution could be:
def progressBar(current, total, barLength = 20):
percent = float(current) * 100 / total
arrow = '-' * int(percent/100 * barLength - 1) + '>'
spaces = ' ' * (barLength - len(arrow))
print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
call this function with value
and endvalue
, result should be
Progress: [-------------> ] 69 %
Note: Python 2.x version here.