This adds #
at the beginning of every line:
:%s/^/#/
And people will stop complaining about your lack of properly commenting scripts.
set nu
set ai
set tabstop=4
set ls=2
set autoindent
Add the above code in your .vimrc file. if .vimrc file is not present please create in your home directory (/home/name of user)
set nu -> This makes Vim display line numbers
set ai -> This makes Vim enable auto-indentation
set ls=2 -> This makes Vim show a status line
set tabstop=4 -> This makes Vim set tab of length 4 spaces (it is 8 by default)
The filename will also be displayed.
This Perl one-liner comments out lines 1 to 3 of the file orig.sh
inclusive (where the first line is numbered 0), and writes the commented version to cmt.sh
.
perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh
Obviously you can change the boundary numbers as required.
If you want to edit the file in place, it's even shorter:
perl -in -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh
$ cat orig.sh
a
b
c
d
e
f
$ perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh
$ cat cmt.sh
a
#b
#c
#d
e
f
If you want to do it while keeping the user interaction on.
In my case I am using (or rather misusing) isFocused
self.myField.inputView = UIView()
This way it will focus but keyboard won't show up.
This solution requires the Apache Commons IO library to be added to the build path. It works by reading the entire file and writing each line back but only if the search term is not contained.
public static void removeLineFromFile(File targetFile, String searchTerm)
throws IOException
{
StringBuffer fileContents = new StringBuffer(
FileUtils.readFileToString(targetFile));
String[] fileContentLines = fileContents.toString().split(
System.lineSeparator());
emptyFile(targetFile);
fileContents = new StringBuffer();
for (int fileContentLinesIndex = 0; fileContentLinesIndex < fileContentLines.length; fileContentLinesIndex++)
{
if (fileContentLines[fileContentLinesIndex].contains(searchTerm))
{
continue;
}
fileContents.append(fileContentLines[fileContentLinesIndex] + System.lineSeparator());
}
FileUtils.writeStringToFile(targetFile, fileContents.toString().trim());
}
private static void emptyFile(File targetFile) throws FileNotFoundException,
IOException
{
RandomAccessFile randomAccessFile = new RandomAccessFile(targetFile, "rw");
randomAccessFile.setLength(0);
randomAccessFile.close();
}
If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.
I had this problem but I solved it by installing the version of the ruby that is specified in my gem file using the RVM
rvm install (ruby version)
After the installation, I use the following command to use the the version that you installed.
rvm --default use (ruby version)
You have to install bundler by using the following command in order to use the latest version
gem install bundler
After the above steps, you can now run following command to install the gems specified on the gemfile
bundle install
I can give you a little tip if you want do like this:
<div style="position:relative;width:100px;height:100px">
<img src="loading.jpg" style='position:absolute;width:100px;height:100px;z-index:0'/>
<img onLoad="$(this).fadeIn('normal').siblings('img').fadeOut('normal')" src="picture.jpg" style="display:none;position:absolute;width:100px;height:100px;z-index:1"/>
</div>
If you do that when the browser caches pictures, it's no problem always img shown but loading img under real picture.
The fastest method is:
function escapeHTML(html) {
return document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML;
}
This method is about twice faster than the methods based on 'replace', see http://jsperf.com/htmlencoderegex/35 .
You should not replace the text entirely. Add the text after the "# END WordPress".
Let's Encrypt is a free, automated, and open certificate authority made by the Internet Security Research Group (ISRG). It is sponsored by well-known organisations such as Mozilla, Cisco or Google Chrome. All modern browsers are compatible and trust Let's Encrypt.
All certificates are free (even wildcard certificates)! For security reasons, the certificates expire pretty fast (after 90 days). For this reason, it is recommended to install an ACME client, which will handle automatic certificate renewal.
There are many clients you can use to install a Let's Encrypt certificate:
Let’s Encrypt uses the ACME protocol to verify that you control a given domain name and to issue you a certificate. To get a Let’s Encrypt certificate, you’ll need to choose a piece of ACME client software to use. - https://letsencrypt.org/docs/client-options/
Try this method. It should work when field when you want to store image is of type byte
.
First it creates byte[]
for image. Then it saves it to the DB using IDataParameter
of type binary
.
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
public static void PerisitImage(string path, IDbConnection connection)
{
using (var command = connection.CreateCommand ())
{
Image img = Image.FromFile (path);
MemoryStream tmpStream = new MemoryStream();
img.Save (tmpStream, ImageFormat.Png); // change to other format
tmpStream.Seek (0, SeekOrigin.Begin);
byte[] imgBytes = new byte[MAX_IMG_SIZE];
tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);
command.CommandText = "INSERT INTO images(payload) VALUES (:payload)";
IDataParameter par = command.CreateParameter();
par.ParameterName = "payload";
par.DbType = DbType.Binary;
par.Value = imgBytes;
command.Parameters.Add(par);
command.ExecuteNonQuery ();
}
}
I would do it this way, so you won't end up with duplicate entries if the script is run multiple times.
@echo off
SET NEWLINE=^& echo.
FIND /C /I "ns1.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^62.116.159.4 ns1.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
FIND /C /I "ns2.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^217.160.113.37 ns2.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
FIND /C /I "ns3.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^89.146.248.4 ns3.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
FIND /C /I "ns4.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^74.208.254.4 ns4.intranet.de>>%WINDIR%\System32\drivers\etc\hosts
Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.
It is enough to register an event function for accelerometer like so:
if(window.DeviceMotionEvent){
window.addEventListener("devicemotion", motion, false);
}else{
console.log("DeviceMotionEvent is not supported");
}
with the handler:
function motion(event){
console.log("Accelerometer: "
+ event.accelerationIncludingGravity.x + ", "
+ event.accelerationIncludingGravity.y + ", "
+ event.accelerationIncludingGravity.z
);
}
And for magnetometer a following event handler has to be registered:
if(window.DeviceOrientationEvent){
window.addEventListener("deviceorientation", orientation, false);
}else{
console.log("DeviceOrientationEvent is not supported");
}
with a handler:
function orientation(event){
console.log("Magnetometer: "
+ event.alpha + ", "
+ event.beta + ", "
+ event.gamma
);
}
There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).
There is a simple working code on GitHub
Have you tried using JSONArray.getJSONObject(int), and JSONArray.length() to create your for-loop:
for (int i = 0; i < recs.length(); ++i) {
JSONObject rec = recs.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
string filePath = @"C:\styles\MyStyles.css";
string siteURL = "http://example.org/";
string libraryName = "Style Library";
using (SPSite oSite = new SPSite(siteURL))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(filePath))
throw new FileNotFoundException("File not found.", filePath);
SPFolder libFolder = oWeb.Folders[libraryName];
// Prepare to upload
string fileName = System.IO.Path.GetFileName(filePath);
FileStream fileStream = File.OpenRead(filePath);
//Check the existing File out if the Library Requires CheckOut
if (libFolder.RequiresCheckout)
{
try {
SPFile fileOld = libFolder.Files[fileName];
fileOld.CheckOut();
} catch {}
}
// Upload document
SPFile spfile = libFolder.Files.Add(fileName, fileStream, true);
// Commit
myLibrary.Update();
//Check the File in and Publish a Major Version
if (libFolder.RequiresCheckout)
{
spFile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
spFile.Publish("Publish Comment");
}
}
}
It's actually very easy to handle using Scala f
interpolator - https://docs.scala-lang.org/overviews/core/string-interpolation.html
Suppose we want to round till 2 decimal places:
scala> val sum = 1 + 1/4D + 1/7D + 1/10D + 1/13D
sum: Double = 1.5697802197802198
scala> println(f"$sum%1.2f")
1.57
In line with billjamesdev answer, here is another approach to validate an URL without using a RegEx:
From Apache Commons Validator lib, look at class UrlValidator. Some example code:
Construct a UrlValidator with valid schemes of "http", and "https".
String[] schemes = {"http","https"}.
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("ftp://foo.bar.com/")) {
System.out.println("url is valid");
} else {
System.out.println("url is invalid");
}
prints "url is invalid"
If instead the default constructor is used.
UrlValidator urlValidator = new UrlValidator();
if (urlValidator.isValid("ftp://foo.bar.com/")) {
System.out.println("url is valid");
} else {
System.out.println("url is invalid");
}
prints out "url is valid"
.black-strip
{ width:100%;
height: 30px;
background-color:black;
}
.green-strip
{ width:0%;
height: 30px;
background-color:lime;
animation-name: progress-bar;
animation-duration: 4s;
animation-iteration-count: infinite;
}
@keyframes progress-bar {
from{width:0%}
to{width:100%}
}
<div class="black-strip">
<div class="green-strip">
</div>
</div>
Running Latest Code Igniter 3.10
$this->load->helper('uri'); // or you can autoload it in config
print base_url($this->uri->uri_string());
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
You could even do it like this:
Example
grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'
This will search for the string 'windows' in all files relative to the current directory and replace 'windows' with 'linux' for each occurrence of the string in each file.
fill_parent
will make the width or height of the element to be as
large as the parent element, in other words, the container.
wrap_content
will make the width or height be as large as needed to
contain the elements within it.
You could use the string to index into a hash table of function pointers.
Edit: glib has a hash table implementation that supports strings as keys and arbitrary pointers as values: http://library.gnome.org/devel/glib/stable/glib-Hash-Tables.html
In order to include a global library, eg jquery.js
file in the scripts array from angular-cli.json
(angular.json
when using angular 6+):
"scripts": [
"../node_modules/jquery/dist/jquery.js"
]
After this, restart ng serve if it is already started.
$past = time() - 3600;
foreach ( $_COOKIE as $key => $value )
{
setcookie( $key, $value, $past, '/' );
}
Even better is however to remember (or store it somewhere) which cookies are set with your application on a domain and delete all those directly.
That way you can be sure to delete all values correctly.
Try this:
yAxis: {min: 0, max: 100}
See this jsfiddle example
I recently came across Python 3 interpreter at CompileOnline.
Before run the jar check Main-Class: classname
is available or not in MANIFEST.MF file. MANIFEST.MF is present in jar.
java -jar filename.jar
See: http://jsfiddle.net/thirtydot/EDp8R/
text-align: justify
combined with .stretch
is what's handling the positioning.display:inline-block; *display:inline; zoom:1
fixes inline-block
for IE6/7, see here.font-size: 0; line-height: 0
fixes a minor issue in IE6.#container {_x000D_
border: 2px dashed #444;_x000D_
height: 125px;_x000D_
text-align: justify;_x000D_
-ms-text-justify: distribute-all-lines;_x000D_
text-justify: distribute-all-lines;_x000D_
/* just for demo */_x000D_
min-width: 612px;_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box2,_x000D_
.box3,_x000D_
.box4 {_x000D_
width: 150px;_x000D_
height: 125px;_x000D_
vertical-align: top;_x000D_
display: inline-block;_x000D_
*display: inline;_x000D_
zoom: 1_x000D_
}_x000D_
_x000D_
.stretch {_x000D_
width: 100%;_x000D_
display: inline-block;_x000D_
font-size: 0;_x000D_
line-height: 0_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box3 {_x000D_
background: #ccc_x000D_
}_x000D_
_x000D_
.box2,_x000D_
.box4 {_x000D_
background: #0ff_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="box1"></div>_x000D_
<div class="box2"></div>_x000D_
<div class="box3"></div>_x000D_
<div class="box4"></div>_x000D_
<span class="stretch"></span>_x000D_
</div>
_x000D_
The extra span
(.stretch
) can be replaced with :after
.
This still works in all the same browsers as the above solution. :after
doesn't work in IE6/7, but they're using distribute-all-lines
anyway, so it doesn't matter.
See: http://jsfiddle.net/thirtydot/EDp8R/3/
There's a minor downside to :after
: to make the last row work perfectly in Safari, you have to be careful with the whitespace in the HTML.
Specifically, this doesn't work:
<div id="container">
..
<div class="box3"></div>
<div class="box4"></div>
</div>
And this does:
<div id="container">
..
<div class="box3"></div>
<div class="box4"></div></div>
You can use this for any arbitrary number of child div
s without adding a boxN
class to each one by changing
.box1, .box2, .box3, .box4 { ...
to
#container > div { ...
This selects any div that is the first child of the #container
div, and no others below it. To generalize the background colors, you can use the CSS3 nth-order selector, although it's only supported in IE9+ and other modern browsers:
.box1, .box3 { ...
becomes:
#container > div:nth-child(odd) { ...
See here for a jsfiddle example.
Let's say your volume name is data_volume
. You can use the following commands to backup and restore the volume to and from a docker image named data_image
:
To backup:
docker run --rm --mount source=data_volume,destination=/data alpine tar -c -f- data | docker run -i --name data_container alpine tar -x -f-
docker container commit data_container data_image
docker rm data_container
To restore:
docker run --rm data_image tar -c -f- data | docker run -i --rm --mount source=data_volume,destination=/data alpine tar -x -f-
In my case the issue was that my default kit's Qt version
was None
.
Go to Tools -> Options... -> Build & Run -> Kits
tab, click on the kit you want to make as default and you'll see a list of fields beneath, one of which is Qt version
. If it's None
, change it to one of the versions available to you in the Qt versions
tab which is just next to the Kits
tab.
npm install --global windows-build-tools
just run this command via powershell (right click and run as administrator!)
worked for me..
None of the above worked on Sublime Text 3 on Windows 10, Ctrl + Shift + ' with the Emmet Sublime Text 3 plugin works great and was the only working solution for me. Ctrl + Shift + T re-opens the last closed item and to my knowledge of Sublime, has done so since early builds of ST3 or late builds of ST2.
You might also want to check out the PyPy project - they have a Python to (anything) compiler, including Python to Javascript, C, and llvm. This allows you to write your code in Python and then compile it into Javascript as you desire.
Also, check out the informative blog:
Unfortunately though, you can't convert Javascript to Python this way. It seems to work really well overall, they used to have a Javascript (made from compiled Python) version of the Bub'n'Bros game online (though the server has been down for a while).
You use this signature: (in c#) static void Main(string[] args)
This article may help to explain the role of the main function in programming as well: http://en.wikipedia.org/wiki/Main_function_(programming)
Here is a little example for you:
class Program
{
static void Main(string[] args)
{
bool doSomething = false;
if (args.Length > 0 && args[0].Equals("doSomething"))
doSomething = true;
if (doSomething) Console.WriteLine("Commandline parameter called");
}
}
There's no much point in doing that, because View
should be generating html, not the controller. But anyways, you could use Controller.Content method, which gives you ability to specify result html, also content-type and encoding
public ActionResult Index()
{
return Content("<html></html>");
}
Or you could use the trick built in asp.net-mvc framework - make the action return string directly. It will deliver string contents into users's browser.
public string Index()
{
return "<html></html>";
}
In fact, for any action result other than ActionResult
, framework tries to serialize it into string and write to response.
I just wrote this cos none of the answers already here were simple enough. You can replace the hardcoded 128 for whatever you want or base them off the size of the original image. All i wanted was to rescale the image into a 128x128 image, keeping the aspect ratio and centering the result in the new image.
private Bitmap CreateLargeIconForImage(Bitmap src)
{
Bitmap bmp = new Bitmap(128, 128);
Graphics g = Graphics.FromImage(bmp);
float scale = Math.Max((float)src.Width / 128.0f, (float)src.Height / 128.0f);
PointF p = new PointF(128.0f - ((float)src.Width / scale), 128.0f - ((float)src.Height / scale));
SizeF size = new SizeF((float)src.Width / scale, (float)src.Height / scale);
g.DrawImage(src, new RectangleF(p, size));
return bmp;
}
Guess I'm too late...
Came across the same problem today; here is my solution using FileSystemObject
:
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String
fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close
Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
I got a link with your requirement.Combine CRT and KEY Files into a PFX with OpenSSL
Extracts from the above link:
First we need to extract the root CA certificate from the existing .crt file, because we need this later. So open up the .crt and click on the Certification Path tab.
Click the topmost certificate (In this case VeriSign) and hit View Certificate. Select the Details tab and hit Copy to File…
Select Base-64 encoded X.509 (.CER) certificate Save it as rootca.cer or something similar. Place it in the same folder as the other files.
Rename it from rootca.cer to rootca.crt Now we should have 3 files in our folder from which we can create a PFX file.
Here is where we need OpenSSL. We can either download and install it on Windows, or simply open terminal on OSX.
EDIT:
There is a support link with step by step information on how to do install the certificate.
After successfully install, export the certificate, choose .pfx
format, include private key.
The imported file can be uploaded to server.
Try this:
With xlApp.ActiveSheet.Pictures.Insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 75
.Height = 100
End With
.Left = xlApp.ActiveSheet.Cells(i, 20).Left
.Top = xlApp.ActiveSheet.Cells(i, 20).Top
.Placement = 1
.PrintObject = True
End With
It's better not to .select anything in Excel, it is usually never necessary and slows down your code.
I imagine that these might possibly be changed with some styling options. But as far as default values go, these are taken from my version of Excel 2010 which should have the defaults.
"Bad" Red Font: 156, 0, 6; Fill: 255, 199, 206
"Good" Green Font: 0, 97, 0; Fill: 198, 239, 206
"Neutral" Yellow Font: 156, 101, 0; Fill: 255, 235, 156
<com.google.android.material.textfield.TextInputLayout
android:hint="Hint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/TextInputLayoutHint">
<androidx.appcompat.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:paddingTop="@dimen/_5sdp"
android:paddingBottom="@dimen/_5sdp"
android:textColor="#000000"
android:textColorHint="#959aa6" />
</com.google.android.material.textfield.TextInputLayout>
res/values/styles.xml
<style name="TextInputLayoutHint" parent="">
<item name="android:textColorHint">#545454</item>
<item name="colorControlActivated">#2dbc99</item>
<item name="android:textSize">11sp</item>
</style>
Suppose you have this file:
something
name
comment
phone
email
something else
and more ...
You want to add "vendor_" in front of "name", "comment", "phone", and "email", regardless of where they appear in the file.
:%s/\<\(name\|comment\|phone\|email\)\>/vendor_\1/gc
The c
flag will prompt you for confirmation. You can drop that if you don't want the prompt.
JFrame.dispose()
public void dispose()
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).
Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.
System.exit()
public static void exit(int status)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n)
is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
Depends on the use case. All mobile devices require a battery. If what you're after is compute power without draining the battery use the Battery Status API:
navigator.getBattery().then(battery => {
battery.charging ? 'charging' : 'not charging';
});
If what you're looking for is presentational use matchMedia
, which returns a Boolean value:
if (window.matchMedia("(min-width: 400px)").matches) {
/* the viewport is at least 400 pixels wide */
} else {
/* the viewport is less than 400 pixels wide */
}
Or combine them for an even better user experience on tablet devices.
You can try @Rule
annotation. Here is the example from the docs:
public static class UsesExternalResource {
Server myServer = new Server();
@Rule public ExternalResource resource = new ExternalResource() {
@Override
protected void before() throws Throwable {
myServer.connect();
};
@Override
protected void after() {
myServer.disconnect();
};
};
@Test public void testFoo() {
new Client().run(myServer);
}
}
You just need to create FileResource
class extending ExternalResource
.
Full Example
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
public class TestSomething
{
@Rule
public ResourceFile res = new ResourceFile("/res.txt");
@Test
public void test() throws Exception
{
assertTrue(res.getContent().length() > 0);
assertTrue(res.getFile().exists());
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import org.junit.rules.ExternalResource;
public class ResourceFile extends ExternalResource
{
String res;
File file = null;
InputStream stream;
public ResourceFile(String res)
{
this.res = res;
}
public File getFile() throws IOException
{
if (file == null)
{
createFile();
}
return file;
}
public InputStream getInputStream()
{
return stream;
}
public InputStream createInputStream()
{
return getClass().getResourceAsStream(res);
}
public String getContent() throws IOException
{
return getContent("utf-8");
}
public String getContent(String charSet) throws IOException
{
InputStreamReader reader = new InputStreamReader(createInputStream(),
Charset.forName(charSet));
char[] tmp = new char[4096];
StringBuilder b = new StringBuilder();
try
{
while (true)
{
int len = reader.read(tmp);
if (len < 0)
{
break;
}
b.append(tmp, 0, len);
}
reader.close();
}
finally
{
reader.close();
}
return b.toString();
}
@Override
protected void before() throws Throwable
{
super.before();
stream = getClass().getResourceAsStream(res);
}
@Override
protected void after()
{
try
{
stream.close();
}
catch (IOException e)
{
// ignore
}
if (file != null)
{
file.delete();
}
super.after();
}
private void createFile() throws IOException
{
file = new File(".",res);
InputStream stream = getClass().getResourceAsStream(res);
try
{
file.createNewFile();
FileOutputStream ostream = null;
try
{
ostream = new FileOutputStream(file);
byte[] buffer = new byte[4096];
while (true)
{
int len = stream.read(buffer);
if (len < 0)
{
break;
}
ostream.write(buffer, 0, len);
}
}
finally
{
if (ostream != null)
{
ostream.close();
}
}
}
finally
{
stream.close();
}
}
}
If you don't want to add any code to the form (as mentioned in the comments to @shadfc's Answer), it is certainly possible, here are two options.
First, you just reference the fields individually in the HTML, rather than the entire form at once:
<form action="" method="post">
<ul class="contactList">
<li id="subject" class="contact">{{ form.subject }}</li>
<li id="email" class="contact">{{ form.email }}</li>
<li id="message" class="contact">{{ form.message }}</li>
</ul>
<input type="submit" value="Submit">
</form>
(Note that I also changed it to a unsorted list.)
Second, note in the docs on outputting forms as HTML, Django:
The Field id, is generated by prepending 'id_' to the Field name. The id attributes and tags are included in the output by default.
All of your form fields already have a unique id. So you would reference id_subject in your CSS file to style the subject field. I should note, this is how the form behaves when you take the default HTML, which requires just printing the form, not the individual fields:
<ul class="contactList">
{{ form }} # Will auto-generate HTML with id_subject, id_email, email_message
{{ form.as_ul }} # might also work, haven't tested
</ul>
See the previous link for other options when outputting forms (you can do tables, etc).
Note - I realize this isn't the same as adding a class to each element (if you added a field to the Form, you'd need to update the CSS also) - but it's easy enough to reference all of the fields by id in your CSS like this:
#id_subject, #id_email, #email_message
{color: red;}
Follow these steps:
sudo xcodebuild --license
.import sys
sys.executable
will give you the interpreter. You can select the interpreter you want when you create a new notebook. Make sure the path to your anaconda interpreter is added to your path (somewhere in your bashrc/bash_profile most likely).
For example I used to have the following line in my .bash_profile, that I added manually :
export PATH="$HOME/anaconda3/bin:$PATH"
EDIT: As mentioned in a comment, this is not the proper way to add anaconda to the path. Quoting Anaconda's doc, this should be done instead after install, using conda init
:
Should I add Anaconda to the macOS or Linux PATH?
We do not recommend adding Anaconda to the PATH manually. During installation, you will be asked “Do you wish the installer to initialize Anaconda3 by running conda init?” We recommend “yes”. If you enter “no”, then conda will not modify your shell scripts at all. In order to initialize after the installation process is done, first run
source <path to conda>/bin/activate
and then runconda init
This will solve the problem:
const json_data = {"2013-01-21":1,"2013-01-22":7};
const arr = Object.keys(json_data).map((key) => [key, json_data[key]]);
console.log(arr);
Or using Object.entries() method:
console.log(Object.entries(json_data));
In both the cases, output will be:
/* output:
[['2013-01-21', 1], ['2013-01-22', 7]]
*/
Use
void callClass(Class classObject)
{
//do something with class
}
A Class
is also a Java object, so you can refer to it by using its type.
Read more about it from official documentation.
Just to improve Wael's answer and put it on a single line:
dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);
UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.
I had a form with 11 submit buttons on it, and it would always use the first submit button when the user pressed enter. I read elsewhere that it is not a good idea (bad practice) to have more than one submit button on a form, and the best way to do this is have the button you want as default, as the only submit button on the form. The other buttons should be made into "TYPE=BUTTON" and an onClick event added that calls your own submit routine in Javascript. Something like this :-
<SCRIPT Language="JavaScript">
function validform()
{
// do whatever you need to validate the form, and return true or false accordingly
}
function mjsubmit()
{
if (validform()) { document.form1.submit(); return true;}
return false;
}
</SCRIPT>
<INPUT TYPE=BUTTON NAME="button1" VALUE="button1" onClick="document.form1.submitvalue='button1'; return mjsubmit();">
<INPUT TYPE=BUTTON NAME="button2" VALUE="button2" onClick="document.form1.submitvalue='button2'; return mjsubmit();">
<INPUT TYPE=SUBMIT NAME="button3" VALUE="button3" onClick="document.form1.submitvalue='button3'; return validform();">
<INPUT TYPE=BUTTON NAME="button4" VALUE="button4" onClick="document.form1.submitvalue='button4'; return mjsubmit();">
Here, button3 is the default, and although you are programmatically submitting the form with the other buttons, the mjsubmit routine validates them. HTH.
If you have
$_POST['period'] = "2012-02";
First, find the first day of the month:
$first_day = $_POST['period'] . "-01"
Then this query will use an index on Date
if you have one:
$q = "
SELECT *
FROM projects
WHERE Date BETWEEN '$first_day'
AND LAST_DAY( '$first_day' )
" ;
One could also use inclusive-exclusive intervals, which work pretty good (you don't have to worry if the column is DATE
, DATETIME
or TIMESTAMP
, nor about the precision:
$q = "
SELECT *
FROM projects
WHERE Date >= '$first_day'
AND Date < '$first_day' + INTERVAL 1 MONTH
" ;
Security warning:
You should properly escape these values or use prepared statements. In short, use whatever method is recommended these days in PHP, to avoid any SQL injection issues.
You forgot to add the global operator. Use this:
var s = "04.07.2012";_x000D_
alert(s.replace(new RegExp("[0-9]","g"), "X"));
_x000D_
I had the same problem ("Uncaught TypeError: Cannot read property 'top' of undefined")
I tried every solution I could find and noting helped. But then I've spotted that my DIV had two IDs.
So, I removed second ID and it worked.
I just wish somebody told me to check my IDs earlier))
You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
meVeekay's answer was good and am just making it more improvised by doing 2 things.
Check whether browser supports HTML5 FileReader() or not.
Allow only image file to be upload by checking its extension.
HTML :
<div id="wrapper">
<input id="fileUpload" type="file" />
<br />
<div id="image-holder"></div>
</div>
jQuery :
$("#fileUpload").on('change', function () {
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
For detail understanding of FileReader()
Check this Article : Using FileReader() preview image before uploading.
From iOS 6 and later UITextAlignment
is deprecated. use NSTextAlignment
myLabel.textAlignment = NSTextAlignmentCenter;
Swift Version from iOS 6 and later
myLabel.textAlignment = .center
Just had the same problem here. In my case, the bat files had space " " After getting rid of spaces from filename and change into underscore, bat file worked
sample before it wont start
"x:\Update & pull.bat"
after rename
"x:\Update_and_pull.bat"
please try following to generate
function addRow()
{
var e1 = document.createElement("input");
e1.type = "text";
e1.name = "name1";
var cont = document.getElementById("content")
cont.appendChild(e1);
}
For linux users, and to sum up and add to what others have said here, you should know the following:
Global variables are not evil. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override).
The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:
export CLASSPATH=.
export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.
echo $CLASSPATH
is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.
Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
Frankly the errors are really hard to see, especially if only one character is "underwaved" in a sea of Java code. I used the instructions above to make the background an orangey-red color and things are much more obvious.
The builtin copy(dst, src)
copies min(len(dst), len(src))
elements.
So if your dst
is empty (len(dst) == 0
), nothing will be copied.
Try tmp := make([]int, len(arr))
(Go Playground):
arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)
Output (as expected):
[1 2 3]
[1 2 3]
Unfortunately this is not documented in the builtin
package, but it is documented in the Go Language Specification: Appending to and copying slices:
The number of elements copied is the minimum of
len(src)
andlen(dst)
.
Edit:
Finally the documentation of copy()
has been updated and it now contains the fact that the minimum length of source and destination will be copied:
Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).
It's better practise, safer and more polite to detect if the process is running and tell the user to close it manually. Of course you could also add a timeout and kill the process if they've gone away...
You probably need to change your mount command from:
[root@localhost Desktop]# sudo mount -t vboxsf D:\share_folder_vm \share_folder
to:
[root@localhost Desktop]# sudo mount -t vboxsf share_name \share_folder
where share_name is the "Name" of the share in the VirtualBox -> Shared Folders -> Folder List list box. The argument you have ("D:\share_folder_vm") is the "Path" of the share on the host, not the "Name".
For those coming in 2018:
The ONLY Solution worked for me:
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Line to show.";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
and its very important to keep de "4096" part because it seems that "fills" the buffer...
Main advantage of MVC architecture is differentiating the layers of a project in Model,View and Controller for the Re-usability of code, easy to maintain code and maintenance. The best thing is the developer feels good to add some code in between the project maintenance.
Here you can see the some more points on Main Advantages of MVC Architecture.
Typescript version:
export class Utility {
public static convertModelToFormData(model: any, form: FormData = null, namespace = ''): FormData {
let formData = form || new FormData();
let formKey;
for (let propertyName in model) {
if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
let formKey = namespace ? `${namespace}[${propertyName}]` : propertyName;
if (model[propertyName] instanceof Date)
formData.append(formKey, model[propertyName].toISOString());
else if (model[propertyName] instanceof Array) {
model[propertyName].forEach((element, index) => {
const tempFormKey = `${formKey}[${index}]`;
this.convertModelToFormData(element, formData, tempFormKey);
});
}
else if (typeof model[propertyName] === 'object' && !(model[propertyName] instanceof File))
this.convertModelToFormData(model[propertyName], formData, formKey);
else
formData.append(formKey, model[propertyName].toString());
}
return formData;
}
}
Using:
let formData = Utility.convertModelToFormData(model);
php\php.ini
set your loadable php extensions path (eg. extension_dir = "C:\php\ext"
)
(https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)php\php.ini
) check if extension=php_mysqli.dll
is uncommented
(https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)"C:\php"
) and php\ext folder (eg."C:\php\ext"
) as your runtime environment variable path
(https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)You need to set the multipart.maxFileSize
and multipart.maxRequestSize
parameters to higher values than the default. This can be done in your spring boot configuration yml files. For example, adding the following to application.yml
will allow users to upload 10Mb files:
multipart:
maxFileSize: 10Mb
maxRequestSize: 10Mb
If the user needs to be able to upload multiple files in a single request and they may total more than 10Mb, then you will need to configure multipart.maxRequestSize
to a higher value:
multipart:
maxFileSize: 10Mb
maxRequestSize: 100Mb
I am also the same problem. I think the reason are,
1) When my activecell is within the table, "ActiveSheet.ShowAllData" can be work. 2) When my activecell not within the table, "ActiveSheet.ShowAllData" cannot work.Using this code, ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=1 can clear the filter.
to modify more css property values, you may use css object. such as:
hilight_css = {"border-bottom-color":"red",
"background-color":"#000"};
$(".msg").css(hilight_css);
but if the modification code is bloated. you should consider the approach March suggested. do it this way:
first, in your css file:
.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }
second, in your js code:
$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");
if ie 6 is not an issue, you can chain these classes to have more specific selectors.
If you install Node using the windows installer, there is nothing you have to do. It adds path to node and npm.
You can also use Windows setx command for changing system environment variables. No reboot is required. Just logout/login. Or just open a new cmd window, if you want to see the changing there.
setx PATH "%PATH%;C:\Program Files\nodejs"
Try These
Call Functions With Dynamic Names, like this:
let dynamic_func_name = 'alert';
(new Function(dynamic_func_name+'()'))()
with parameters:
let dynamic_func_name = 'alert';
let para_1 = 'HAHAHA';
let para_2 = 'ABCD';
(new Function(`${dynamic_func_name}('${para_1}','${para_2}')`))()
Run Dynamic Code:
let some_code = "alert('hahaha');";
(new Function(some_code))()
Use the optional font
argument to turtle.write()
, from the docs:
turtle.write(
arg, move=False, align="left", font=("Arial", 8, "normal"))
Parameters:
- arg – object to be written to the TurtleScreen
- move – True/False
- align – one of the strings “left”, “center” or right”
- font – a triple (fontname, fontsize, fonttype)
So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal"))
to change the font size to 16 (default is 8).
As of rev 17 of the Android Developer Tools, the correct way to add a library jar when.using the tools and Eclipse is to create a directory called libs
on the same level as your src
and assets
directories and then drop the jar in there. Nothing else.required, the tools take care of all the rest for you automatically.
See http://msdn.microsoft.com/en-us/library/ms187928.aspx
You can concatenate it:
SELECT CONVERT(VARCHAR(10), GETDATE(), 104) + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)
To check input type
<!DOCTYPE html>
<html>
<body>
<input type=number id="txtinp">
<button onclick=checktype()>Try it</button>
<script>
function checktype()
{
alert(document.getElementById("txtinp").type);
}
</script>
</body>
</html>
Had a similar problem. My issue was that I had several projects within the same solution that each were referencing a specific version of a DLL but different versions. The solution was to set 'Specific Version' to false in the all of the properties of all of the references.
Just spotted this thread while searching for this very answer. I just made a small jQuery function, hope this helps, works like a charm:
JAVASCRIPT
var maxHeight = 0;
$('.inner').each(function() {
maxHeight = Math.max(maxHeight, $(this).height());
});
$('.lhs_content .inner, .rhs_content .inner').css({height:maxHeight + 'px'});
HTML
<div class="lhs_content">
<div class="inner">
Content in here
</div>
</div>
<div class="rhs_content">
<div class="inner">
More content in here
</div>
</div>
git filter-branch
is the major-surgery tool.
git filter-branch --parent-filter true -- @^!
--parent-filter
gets the parents on stdin and should print the rewritten parents on stdout; unix true
exits successfully and prints nothing, so: no parents. @^!
is Git shorthand for "the head commit but not any of its parents". Then delete all the other refs and push at leisure.
You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:
public class Item
{
public string name { get; set; }
public string index { get; set; }
public string optional { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
Usage:
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item>
{
new Item { name = "test1", index = "index1" },
new Item { name = "test2", index = "index2" }
};
And in the result you won't have to change things several times if you need to change data-structure.
p.s. Here's very nice tool for complex json
s
You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.
You just need to re-open the image with IrfanView after changing the view color to white.
To change the viewing color in Irfanview go to:
Options > Properties/Settings > Viewing > Main window color
select regexp_replace('This is a test ' || chr(9) || ' foo ', '[[:space:]]', '') from dual;
REGEXP_REPLACE
--------------
Thisisatestfoo
Remove "track by index" from the ng-repeat and it would refresh the DOM
You should look at using the System.Data.SqlClient.SqlBulkCopy
for this. Here's the documentation, and of course there are plenty of tutorials online.
Sorry, I know you were looking for a simple answer to get EF to do what you want, but bulk operations are not really what ORMs are meant for.
Unless you need to access more memory that 32b addressing will allow you, the benefits will be small, if any.
When running on 64b CPU, you get the same memory interface no matter if you are running 32b or 64b code (you are using the same cache and same BUS).
While x64 architecture has a few more registers which allows easier optimizations, this is often counteracted by the fact pointers are now larger and using any structures with pointers results in a higher memory traffic. I would estimate the increase in the overall memory usage for a 64b application compared to a 32b one to be around 15-30 %.
Try the maven-exec-plugin. From there:
mvn exec:java -Dexec.mainClass="com.example.Main"
This will run your class in the JVM. You can use -Dexec.args="arg0 arg1"
to pass arguments.
If you're on Windows, apply quotes for
exec.mainClass
andexec.args
:mvn exec:java -D"exec.mainClass"="com.example.Main"
If you're doing this regularly, you can add the parameters into the pom.xml as well:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.example.Main</mainClass>
<arguments>
<argument>foo</argument>
<argument>bar</argument>
</arguments>
</configuration>
</plugin>
What worked for me was adding:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
finish();
}
to TheRelevantActivity.java
and now it is working as expected
and yeah don't forget to add:
getSupportActionbar.setDisplayHomeAsUpEnabled(true);
in onCreate()
method
Quoting this link: http://steveswanson.wordpress.com/2009/04/21/exporting-and-importing-an-individual-mysql-table/
To export the table run the following command from the command line:
mysqldump -p --user=username dbname tableName > tableName.sql
This will export the tableName to the file tableName.sql.
To import the table run the following command from the command line:
mysql -u username -p -D dbname < tableName.sql
The path to the tableName.sql needs to be prepended with the absolute path to that file. At this point the table will be imported into the DB.
You've not shown how you're creating the string 2016-01-12T23:00:00.000Z
, but I assume via .format()
.
Anyway, .set()
is using your local time zone, but the Z
in the time string indicates zero time, otherwise known as UTC.
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
So I assume your local timezone is 23 hours from UTC?
saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format()
call that outputs using your local timezone, rather than UTC.
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/
Using pgrep to get pid's of matching command lines:
top -c -p $(pgrep -d',' -f string_to_match_in_cmd_line)
top -p
expects a comma separated list of pids so we use -d','
in pgrep. The -f
flag in pgrep makes it match the command line instead of program name.
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
We can do the same thing in such a way.
const Child = () => {
return (
write your whole HTML here.
)
}
now you want to send this HTML inside another component which name is Parent component.
Calling :-
<Parent child={<child/>} >
</Parent>
Use Of Child:-
const Parent = (props) => {
const { child } = props;
return (
{child}
)
}
this work perfect for me.
Windows-vm "C:\Program Files\Java\jdk1.6.0_07\jre\bin\javaw.exe"
from IPython.display import HTML
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')
using System.Linq;
list.Where(x=> x.Name == nameToExtract);
Edit: misread question (now all matches)
There is a --summarize
switch which includes bucket summary information (i.e. number of objects, total size).
Here's the correct answer using AWS cli:
aws s3 ls s3://bucketName/path/ --recursive --summarize | grep "Total Objects:"
Total Objects: 194273
See the documentation
On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:
First give all of the rows children a border on the right and bottom
.borders div{
border-right:1px solid #999;
border-bottom:1px solid #999;
}
Next give the first child of each or a left border
.borders div:first-child{
border-left:
1px solid #999;
}
Last make sure to clear the borders for their child elements
.borders div > div{
border:0;
}
HTML:
<div class="row borders">
<div class="col-xs-5 col-md-2">Email</div>
<div class="col-xs-7 col-md-4">[email protected]</div>
<div class="col-xs-5 col-md-2">Phone</div>
<div class="col-xs-7 col-md-4">555-123-4567</div>
</div>
I've wrote such a simple class:
public static class WatermarkExtension
{
public static MvcHtmlString WatermarkFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var watermark = ModelMetadata.FromLambdaExpression(expression, html.ViewData).Watermark;
var htmlEncoded = HttpUtility.HtmlEncode(watermark);
return new MvcHtmlString(htmlEncoded);
}
}
The usage as such:
@Html.TextBoxFor(model => model.AddressSuffix, new {placeholder = Html.WatermarkFor(model => model.AddressSuffix)})
And property in a viewmodel:
[Display(ResourceType = typeof (Resources), Name = "AddressSuffixLabel", Prompt = "AddressSuffixPlaceholder")]
public string AddressSuffix
{
get { return _album.AddressSuffix; }
set { _album.AddressSuffix = value; }
}
Notice Prompt parameter. In this case I use strings from resources for localization but you can use just strings, just avoid ResourceType parameter.
In my experience copy-paste from eclipse and Notepad++ works directly with word.
For some reason I had a problem with a file that didn't preserve coloring. I made a new .java file, copy-paste code to that, then copy-paste to word and it worked...
As the other guys said, create a new paragraph style. What I do is use mono-spaced font like courier new, small size close to 8px for fonts, single spaced with no space between paragraphs, make tab stops small (0.5cm,1cm,..,5cm), put a simple line border around the text and disable grammar checks. That way i achieved the line braking of eclipse so I don't have to do anything more.
Hope I helped ;)
Style is an attribute so css
won't work for it.U can use attr
Change:
$('.handle').css({'style':'left: 300px'});
T0:
$('.handle').attr('style','left: 300px');//Use `,` Comma instead of `:` colon
Not my code, but I think it's pretty nicely written. It allows to check by the key as well as by the Object element itself and handles both the On Error method and iterating through all Collection elements.
https://danwagner.co/how-to-check-if-a-collection-contains-an-object/
I'll not copy the full explanation since it is available on the linked page. Solution itself copied in case the page eventually becomes unavailable in the future.
The doubt I have about the code is the overusage of GoTo in the first If block but that's easy to fix for anyone so I'm leaving the original code as it is.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'INPUT : Kollection, the collection we would like to examine
' : (Optional) Key, the Key we want to find in the collection
' : (Optional) Item, the Item we want to find in the collection
'OUTPUT : True if Key or Item is found, False if not
'SPECIAL CASE: If both Key and Item are missing, return False
Option Explicit
Public Function CollectionContains(Kollection As Collection, Optional Key As Variant, Optional Item As Variant) As Boolean
Dim strKey As String
Dim var As Variant
'First, investigate assuming a Key was provided
If Not IsMissing(Key) Then
strKey = CStr(Key)
'Handling errors is the strategy here
On Error Resume Next
CollectionContains = True
var = Kollection(strKey) '<~ this is where our (potential) error will occur
If Err.Number = 91 Then GoTo CheckForObject
If Err.Number = 5 Then GoTo NotFound
On Error GoTo 0
Exit Function
CheckForObject:
If IsObject(Kollection(strKey)) Then
CollectionContains = True
On Error GoTo 0
Exit Function
End If
NotFound:
CollectionContains = False
On Error GoTo 0
Exit Function
'If the Item was provided but the Key was not, then...
ElseIf Not IsMissing(Item) Then
CollectionContains = False '<~ assume that we will not find the item
'We have to loop through the collection and check each item against the passed-in Item
For Each var In Kollection
If var = Item Then
CollectionContains = True
Exit Function
End If
Next var
'Otherwise, no Key OR Item was provided, so we default to False
Else
CollectionContains = False
End If
End Function
Try this:
1- From Xcode menu open: Product > Scheme > Edit Scheme
2- On your Environment Variables set OS_ACTIVITY_MODE
= disable
Try removing the uses-sdk
part form AndroidManifest.xml
file. it worked for me!
Don't use the Android Virtual Device with too low configuration. Let it be medium.
display: block;
for the table
position: sticky; top: 0;
for the header row<table style="display: block; height: 100px; overflow: auto;">
<thead>
<tr>
<td style="position: sticky; top: 0;">Header stays put</td>
<td style="position: sticky; top: 0;">Layout aligned</td>
</tr>
</thead>
<tbody>
<tr>
<td>foo1</td>
<td>Header stays put</td>
</tr>
<tr>
<td>foo2</td>
<td>Header stays put</td>
</tr>
</tbody>
</table>
https://jsfiddle.net/0zxk18fp/
Tested on Chrome, Firefox, Safari, Edge
In my case I was modifying the request to append a header (using Fiddler) to an https
request, but I did not configure it to decrypt https traffic. You can export a manually-created certificate from Fiddler, so you can trust/import the certificate by your browsers. See above link for details, some steps include:
This generates a random float between two floats.
float RandomFloat(float min, float max){
return ((max - min) * ((float)rand() / RAND_MAX)) + min;
}
length of an array(type int) with sizeof: sizeof(array)/sizeof(int)
In addition to the pure javascript answers above, You can use jQuery text method as following:
$('#myspan').text('newtext');
If you need to extend the answer to get/change html content of a span or div elements, you can do this:
$('#mydiv').html('<strong>new text</strong>');
References:
.text(): http://api.jquery.com/text/
.html(): http://api.jquery.com/html/
I encountered this error message when trying to insert String into an XMLTYPE column.
Specifically using Java's PreparedStatement like this:
ps.setString('XML', document);
where XML
here is defined as XMLTYPE.
I know this is old but you could create a custom extension if you needed to create that form over and over:
public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)
{
return htmlHelper.BeginForm(null, null, FormMethod.Post,
new Dictionary<string, object>() { { "enctype", "multipart/form-data" } });
}
Usage then just becomes
<% using(Html.BeginMultipartForm()) { %>
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
The problem with your code is in the line:
for(i in length(namevector))
You need to ask yourself: what is length(namevector)
? It's one number. So essentially you're saying:
for(i in 11)
df[,i] <- NA
Or more simply:
df[,11] <- NA
That's why you're getting an error. What you want is:
for(i in namevector)
df[,i] <- NA
Or more simply:
df[,namevector] <- NA
If your compiler supports (at least part of) C++11 you could do something like:
for (auto& t : myMap)
std::cout << t.first << " "
<< t.second.first << " "
<< t.second.second << "\n";
For C++03 I'd use std::copy
with an insertion operator instead:
typedef std::pair<string, std::pair<string, string> > T;
std::ostream &operator<<(std::ostream &os, T const &t) {
return os << t.first << " " << t.second.first << " " << t.second.second;
}
// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));
As I said in the comments, a <div>
element does not have a value
attribute. Although (very) bad, it can be accessed as:
console.log(document.getElementById('demo').getAttribute);
I suggest using HTML5 data-*
attributes rather. Something like this:
<div id="demo" data-myValue="1">...</div>
in which case you could access it using:
element.getAttribute('data-myValue');
//Or using jQuery:
$('#demo').data('myValue');
Go to mysql edit table
-> change column type to varchar(45)
.
fcntl()
has always worked reliably for me. In any case, here is the function I use to enable/disable blocking on a socket:
#include <fcntl.h>
/** Returns true on success, or false if there was an error */
bool SetSocketBlockingEnabled(int fd, bool blocking)
{
if (fd < 0) return false;
#ifdef _WIN32
unsigned long mode = blocking ? 0 : 1;
return (ioctlsocket(fd, FIONBIO, &mode) == 0) ? true : false;
#else
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) return false;
flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
return (fcntl(fd, F_SETFL, flags) == 0) ? true : false;
#endif
}
According to the official default HTML stylesheet, there is no defined default link color. However, you can find out the default your browser uses by either taking a screenshot and using the pipette tool in any decent graphic editor or using the developer tools of your browser (select an a
element, look for computed values>color
).
In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go
EDIT:
That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.
Simple and neat with fontawesome
input[type=radio] {
-moz-appearance: none;
-webkit-appearance: none;
-o-appearance: none;
outline: none;
content: none;
margin-left: 5px;
}
input[type=radio]:before {
font-family: "FontAwesome";
content: "\f00c";
font-size: 25px;
color: transparent !important;
background: #fff;
width: 25px;
height: 25px;
border: 2px solid black;
margin-right: 5px;
}
input[type=radio]:checked:before {
color: black !important;
}
no there is an alternative way to implement goto statement
class id:
def data1(self):
name=[]
age=[]
n=1
while n>0:
print("1. for enter data")
print("2. update list")
print("3. show data")
print("choose what you want to do ?")
ch=int(input("enter your choice"))
if ch==1:
n=int(input("how many elemet you want to enter="))
for i in range(n):
name.append(input("NAME "))
age.append(int(input("age ")))
elif ch==2:
name.append(input("NAME "))
age.append(int(input("age ")))
elif ch==3:
try:
if name==None:
print("empty list")
else:
print("name \t age")
for i in range(n):
print(name[i]," \t ",age[i])
break
except:
print("list is empty")
print("do want to continue y or n")
ch1=input()
if ch1=="y":
n=n+1
else:
print("name \t age")
for i in range(n):
print(name[i]," \t ",age[i])
n=-1
p1=id()
p1.data1()
format = function date2str(x, y) {
var z = {
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
});
return y.replace(/(y+)/g, function(v) {
return x.getFullYear().toString().slice(-v.length)
});
}
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
Either modify the pattern beforehand so that it only matches the entire string:
var r = /^a$/
or check afterward whether the pattern matched the whole string:
function matchExact(r, str) {
var match = str.match(r);
return match && str === match[0];
}
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
Unless the OP is using PowerShell Community Extensions which does provide a Start-Process cmdlet along with a bunch of others. If this the case then Glennular's solution works a treat since it matches the positional parameters of pscx\start-process : -path (position 1) -arguments (positon 2).
Tested on 4.2.7 release
package com.national.software.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import com.national.software.dto.UserDetails;
public class HibernateTest {
static SessionFactory sessionFactory;
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("user1");
Configuration config = new Configuration();
config.configure();
ServiceRegistry serviceRegistry = (ServiceRegistry) new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
sessionFactory = config.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
I know the topic is old, but you can declare the Ajax as a variable, then use a function to call the variable on the desired content. Keep in mind you are calling what you have in the Ajax if you want a different elements from the Ajax you need to specify it.
Example:
Var infogen = $.ajax({'your query')};
$("#refresh").click(function(){
infogen;
console.log("to verify");
});
Hope helps
if not try:
$("#refresh").click(function(){
loca.tion.reload();
console.log("to verify");
});
C++20 will add constexpr
strings and vectors
The following proposal has been accepted apparently: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0980r0.pdf and it adds constructors such as:
// 20.3.2.2, construct/copy/destroy
constexpr
basic_string() noexcept(noexcept(Allocator())) : basic_string(Allocator()) { }
constexpr
explicit basic_string(const Allocator& a) noexcept;
constexpr
basic_string(const basic_string& str);
constexpr
basic_string(basic_string&& str) noexcept;
in addition to constexpr versions of all / most methods.
There is no support as of GCC 9.1.0, the following fails to compile:
#include <string>
int main() {
constexpr std::string s("abc");
}
with:
g++-9 -std=c++2a main.cpp
with error:
error: the type ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’} of ‘constexpr’ variable ‘s’ is not literal
std::vector
discussed at: Cannot create constexpr std::vector
Tested in Ubuntu 19.04.
I feel like you're trying to solve the wrong problem here. Shouldn't you be trying to make the ssh daemons more stable? Try running something like monit, which will check to see if the daemon is running and restart it if it isn't (giving you time to find the root problem behind sshd shutting down on you). Or is the network service troublesome? Try looking at man ifup
. Does the Whole Damn Thing just like to shut down on you? Well, that's a bigger problem ... try looking at your logs (start with syslog) to find hardware failures or services that are shutting your boxen down (maybe a temperature monitor?).
Making your scripts fault tolerant is great, but you might also want to make your boxen fault tolerant.
Checkout the pre-release notes about Swift and Objective C in the same project
You should be importing
#import "SCLAlertView-Swift.h"
alert('Alert For your User!') ? "" : location.reload();
You can write above code in this format also.It seems quite decent
Here is a way to call controller's function from outside of it:
angular.element(document.getElementById('yourControllerElementID')).scope().get();
where get()
is a function from your controller.
You can switch
document.getElementById('yourControllerElementID')`
to
$('#yourControllerElementID')
If you are using jQuery.
Also, if your function means changing anything on your View, you should call
angular.element(document.getElementById('yourControllerElementID')).scope().$apply();
to apply the changes.
One more thing, you should note is that scopes are initialized after the page is loaded, so calling methods from outside of scope should always be done after the page is loaded. Else you will not get to the scope at all.
UPDATE:
With the latest versions of angular, you should use
angular.element(document.getElementById('yourControllerElementID')).injector().??get('$rootScope')
And yes, this is, in fact, a bad practice, but sometimes you just need things done quick and dirty.
In order to better understand []
and new Array()
:
> []
[]
> new Array()
[]
> [] == []
false
> [] === []
false
> new Array() == new Array()
false
> new Array() === new Array()
false
> typeof ([])
"object"
> typeof (new Array())
"object"
> [] === new Array()
false
> [] == new Array()
false
The above result is from Google Chrome console on Windows 7.
I just had the exact same error, and solved it by restarting xcode.
For me the issue occurred after an svn update, the file in question was added to the projects folder, but it never appeared in xcode(9.3.1) – until I restarted it.
I want to clear here that preg_split();
is far away from it but explode();
can be used in similar way as split();
following is the comparison between split();
and explode();
usage
<?php
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo $month; // foo
echo $day; // *
echo $year;
?>
URL: http://php.net/manual/en/function.split.php
<?php
$data = "04/30/1973";
list($month, $day, $year) = explode("/", $data);
echo $month; // foo
echo $day; // *
echo $year;
?>
URL: http://php.net/manual/en/function.explode.php
Here is how we can use it :)
Try line-height
property; there are many ways to assign line height
Converting Using OpenSSL
These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software.
Convert a DER file (.crt .cer .der) to PEM
openssl x509 -inform der -in certificate.cer -out certificate.pem
Convert a PEM file to DER
openssl x509 -outform der -in certificate.pem -out certificate.der
Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM
openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes
You can add -nocerts to only output the private key or add -nokeys to only output the certificates.
Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
Convert PEM to CRT (.CRT file)
openssl x509 -outform der -in certificate.pem -out certificate.crt
OpenSSL Convert PEM
Convert PEM to DER
openssl x509 -outform der -in certificate.pem -out certificate.der
Convert PEM to P7B
openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b -certfile CACert.cer
Convert PEM to PFX
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
OpenSSL Convert DER
Convert DER to PEM
openssl x509 -inform der -in certificate.cer -out certificate.pem
OpenSSL Convert P7B
Convert P7B to PEM
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
Convert P7B to PFX
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer
OpenSSL Convert PFX
Convert PFX to PEM
openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes
Generate rsa keys by OpenSSL
Using OpenSSL on the command line you’d first need to generate a public and private key, you should password protect this file using the -passout argument, there are many different forms that this argument can take so consult the OpenSSL documentation about that.
openssl genrsa -out private.pem 1024
This creates a key file called private.pem that uses 1024 bits. This file actually have both the private and public keys, so you should extract the public one from this file:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
or
openssl rsa -in private.pem -pubout > public.pem
or
openssl rsa -in private.pem -pubout -out public.pem
You’ll now have public.pem containing just your public key, you can freely share this with 3rd parties. You can test it all by just encrypting something yourself using your public key and then decrypting using your private key, first we need a bit of data to encrypt:
Example file :
echo 'too many secrets' > file.txt
You now have some data in file.txt, lets encrypt it using OpenSSL and the public key:
openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl
This creates an encrypted version of file.txt calling it file.ssl, if you look at this file it’s just binary junk, nothing very useful to anyone. Now you can unencrypt it using the private key:
openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt
You will now have an unencrypted file in decrypted.txt:
cat decrypted.txt
|output -> too many secrets
RSA TOOLS Options in OpenSSL
NAME
rsa - RSA key processing tool
SYNOPSIS
openssl rsa [-help] [-inform PEM|NET|DER] [-outform PEM|NET|DER] [-in filename] [-passin arg] [-out filename] [-passout arg] [-aes128] [-aes192] [-aes256] [-camellia128] [-camellia192] [-camellia256] [-des] [-des3] [-idea] [-text] [-noout] [-modulus] [-check] [-pubin] [-pubout] [-RSAPublicKey_in] [-RSAPublicKey_out] [-engine id]
DESCRIPTION
The rsa command processes RSA keys. They can be converted between various forms and their components printed out. Note this command uses the traditional SSLeay compatible format for private key encryption: newer applications should use the more secure PKCS#8 format using the pkcs8 utility.
COMMAND OPTIONS
-help
Print out a usage message.
-inform DER|NET|PEM
This specifies the input format. The DER option uses an ASN1 DER encoded form compatible with the PKCS#1 RSAPrivateKey or SubjectPublicKeyInfo format. The PEM form is the default format: it consists of the DER format base64 encoded with additional header and footer lines. On input PKCS#8 format private keys are also accepted. The NET form is a format is described in the NOTES section.
-outform DER|NET|PEM
This specifies the output format, the options have the same meaning as the -inform option.
-in filename
This specifies the input filename to read a key from or standard input if this option is not specified. If the key is encrypted a pass phrase will be prompted for.
-passin arg
the input file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.
-out filename
This specifies the output filename to write a key to or standard output if this option is not specified. If any encryption options are set then a pass phrase will be prompted for. The output filename should not be the same as the input filename.
-passout password
the output file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.
-aes128|-aes192|-aes256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea
These options encrypt the private key with the specified cipher before outputting it. A pass phrase is prompted for. If none of these options is specified the key is written in plain text. This means that using the rsa utility to read in an encrypted key with no encryption option can be used to remove the pass phrase from a key, or by setting the encryption options it can be use to add or change the pass phrase. These options can only be used with PEM format output files.
-text
prints out the various public or private key components in plain text in addition to the encoded version.
-noout
this option prevents output of the encoded version of the key.
-modulus
this option prints out the value of the modulus of the key.
-check
this option checks the consistency of an RSA private key.
-pubin
by default a private key is read from the input file: with this option a public key is read instead.
-pubout
by default a private key is output: with this option a public key will be output instead. This option is automatically set if the input is a public key.
-RSAPublicKey_in, -RSAPublicKey_out
like -pubin and -pubout except RSAPublicKey format is used instead.
-engine id
specifying an engine (by its unique id string) will cause rsa to attempt to obtain a functional reference to the specified engine, thus initialising it if needed. The engine will then be set as the default for all available algorithms.
NOTES
The PEM private key format uses the header and footer lines:
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
The PEM public key format uses the header and footer lines:
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
The PEM RSAPublicKey format uses the header and footer lines:
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
The NET form is a format compatible with older Netscape servers and Microsoft IIS .key files, this uses unsalted RC4 for its encryption. It is not very secure and so should only be used when necessary.
Some newer version of IIS have additional data in the exported .key files. To use these with the utility, view the file with a binary editor and look for the string "private-key", then trace back to the byte sequence 0x30, 0x82 (this is an ASN1 SEQUENCE). Copy all the data from this point onwards to another file and use that as the input to the rsa utility with the -inform NET option.
EXAMPLES
To remove the pass phrase on an RSA private key:
openssl rsa -in key.pem -out keyout.pem
To encrypt a private key using triple DES:
openssl rsa -in key.pem -des3 -out keyout.pem
To convert a private key from PEM to DER format:
openssl rsa -in key.pem -outform DER -out keyout.der
To print out the components of a private key to standard output:
openssl rsa -in key.pem -text -noout
To just output the public part of a private key:
openssl rsa -in key.pem -pubout -out pubkey.pem
Output the public part of a private key in RSAPublicKey format:
openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
get sock opt may be somewhat useful, however, another way would to have a signal handler installed for SIGPIPE. Basically whenever you the socket connection breaks, the kernel will send a SIGPIPE signal to the process and then you can do the needful. But this still does not provide the solution for knowing the status of the connection. hope this helps.
One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)
Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)
In a One-To-Many relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child. In a Many-To-Many, the existence of either type is dependent on something outside the both of them (in the larger application context).
Your subject matter (domain) should dictate whether or not the relationship is One-To-Many or Many-To-Many -- however, I find that making the relationship unidirectional or bidirectional is an engineering decision that trades off memory, processing, performance, etc.
What can be confusing is that a Many-To-Many Bidirectional relationship does not need to be symmetric! That is, a bunch of People could point to a skill, but the skill need not relate back to just those people. Typically it would, but such symmetry is not a requirement. Take love, for example -- it is bi-directional ("I-Love", "Loves-Me"), but often asymmetric ("I love her, but she doesn't love me")!
All of these are well supported by Hibernate and JPA. Just remember that Hibernate or any other ORM doesn't give a hoot about maintaining symmetry when managing bi-directional many-to-many relationships...thats all up to the application.
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
It's better to use JSON.parse(yourUnescapedJson);
One additional tweak worth mentioning: I'm not sure if this is a .NET 4.0 or Visual Studio 2010 feature, but if you're using both you don't need to declare the value parameter for the setter/mutator block of code:
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Private Set
_name = value
End Set
End Property
The question didn't ask which is fastest, but to add to the sed answer, -n '1p' is badly performing as the pattern space is still scanned on large files. Out of curiosity I found that 'head' wins over sed narrowly:
# best:
head -n1 $bigfile >/dev/null
# a bit slower than head (I saw about 10% difference):
sed '1q' $bigfile >/dev/null
# VERY slow:
sed -n '1p' $bigfile >/dev/null
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g>
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(145,200,103);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(132,168,86);stop-opacity:1" />
</linearGradient>
</defs>
<rect width="220" height="30" class="GradientBorder" fill="url(#grad1)" />
<text x="60" y="20" font-family="Calibri" font-size="20" fill="white" >My Code , Your Achivement....... </text>
</g>
</svg>
This is my solution, feedback is welcome.. :)
$('input').keydown( function (event) { //event==Keyevent
if(event.which == 13) {
var inputs = $(this).closest('form').find(':input:visible');
inputs.eq( inputs.index(this)+ 1 ).focus();
event.preventDefault(); //Disable standard Enterkey action
}
// event.preventDefault(); <- Disable all keys action
});
To avoid deprecated code and warnings you can use:
view.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
} else {
view.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
yourFunctionHere();
}
});
I can give an example commonly seen in project.
Here, option --no-ff
(i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff
(i.e. fast-forward merge) is by default.
$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature' // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk // => see details with graph
$ git checkout -b anotherFeature // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk // => see details with graph
(*) Note that here if the newFeature
branch is re-used, instead of creating a new branch, git will have to do a --no-ff
merge anyway. This means fast forward merge is not always eligible.
Incidentally, if your span
class is even-numbered (e.g. span8
) you can add an offset
class to center it – for span8
that would be offset2
(assuming the default 12-column grid), for span6
it would be offset3
and so on (basically, half the number of remaining columns if you subtract the span
-number from the total number of columns in the grid).
UPDATE
Bootstrap 3 renamed a lot of classes so all the span*
classes should be col-md-*
and the offset
classes should be col-md-offset-*
, assuming you're using the medium-sized responsive grid.
I created a quick demo here, hope it helps: http://codepen.io/anon/pen/BEyHd.
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
You can to use Count Lines of Code (CLOC)
On Settings
-> External Tools
add a new tool
Simply compare the width of the documents root element (i.e. html element) against the inner portion of the window:
if ((window.innerWidth - document.documentElement.clientWidth) >0) console.log('V-scrollbar active')
If you also need to know the scrollbar width:
vScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
Should work:
In [1]: price = 1*9
In [2]: price
Out[2]: 9
The problem is that your code is creating a blank UIViewController, not a SecondViewController. You need to create an instance of your subclass, not a UIViewController,
func transition(Sender: UIButton!) {
let secondViewController:SecondViewController = SecondViewController()
self.presentViewController(secondViewController, animated: true, completion: nil)
}
If you've overridden init(nibName nibName: String!,bundle nibBundle: NSBundle!) in your SecondViewController class, then you need to change the code to,
let sec: SecondViewController = SecondViewController(nibName: nil, bundle: nil)
My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.
<div ng-repeat="f in foos">
<div>
<div ng-repeat="b in foos.bars">
<a ng-click="addSomething($parent.$index)">Add Something</a>
</div>
</div>
</div>
Using using
is a pretty good way:
using (MyForm foo = new MyForm())
{
if (foo.ShowDialog() == DialogResult.OK)
{
// your code
}
}
I had similar problems. The one downside is that with cin.ignore()
, you have to press enter 1 more time, which messes with the program.
Minor note: Please consider that when you import from a default export, the naming is completely independent. This actually has an impact on refactorings.
Let's say you have a class Foo
like this with a corresponding import:
export default class Foo { }
// The name 'Foo' could be anything, since it's just an
// Identifier for the default export
import Foo from './Foo'
Now if you refactor your Foo
class to be Bar
and also rename the file, most IDEs will NOT touch your import. So you will end up with this:
export default class Bar { }
// The name 'Foo' could be anything, since it's just an
// Identifier for the default export.
import Foo from './Bar'
Especially in TypeScript, I really appreciate named exports and the more reliable refactoring. The difference is just the lack of the default
keyword and the curly braces. This btw also prevents you from making a typo in your import since you have type checking now.
export class Foo { }
//'Foo' needs to be the class name. The import will be refactored
//in case of a rename!
import { Foo } from './Foo'
You can always add this in any cell:
import pdb; pdb.set_trace()
and the debugger will stop on that line. For example:
In[1]: def fun1(a):
def fun2(a):
import pdb; pdb.set_trace() # debugging starts here
return fun2(a)
In[2]: fun1(1)
You shouldn't use the third one because its wrong. "String" takes 7 bytes, not 5.
The first one is a pointer (can be reassigned to a different address), the other two are declared as arrays, and cannot be reassigned to different memory locations (but their content may change, use const
to avoid that).
Eclipse > Help > Eclipse Marketplace...
Search for m2e
Install Maven Integration for Eclipse (Juno and newer)
. [It works for Indigo also]
Current for 2016 link is https://msdn.microsoft.com/en-us/library/mt204009.aspx
SQL Server Data Tools in Visual Studio 2015 is a modern development tool that you can download for free to build SQL Server relational databases, Azure SQL databases, Integration Services packages, Analysis Services data models, and Reporting Services reports. With SSDT, you can design and deploy any SQL Server content type with the same ease as you would develop an application in Visual Studio. This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016.
Note that you don't need to have Visual Studio pre-installed. SSDT will install required components of VS, if it is not installed on your machine.
This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016
Previously included in SQL Server standalone Business Intelligence Studio is not available any more and in last years replaced by SQL Server Data Tools (SSDT) for Visual Studio. See answer http://sqlmag.com/sql-server-2014/q-where-business-intelligence-development-studio-bids-sql-server-2014
If you are styling calc in a GWT project, its parser might not parse calc for you as it did not for me... the solution is to wrap it in a css literal like this:
height: literal("-moz-calc(100% - (20px + 30px))");
height: literal("-webkit-calc(100% - (20px + 30px))");
height: literal("calc(100% - (20px + 30px))");
How a character is represented is up to the renderer, but the server may also strip out certain characters before sending the document.
You can also have untitled YouTube videos like https://www.youtube.com/watch?v=dmBvw8uPbrA by using the Unicode character ZERO WIDTH NON-JOINER (U+200C), or ‌
in HTML. The code block below should contain that character:
??
You should use this code
this.setVisible(false); //this will close frame i.e. NewJFrame
new NewJFrame().setVisible(true); // Now this will open NewJFrame for you again and will also get refreshed
First, Latin-1 is the same as ISO-8859-1, so, the default was already OK for you. Right?
You successfully set the encoding to ISO-8859-1 with your command line parameter. You also set it programmatically to "Latin-1", but, that's not a recognized value of a file encoding for Java. See http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
When you do that, looks like Charset resets to UTF-8, from looking at the source. That at least explains most of the behavior.
I don't know why OutputStreamWriter shows ISO8859_1. It delegates to closed-source sun.misc.* classes. I'm guessing it isn't quite dealing with encoding via the same mechanism, which is weird.
But of course you should always be specifying what encoding you mean in this code. I'd never rely on the platform default.
I too have had a problem with this. And after quite a while searching for the answer and looking at all the responses by everybody, I think I've come up with a viable solution to this.
It seems that most of the answers that I've come across is using functions to hold the constants. As many of the users of the MANY forums post about, the functions can be easily over written by users on the client side. I was intrigued by Keith Evetts' answer that the constants object can not be accessed by the outside, but only from the functions on the inside.
So I came up with this solution:
Put everything inside an anonymous function so that way, the variables, objects, etc. cannot be changed by the client side. Also hide the 'real' functions by having other functions call the 'real' functions from the inside. I also thought of using functions to check if a function has been changed by a user on the client side. If the functions have been changed, change them back using variables that are 'protected' on the inside and cannot be changed.
/*Tested in: IE 9.0.8; Firefox 14.0.1; Chrome 20.0.1180.60 m; Not Tested in Safari*/
(function(){
/*The two functions _define and _access are from Keith Evetts 2009 License: LGPL (SETCONST and CONST).
They're the same just as he did them, the only things I changed are the variable names and the text
of the error messages.
*/
//object literal to hold the constants
var j = {};
/*Global function _define(String h, mixed m). I named it define to mimic the way PHP 'defines' constants.
The argument 'h' is the name of the const and has to be a string, 'm' is the value of the const and has
to exist. If there is already a property with the same name in the object holder, then we throw an error.
If not, we add the property and set the value to it. This is a 'hidden' function and the user doesn't
see any of your coding call this function. You call the _makeDef() in your code and that function calls
this function. - You can change the error messages to whatever you want them to say.
*/
self._define = function(h,m) {
if (typeof h !== 'string') { throw new Error('I don\'t know what to do.'); }
if (!m) { throw new Error('I don\'t know what to do.'); }
else if ((h in j) ) { throw new Error('We have a problem!'); }
else {
j[h] = m;
return true;
}
};
/*Global function _makeDef(String t, mixed y). I named it makeDef because we 'make the define' with this
function. The argument 't' is the name of the const and doesn't need to be all caps because I set it
to upper case within the function, 'y' is the value of the value of the const and has to exist. I
make different variables to make it harder for a user to figure out whats going on. We then call the
_define function with the two new variables. You call this function in your code to set the constant.
You can change the error message to whatever you want it to say.
*/
self._makeDef = function(t, y) {
if(!y) { throw new Error('I don\'t know what to do.'); return false; }
q = t.toUpperCase();
w = y;
_define(q, w);
};
/*Global function _getDef(String s). I named it getDef because we 'get the define' with this function. The
argument 's' is the name of the const and doesn't need to be all capse because I set it to upper case
within the function. I make a different variable to make it harder for a user to figure out whats going
on. The function returns the _access function call. I pass the new variable and the original string
along to the _access function. I do this because if a user is trying to get the value of something, if
there is an error the argument doesn't get displayed with upper case in the error message. You call this
function in your code to get the constant.
*/
self._getDef = function(s) {
z = s.toUpperCase();
return _access(z, s);
};
/*Global function _access(String g, String f). I named it access because we 'access' the constant through
this function. The argument 'g' is the name of the const and its all upper case, 'f' is also the name
of the const, but its the original string that was passed to the _getDef() function. If there is an
error, the original string, 'f', is displayed. This makes it harder for a user to figure out how the
constants are being stored. If there is a property with the same name in the object holder, we return
the constant value. If not, we check if the 'f' variable exists, if not, set it to the value of 'g' and
throw an error. This is a 'hidden' function and the user doesn't see any of your coding call this
function. You call the _getDef() function in your code and that function calls this function.
You can change the error messages to whatever you want them to say.
*/
self._access = function(g, f) {
if (typeof g !== 'string') { throw new Error('I don\'t know what to do.'); }
if ( g in j ) { return j[g]; }
else { if(!f) { f = g; } throw new Error('I don\'t know what to do. I have no idea what \''+f+'\' is.'); }
};
/*The four variables below are private and cannot be accessed from the outside script except for the
functions inside this anonymous function. These variables are strings of the four above functions and
will be used by the all-dreaded eval() function to set them back to their original if any of them should
be changed by a user trying to hack your code.
*/
var _define_func_string = "function(h,m) {"+" if (typeof h !== 'string') { throw new Error('I don\\'t know what to do.'); }"+" if (!m) { throw new Error('I don\\'t know what to do.'); }"+" else if ((h in j) ) { throw new Error('We have a problem!'); }"+" else {"+" j[h] = m;"+" return true;"+" }"+" }";
var _makeDef_func_string = "function(t, y) {"+" if(!y) { throw new Error('I don\\'t know what to do.'); return false; }"+" q = t.toUpperCase();"+" w = y;"+" _define(q, w);"+" }";
var _getDef_func_string = "function(s) {"+" z = s.toUpperCase();"+" return _access(z, s);"+" }";
var _access_func_string = "function(g, f) {"+" if (typeof g !== 'string') { throw new Error('I don\\'t know what to do.'); }"+" if ( g in j ) { return j[g]; }"+" else { if(!f) { f = g; } throw new Error('I don\\'t know what to do. I have no idea what \\''+f+'\\' is.'); }"+" }";
/*Global function _doFunctionCheck(String u). I named it doFunctionCheck because we're 'checking the functions'
The argument 'u' is the name of any of the four above function names you want to check. This function will
check if a specific line of code is inside a given function. If it is, then we do nothing, if not, then
we use the eval() function to set the function back to its original coding using the function string
variables above. This function will also throw an error depending upon the doError variable being set to true
This is a 'hidden' function and the user doesn't see any of your coding call this function. You call the
doCodeCheck() function and that function calls this function. - You can change the error messages to
whatever you want them to say.
*/
self._doFunctionCheck = function(u) {
var errMsg = 'We have a BIG problem! You\'ve changed my code.';
var doError = true;
d = u;
switch(d.toLowerCase())
{
case "_getdef":
if(_getDef.toString().indexOf("z = s.toUpperCase();") != -1) { /*do nothing*/ }
else { eval("_getDef = "+_getDef_func_string); if(doError === true) { throw new Error(errMsg); } }
break;
case "_makedef":
if(_makeDef.toString().indexOf("q = t.toUpperCase();") != -1) { /*do nothing*/ }
else { eval("_makeDef = "+_makeDef_func_string); if(doError === true) { throw new Error(errMsg); } }
break;
case "_define":
if(_define.toString().indexOf("else if((h in j) ) {") != -1) { /*do nothing*/ }
else { eval("_define = "+_define_func_string); if(doError === true) { throw new Error(errMsg); } }
break;
case "_access":
if(_access.toString().indexOf("else { if(!f) { f = g; }") != -1) { /*do nothing*/ }
else { eval("_access = "+_access_func_string); if(doError === true) { throw new Error(errMsg); } }
break;
default:
if(doError === true) { throw new Error('I don\'t know what to do.'); }
}
};
/*Global function _doCodeCheck(String v). I named it doCodeCheck because we're 'doing a code check'. The argument
'v' is the name of one of the first four functions in this script that you want to check. I make a different
variable to make it harder for a user to figure out whats going on. You call this function in your code to check
if any of the functions has been changed by the user.
*/
self._doCodeCheck = function(v) {
l = v;
_doFunctionCheck(l);
};
}())
It also seems that security is really a problem and there is not way to 'hide' you programming from the client side. A good idea for me is to compress your code so that it is really hard for anyone, including you, the programmer, to read and understand it. There is a site you can go to: http://javascriptcompressor.com/. (This is not my site, don't worry I'm not advertising.) This is a site that will let you compress and obfuscate Javascript code for free.
First, I want to agree with others that the regex or str.translate(...)
based solutions are most performant. For my use case the performance of this function wasn't significant, so I wanted to add ideas that I considered with that criteria.
My main goal was to generalize ideas from some of the other answers into one solution that could work for strings containing more than just regex words (i.e., blacklisting the explicit subset of punctuation characters vs whitelisting word characters).
Note that, in any approach, one might also consider using string.punctuation
in place of a manually defined list.
I was surprised to see no answer so far uses re.sub(...). I find it a simple and natural approach to this problem.
import re
my_str = "Hey, you - what are you doing here!?"
words = re.split(r'\s+', re.sub(r'[,\-!?]', ' ', my_str).strip())
In this solution, I nested the call to re.sub(...)
inside re.split(...)
— but if performance is critical, compiling the regex outside could be beneficial — for my use case, the difference wasn't significant, so I prefer simplicity and readability.
This is a few more lines, but it has the benefit of being expandable without having to check whether you need to escape a certain character in regex.
my_str = "Hey, you - what are you doing here!?"
replacements = (',', '-', '!', '?')
for r in replacements:
my_str = my_str.replace(r, ' ')
words = my_str.split()
It would have been nice to be able to map the str.replace to the string instead, but I don't think it can be done with immutable strings, and while mapping against a list of characters would work, running every replacement against every character sounds excessive. (Edit: See next option for a functional example.)
(In Python 2, reduce
is available in global namespace without importing it from functools.)
import functools
my_str = "Hey, you - what are you doing here!?"
replacements = (',', '-', '!', '?')
my_str = functools.reduce(lambda s, sep: s.replace(sep, ' '), replacements, my_str)
words = my_str.split()
Stacks for threads are often smaller. You can change the default at link time, or change at run time also. For reference, some defaults are:
After half a day of fiddling with this, found out that PDO had a bug where...
--
//This would run as expected:
$pdo->exec("valid-stmt1; valid-stmt2;");
--
//This would error out, as expected:
$pdo->exec("non-sense; valid-stmt1;");
--
//Here is the bug:
$pdo->exec("valid-stmt1; non-sense; valid-stmt3;");
It would execute the "valid-stmt1;"
, stop on "non-sense;"
and never throw an error. Will not run the "valid-stmt3;"
, return true and lie that everything ran good.
I would expect it to error out on the "non-sense;"
but it doesn't.
Here is where I found this info: Invalid PDO query does not return an error
Here is the bug: https://bugs.php.net/bug.php?id=61613
So, I tried doing this with mysqli and haven't really found any solid answer on how it works so I thought I's just leave it here for those who want to use it..
try{
// db connection
$mysqli = new mysqli("host", "user" , "password", "database");
if($mysqli->connect_errno){
throw new Exception("Connection Failed: [".$mysqli->connect_errno. "] : ".$mysqli->connect_error );
exit();
}
// read file.
// This file has multiple sql statements.
$file_sql = file_get_contents("filename.sql");
if($file_sql == "null" || empty($file_sql) || strlen($file_sql) <= 0){
throw new Exception("File is empty. I wont run it..");
}
//run the sql file contents through the mysqli's multi_query function.
// here is where it gets complicated...
// if the first query has errors, here is where you get it.
$sqlFileResult = $mysqli->multi_query($file_sql);
// this returns false only if there are errros on first sql statement, it doesn't care about the rest of the sql statements.
$sqlCount = 1;
if( $sqlFileResult == false ){
throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], [".$mysqli->errno."]: '".$mysqli->error."' }");
}
// so handle the errors on the subsequent statements like this.
// while I have more results. This will start from the second sql statement. The first statement errors are thrown above on the $mysqli->multi_query("SQL"); line
while($mysqli->more_results()){
$sqlCount++;
// load the next result set into mysqli's active buffer. if this fails the $mysqli->error, $mysqli->errno will have appropriate error info.
if($mysqli->next_result() == false){
throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], Error No: [".$mysqli->errno."]: '".$mysqli->error."' }");
}
}
}
catch(Exception $e){
echo $e->getMessage(). " <pre>".$e->getTraceAsString()."</pre>";
}
Here's another one. It looks for the first and last non empty cell and builds are range from those. This also handles cases where your data is not rectangular and does not start in A1. Furthermore it handles merged cells as well, which .Find skips when executed from a macro, used on .Cells on a worksheet.
Function getUsedRange(ByRef sheet As Worksheet) As Range
' finds used range by looking for non empty cells
' works around bug in .Find that skips merged cells
' by starting at with the UsedRange (that may be too big)
' credit to https://contexturesblog.com/archives/2012/03/01/select-actual-used-range-in-excel-sheet/
' for the .Find commands
Dim excelsUsedRange As Range
Dim lastRow As Long
Dim lastCol As Long
Dim lastCell As Range
Dim firstRow As Long
Dim firstCol As Long
Dim firstCell As Range
Set excelsUsedRange = ActiveSheet.UsedRange
lastRow = excelsUsedRange.Find(What:="*", _
LookIn:=xlValues, SearchOrder:=xlRows, _
SearchDirection:=xlPrevious).Row
lastCol = excelsUsedRange.Find(What:="*", _
LookIn:=xlValues, SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
Set lastCell = sheet.Cells(lastRow, lastCol)
firstRow = excelsUsedRange.Find(What:="*", After:=lastCell, _
LookIn:=xlValues, SearchOrder:=xlRows, _
SearchDirection:=xlNext).Row
firstCol = excelsUsedRange.Find(What:="*", After:=lastCell, _
LookIn:=xlValues, SearchOrder:=xlByColumns, _
SearchDirection:=xlNext).Row
Set firstCell = sheet.Cells(firstRow, firstCol)
Set getUsedRange = sheet.Range(firstCell, lastCell)
End Function
Check if the url s.source is correct.
Example for me
// fail Project>>t<<est
s.source = { :git => '.../Projecttest-iOS', :tag => s.version.to_s }
// success Project>>T<<est
s.source = { :git => '.../ProjectTest-iOS', :tag => s.version.to_s }
Quick and dirty way:
<View
android:id="@+id/colored_bar"
android:layout_width="48dp"
android:layout_height="3dp"
android:background="@color/bar_red" />
You can use the latest version of the jQuery library by any of the following.
Google Ajax API CDN (also supports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2"></script>
/jquery.min.js
Microsoft CDN (also aupports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
Ajax CDN Announcement, Microsoft Ajax CDN Documentation
jQuery CDN (via Media Temple)
<script type="text/javascript" src=" http://code.jquery.com/jquery-1.7.2.min.js"></script>
** Minified version
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
** Development (Full) version
There are two ways to handle exceptions in pytest
:
pytest.raises
to write assertions about raised exceptions@pytest.mark.xfail
pytest.raises
From the docs:
In order to write assertions about raised exceptions, you can use
pytest.raises
as a context manager
Examples:
Asserting just an exception:
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
with pytest.raises(ZeroDivisionError)
says that whatever is
in the next block of code should raise a ZeroDivisionError
exception. If no exception is raised, the test fails. If the test raises a different exception, it fails.
If you need to have access to the actual exception info:
import pytest
def f():
f()
def test_recursion_depth():
with pytest.raises(RuntimeError) as excinfo:
f()
assert "maximum recursion" in str(excinfo.value)
excinfo
is a ExceptionInfo
instance, which is a wrapper around the actual exception raised. The main attributes of interest are .type
, .value
and .traceback
.
@pytest.mark.xfail
It is also possible to specify a raises
argument to pytest.mark.xfail
.
import pytest
@pytest.mark.xfail(raises=IndexError)
def test_f():
l = [1, 2, 3]
l[10]
@pytest.mark.xfail(raises=IndexError)
says that whatever is
in the next block of code should raise an IndexError
exception. If an IndexError
is raised, test is marked as xfailed (x)
. If no exception is raised, the test is marked as xpassed (X)
. If the test raises a different exception, it fails.
Notes:
Using pytest.raises
is likely to be better for cases where you are testing exceptions your own code is deliberately raising, whereas using @pytest.mark.xfail
with a check function is probably better for something like documenting unfixed bugs or bugs in dependencies.
You can pass a match
keyword parameter to the context-manager (pytest.raises
) to test that a regular expression matches on the string representation of an exception. (see more)
There are at least these two issues I have observed for this problem: 1) It could be either because your sender username or password might not be correct 2) Or it could be as answered by Avinash above, the security condition on the account. Once you try SendMail using SMTP, you normally get a notification in to your account that it may be an unauthorized attempt to access your account, if not user can follow the link to turn the settings to lessSecureApp. Once this is done and smtp SendMail is tried again, it works.
The steps for schedule jobs in Jenkins:
@midnight
Note: under the schedule field, can see the last and the next date-time run.
Jenkins also supports predefined aliases to schedule build:
@hourly
, @daily
, @weekly
, @monthly
, @midnight
@hourly
--> Build every hour at the beginning of the hour --> 0 * * * *
@daily, @midnight
--> Build every day at midnight --> 0 0 * * *
@weekly
--> Build every week at midnight on Sunday morning --> 0 0 * * 0
@monthly
--> Build every month at midnight of the first day of the month --> 0 0 1 * *
You should use cm
or mm
as unit when you specify for printing. Using pixels will cause the browser to translate it to something similar to what it looks like on screen. Using cm
or mm
will ensure consistent size on the paper.
body
{
margin: 25mm 25mm 25mm 25mm;
}
For font sizes, use pt
for the print media.
Note that setting the margin on the body in css style will not adjust the margin in the printer driver that defines the printable area of the printer, or margin controlled by the browser (may be adjustable in print preview on some browsers)... It will just set margin on the document inside the printable area.
You should also be aware that IE7++ automatically adjusts the size to best fit, and causes everything to be wrong even if you use cm
or mm
. To override this behaviour, the user must select 'Print preview' and then set the print size to 100%
(default is Shrink To Fit
).
A better option for full control on printed margins is to use the @page
directive to set the paper margin, which will affect the margin on paper outside the html body element, which is normally controlled by the browser. See http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html.
This currently works in all major browsers except Safari.
In Internet explorer, the margin is actually set to this value in the settings for this printing, and if you do Preview you will get this as default, but the user can change it in the preview.
@page
{
size: auto; /* auto is the initial value */
/* this affects the margin in the printer settings */
margin: 25mm 25mm 25mm 25mm;
}
body
{
/* this affects the margin on the content before sending to printer */
margin: 0px;
}
Related answer: Disabling browser print options (headers, footers, margins) from page?
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
Just remember that it's the eighth Mersenne prime.
If that's too hard, it's also the third of only four known double Mersenne primes.
Edit per comment request:
The Euclid-Euler theorem states that every even perfect number has the form 2^(n - 1) (2^n - 1), where 2^n - 1 is a prime number. The prime numbers of the form 2^n - 1 are known as Mersenne primes, and require n itself to be prime.
We know that the length of an INT32 is of course 32 bits. Given the generally accepted understanding of 2's complement, a signed INT32 is 32 bits - 1 bit.
To find the magnitude of a binary number with a given number of bits we generally raise 2 to the power n, minus 1, where n is equal to the number of bits.
Thus the magnitude calculation is 2^(32 - 1) - 1 = 2^31 - 1. 31 is prime and as outlined above, prime numbers of this form are Mersenne primes. We can prove it is the eight of such simply by counting them. For further details, please ask Euler, or maybe Bernoulli (to whom he wrote about them).
Use setFullyear as others have posted but be aware this returns a timestamp value not a date object. It is also a good candidate imho to add functionality via the prototype. This leads us to the following pattern:
Date.prototype.addYears = function(n) {
var now = new Date();
return new Date(now.setFullYear(now.getFullYear() + n));
};
console.log('Year from now is', new Date().addYears(1));
GRANT SELECT ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password';
This will create a user with SELECT
privilege for all database including Views.
The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.
Character Devices
Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).
TTY
/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty
, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty
, your subsequent input gets duplicated (until you press Ctrl-C).
/dev/tty
doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0
is normally your serial port)
This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :
/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).
Here is the man page: http://linux.die.net/man/4/tty
It is better to parse the URL properly - this way you can handle http://.../file.doc?foo
and http://.../foo.doc/file.exe
correctly.
from urlparse import urlparse
import os
path = urlparse(url_string).path
ext = os.path.splitext(path)[1]
if ext in extensionsToCheck:
print(url_string)
Once you have the packages setup, you'll need to create either an app.config or web.config and add something like the following:
<configuration>
<appSettings>
<add key="key" value="value"/>
</appSettings>
</configuration>
You need to commit or destroy any unsaved changes before you switch branch.
Git won't let you switch branch if it means unsaved changes would be removed.
Best solution that my friend Dhanush Kumar came up with:
def second_max(loop):
glo_max = loop[0]
sec_max = float("-inf")
for i in loop:
if i > glo_max:
sec_max = glo_max
glo_max=i
elif sec_max < i < glo_max:
sec_max = i
return sec_max
#print(second_max([-1,-3,-4,-5,-7]))
assert second_max([-1,-3,-4,-5,-7])==-3
assert second_max([5,3,5,1,2]) == 3
assert second_max([1,2,3,4,5,7]) ==5
assert second_max([-3,1,2,5,-2,3,4]) == 4
assert second_max([-3,-2,5,-1,0]) == 0
assert second_max([0,0,0,1,0]) == 0
I created an open source project called Chutzpah which is a test runner for JavaScript unit tests. Chutzpah enables you to run JavaScript unit tests from the command line and from inside of Visual Studio. It also supports running in the TeamCity continuous integration server.
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
OpenOffice templates + OOo command line interface.
There are tools and libraries available to ease each of those steps.
May be that helps.
You could try the fnmatch module, it's got a shell-like wildcard syntax
or can use regular expressions
import re
As mentioned, the C compiler will add padding for alignment requirements. These requirements often have to do with the memory subsystem. Some types of computers can only access memory lined up to some 'nice' value, like 4 bytes. This is often the same as the word length. Thus, the C compiler may align fields in your structure to this value to make them easier to access (e.g., 4 byte values should be 4 byte aligned) Further, it may pad the bottom of the structure to line up data which follows the structure. I believe there are other reasons as well. More info can be found at this wikipedia page.
I did it this way. it's easy :)
Date d1 = jDateChooserFrom.getDate();
Date d2 = jDateChooserTo.getDate();
Calendar day1 = Calendar.getInstance();
day1.setTime(d1);
Calendar day2 = Calendar.getInstance();
day2.setTime(d2);
int from = day1.get(Calendar.DAY_OF_YEAR);
int to = day2.get(Calendar.DAY_OF_YEAR);
int difference = to-from;
press f5 for running queries instead of f9. It will give you all the results in one go...
If you working with numpy, you can use the following solution which also works with negative numbers (it's also working on arrays)
import numpy as np
def round_down(num):
if num < 0:
return -np.ceil(abs(num))
else:
return np.int32(num)
round_down = np.vectorize(round_down)
round_down([-1.1, -1.5, -1.6, 0, 1.1, 1.5, 1.6])
> array([-2., -2., -2., 0., 1., 1., 1.])
I think it will also work if you just use the math
module instead of numpy
module.
public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
{
int iii1=0;
int iii2=0;
int iii3=0;
while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
// iii2 is the number of the occurences
if(iii2>0) {
positions_ = new int[iii2];
while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
positions_[iii3] = iii1-1;
iii3 = iii3 + 1;
System.out.println("position=" + positions_[iii3 - 1]);
}
}
return iii2;
}
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"
UPDATE mytable SET spares = CONCAT(spares, ',', '818') WHERE id = 1
not working for me.
spares is NULL
by default but its varchar
You can just use the method below:
document.write()
It is very simple, in the doc below I explain
document.write("<div class='div'>Some content inside the div (It is styled!)</div>")
_x000D_
.div {
background-color: red;
padding: 5px;
color: #fff;
font-family: Arial;
cursor: pointer;
}
.div:hover {
background-color: blue;
padding: 10px;
}
.div:hover:before {
content: 'Hover! ';
}
.div:active {
background-color: green;
padding: 15px;
}
.div:active:after {
content: ' Active! or clicked...';
}
_x000D_
<p>Below or above well show the div</p>
<p>Try pointing hover it and clicking on it. Those are tha styles aplayed. The text and background color changes.</p>
_x000D_