LinearLayout
means you can align views one by one (vertically/ horizontally).
RelativeLayout
means based on relation of views from its parents and other views.
ConstraintLayout
is similar to a RelativeLayout in that it uses relations to position and size widgets, but has additional flexibility and is easier to use in the Layout Editor.
WebView
to load html, static or dynamic pages.
FrameLayout
to load child one above another, like cards inside a frame, we can place one above another or anywhere inside the frame.
deprecated - AbsoluteLayout
means you have to give exact position where the view should be.
For more information, please check this address https://developer.android.com/guide/topics/ui/declaring-layout#CommonLayouts
Try below code to set view on specific location :-
TextView textView = new TextView(getActivity());
textView.setId(R.id.overflowCount);
textView.setText(count + "");
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
textView.setTextColor(getActivity().getResources().getColor(R.color.white));
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// to handle click
}
});
// set background
textView.setBackgroundResource(R.drawable.overflow_menu_badge_bg);
// set apear
textView.animate()
.scaleXBy(.15f)
.scaleYBy(.15f)
.setDuration(700)
.alpha(1)
.setInterpolator(new BounceInterpolator()).start();
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.topMargin = 100; // margin in pixels, not dps
layoutParams.leftMargin = 100; // margin in pixels, not dps
textView.setLayoutParams(layoutParams);
// add into my parent view
mainFrameLaout.addView(textView);
$date = new DateTime('2000-12-31');
$date->modify('+1 day');
echo $date->format('Y-m-d') . "\n";
For git mv
the
manual page
says
The index is updated after successful completion, […]
So, at first, you have to update the index on your own
(by using git add mobile.css
). However
git status
will still show two different files
$ git status
# On branch master
warning: LF will be replaced by CRLF in index.html
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: index.html
# new file: mobile.css
#
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# deleted: iphone.css
#
You can get a different output by running
git commit --dry-run -a
, which results in what you
expect:
Tanascius@H181 /d/temp/blo (master)
$ git commit --dry-run -a
# On branch master
warning: LF will be replaced by CRLF in index.html
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: index.html
# renamed: iphone.css -> mobile.css
#
I can't tell you exactly why we see these differences
between git status
and
git commit --dry-run -a
, but
here is a hint from
Linus:
git really doesn't even care about the whole "rename detection" internally, and any commits you have done with renames are totally independent of the heuristics we then use to show the renames.
A dry-run
uses the real renaming mechanisms, while a
git status
probably doesn't.
BigInteger.valueOf(1695609641).toByteArray()
Here is an approach for you to do something on a different thread and start listening to the key pressed in a different thread. And the Console will stop its processing when your actual process ends or the user terminates the process by pressing Esc key.
class SplitAnalyser
{
public static bool stopProcessor = false;
public static bool Terminate = false;
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Split Analyser starts");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Press Esc to quit.....");
Thread MainThread = new Thread(new ThreadStart(startProcess));
Thread ConsoleKeyListener = new Thread(new ThreadStart(ListerKeyBoardEvent));
MainThread.Name = "Processor";
ConsoleKeyListener.Name = "KeyListener";
MainThread.Start();
ConsoleKeyListener.Start();
while (true)
{
if (Terminate)
{
Console.WriteLine("Terminating Process...");
MainThread.Abort();
ConsoleKeyListener.Abort();
Thread.Sleep(2000);
Thread.CurrentThread.Abort();
return;
}
if (stopProcessor)
{
Console.WriteLine("Ending Process...");
MainThread.Abort();
ConsoleKeyListener.Abort();
Thread.Sleep(2000);
Thread.CurrentThread.Abort();
return;
}
}
}
public static void ListerKeyBoardEvent()
{
do
{
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
Terminate = true;
}
} while (true);
}
public static void startProcess()
{
int i = 0;
while (true)
{
if (!stopProcessor && !Terminate)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Processing...." + i++);
Thread.Sleep(3000);
}
if(i==10)
stopProcessor = true;
}
}
}
$string = trim(preg_replace('/\s+/','',$string));
List is an interface so you can't instanciate it. Use any of its implementatons instead e.g.
List<Object> object = new List<Object>();
About List : you can use any object as a generic param for it instance:
List<?> list = new ArrayList<String>();
or
List<?> list = new ArrayList<Integer>();
While using List<Object>
this declaration is invalid because it will be type missmatch.
<script type="text/javascript">
function test()
{
var path = "C:/es/h221.txt";
var pos =path.lastIndexOf( path.charAt( path.indexOf(":")+1) );
alert("pos=" + pos );
var filename = path.substring( pos+1);
alert( filename );
}
</script>
<form name="InputForm"
action="page2.asp"
method="post">
<P><input type="button" name="b1" value="test file button"
onClick="test()">
</form>
Another way to get datetime UTC with milliseconds.
from datetime import datetime
datetime.utcnow().isoformat(sep='T', timespec='milliseconds') + 'Z'
2020-10-29T14:46:37.655Z
console.log(document.getElementById('xx') ) evaluates to null.
document.getElementById('xx') !=null evaluates to false
You should use document.getElementById('xx') !== null
as it is a stronger equality check.
If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this:
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus
would return:
{
date: '9/10/11',
author: 'nilbus'
}
I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too:
The other clean solution if you don't want to pop all stack entries...
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.home_activity_container, fragmentInstance).addToBackStack(null).commit();
This will clean the stack first and then load a new fragment, so at any given point you'll have only single fragment in stack
pg_dump -h localhost -p 5432 -U postgres -d mydb -t my_table > backup.sql
You can take the backup of a single table but I would suggest to take the backup of whole database and then restore whichever table you need. It is always good to have backup of whole database.
I could get solution for such a similar problem with addition of a simple line
HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");
My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.
Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.
Firstly you have to make it executable using: chmod +x name_of_your_file_script
.
After you made it executable, you can run it using ./same_name_of_your_file_script
Explained here Language-specific editor settings but specifically:
"[markdown]": {
"editor.wordWrap": "on",
},
"[plaintext]": {
"editor.wordWrap": "bounded",
},
"[typescript]": {
"editor.tabSize": 2,
"editor.wordWrap": "off",
},
In addition to other replies. If you allow html
in options you can pass jQuery
object to content, and it will be appended to popover's content with all events and bindings. Here is the logic from source code:
html
is not allowed content data will be applied as texthtml
allowed and content data is string it will be applied as html
$("#popover-button").popover({
content: $("#popover-content"),
html: true,
title: "Popover title"
});
Stopwatch
is designed for this purpose and is one of the best ways to measure time execution in .NET.
var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Do not use DateTime to measure time execution in .NET.
UPDATE:
As pointed out by @series0ne in the comments section: If you want a real precise measurement of the execution of some code, you will have to use the performance counters that's built into the operating system. The following answer contains a nice overview.
It means that $objPage
is not an instance of an object. Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:
function page_properties(PageAtrributes $objPortal) {
...
$objPage->set_page_title($myrow['title']);
}
This function will only accept PageAtrributes
for the first parameter.
I got this to work using a .user.ini file in the same directory as my index.php script that loads my app. Here are the contents:
upload_max_filesize = "20M"
post_max_size = "25M"
This is the recommended solution for Heroku.
This works for me permanently:
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27","User")
1,Download the bat to exe converter and install it 2,Run the bat to exe application 3,Download .pco images if you want to make good looking exe 4,specify the bat file location(c:\my.bat) 5,Specify the location for saving the exe(ex:c:/my.exe) 6,Select Version Information Tab 7,Choose the icon file (downloaded .pco image) 8,if you want fill the information like version,comapny name etc 9,change the tab to option 10,Select the invisible application(This will hide the command prompt while running the application) 11,Choose 32 bit(if you select 64 bit exe will work only in 32 bit OS) 12,Compile 13,Copy the exe to the location where bat file executed properly 14,Run the exe
You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.
you can use OFFSET
and FETCH NEXT
SELECT id
FROM tablename
ORDER BY column
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;
NOTE:
OFFSET can only be used with ORDER BY clause. It cannot be used on its own.
OFFSET value must be greater than or equal to zero. It cannot be negative, else return error.
The OFFSET argument is used to identify the starting point to return rows from a result set. Basically, it exclude the first set of records.
The FETCH argument is used to return a set of number of rows. FETCH can’t be used itself, it is used in conjuction with OFFSET.
I have not yet seen a problem with the limit that did not involve large files stored within the document itself. There are already a variety of databases which are very efficient at storing/retrieving large files; they are called operating systems. The database exists as a layer over the operating system. If you are using a NoSQL solution for performance reasons, why would you want to add additional processing overhead to the access of your data by putting the DB layer between your application and your data?
JSON is a text format. So, if you are accessing your data through JSON, this is especially true if you have binary files because they have to be encoded in uuencode, hexadecimal, or Base 64. The conversion path might look like
binary file <> JSON (encoded) <> BSON (encoded)
It would be more efficient to put the path (URL) to the data file in your document and keep the data itself in binary.
If you really want to keep these files of unknown length in your DB, then you would probably be better off putting these in GridFS and not risking killing your concurrency when the large files are accessed.
When I was managing a large multi-user planning system backed by Oracle, our DBA had a weekly job that gathered statistics. Also, when we rolled out a significant change that could affect or be affected by statistics, we would force the job to run out of cycle to get things caught up.
Update: using .indexOf()
to detect if stat
value is one of arr
elements
Pure JavaScript
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
Answer in Swift 5 (Continuation of Ricky's answer in Swift)
Add the
UIGestureRecognizerDelegate
to your ViewController
override func viewDidLoad() {
super.viewDidLoad()
//Long Press
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
longPressGesture.minimumPressDuration = 0.5
self.tableView.addGestureRecognizer(longPressGesture)
}
And the function:
@objc func handleLongPress(longPressGesture: UILongPressGestureRecognizer) {
let p = longPressGesture.location(in: self.tableView)
let indexPath = self.tableView.indexPathForRow(at: p)
if indexPath == nil {
print("Long press on table view, not row.")
} else if longPressGesture.state == UIGestureRecognizer.State.began {
print("Long press on row, at \(indexPath!.row)")
}
}
None of these answer point out an important difference about these two operations. Drop table is an operation that can be rolled back. However, truncate cannot be rolled back ['TRUNCATE TABLE' can be rolled back as well]. In this way dropping a very large table can be very expensive if there are many rows, because they all have to be recorded in a temporary space in case you decide to roll it back.
Usually, if I want to get rid of a large table, I will truncate it, then drop it. This way the data will be nixed without record, and the table can be dropped, and that drop will be very inexpensive because no data needs to be recorded.
It is important to point out though that truncate just deletes data, leaving the table, while drop will, in fact, delete the data and the table itself. (assuming foreign keys don't preclude such an action)
...the correct answer is to use async/await with the native fs
promises module included in node. Upgrade to Node.js 10 or 11 (already supported by major cloud providers) and do this:
const fs = require('fs').promises;
// This must run inside a function marked `async`:
const file = await fs.readFile('filename.txt', 'utf8');
await fs.writeFile('filename.txt', 'test');
Do not use third-party packages and do not write your own wrappers, that's not necessary anymore.
Before Node 11.14.0
, you would still get a warning that this feature is experimental, but it works just fine and it's the way to go in the future. Since 11.14.0
, the feature is no longer experimental and is production-ready.
import
instead of require
?It works, too - but only in Node.js versions where this feature is not marked as experimental.
import { promises as fs } from 'fs';
(async () => {
await fs.writeFile('./test.txt', 'test', 'utf8');
})();
textBlock.Foreground = new SolidColorBrush(Colors.White);
remove from your config.yml
spool: { type: memory }
Then you will be to add try catch like this
try{
$mailer = $this->getMailer();
$response = $this->getMailer()->send($message);
}catch(\Swift_TransportException $e){
$response = $e->getMessage() ;
}
Some people have already mentioned HttpURLConnection, URL and URLConnection. If you need all the control and extra features that the curl library provides you (and more), I'd recommend Apache's httpclient.
You've answered the question with this statement:
Cron calls this
.sh
every 2 minutes
Cron does not run in a terminal, so why would you expect one to be set?
The most common reason for getting this error message is because the script attempts to source the user's .profile
which does not check that it's running in a terminal before doing something tty related. Workarounds include using a shebang line like:
#!/bin/bash -p
Which causes the sourcing of system-level profile scripts which (one hopes) does not attempt to do anything too silly and will have guards around code that depends on being run from a terminal.
If this is the entirety of the script, then the TERM
error is coming from something other than the plain content of the script.
Assuming you have a field for DateTime
, you could have your query look like this:
SELECT *
FROM TABLE
WHERE DateTime > (GetDate() + 90)
When you use addEventListener
, this
will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this
from within your function:
productLineSelect.addEventListener('change',getSelection,false);
function getSelection(){
var value = sel.options[this.selectedIndex].value;
alert(value);
}
If you want to pass in some other argument from the context where you call addEventListener
, you can use a closure, like this:
productLineSelect.addEventListener('change', function(){
// pass in `this` (the element), and someOtherVar
getSelection(this, someOtherVar);
},false);
function getSelection(sel, someOtherVar){
var value = sel.options[sel.selectedIndex].value;
alert(value);
alert(someOtherVar);
}
There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this hash collision:
>>> hash(1.1)
2040142438
>>> hash(4504.1)
2040142438
Yet it doesn't break the dictionary:
>>> d = { 1.1: 'a', 4504.1: 'b' }
>>> d[1.1]
'a'
>>> d[4504.1]
'b'
Sanity check:
>>> for k,v in d.items(): print(hash(k))
2040142438
2040142438
Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.
(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at hash(1.1) == hash(214748749.8)
.)
For those, who want to use Shell.Application.Namespace.Folder.CopyHere() and want to hide progress bars while copying, or use more options, the documentation is here:
https://docs.microsoft.com/en-us/windows/desktop/shell/folder-copyhere
To use powershell and hide progress bars and disable confirmations you can use code like this:
# We should create folder before using it for shell operations as it is required
New-Item -ItemType directory -Path "C:\destinationDir" -Force
$shell = New-Object -ComObject Shell.Application
$zip = $shell.Namespace("C:\archive.zip")
$items = $zip.items()
$shell.Namespace("C:\destinationDir").CopyHere($items, 1556)
Limitations of use of Shell.Application on windows core versions:
https://docs.microsoft.com/en-us/windows-server/administration/server-core/what-is-server-core
On windows core versions, by default the Microsoft-Windows-Server-Shell-Package is not installed, so shell.applicaton will not work.
note: Extracting archives this way will take a long time and can slow down windows gui
If you want the result as a list, then use:
x=[];
$("#list_id").children(':selected').each(function(){x.push($(this).text());})
Although this is old, it still keeps coming up pretty well in google. So I figured I'd mention this. No one mentioned to check for when x = 0.
0! and 1! both = 1.
This isn't being checked with the previous answers, and would cause a stack overflow, if fact(0) was run. Anyway simple fix:
public static int fact(int x){
if (x==1 | x==0)
return 1;
return fact(x-1) * x;
}// fact
Alternatively you can use img2pdf to convert images to pdf. Install it on Debian or Ubuntu with:
sudo apt install img2pdf
Convert one or more images to pdf:
img2pdf img.jpg -o output.pdf
It uses a different mechanism than imagemagick to embed the image into the pdf. When possible Img2pdf embeds the image directly into the pdf, without decoding and recoding the image.
Check http://msdn.microsoft.com/en-us/library/dd203099.aspx
under Cryptography Application Block.
Don't know if you will get your answer, but it's worth a try.
Edit after Comment.
Ok then check this code.
using System.Security.Cryptography;
public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) {
X509Certificate2 myCertificate;
try{
myCertificate = new X509Certificate2(PathToPrivateKeyFile);
} catch{
throw new CryptographicException("Unable to open key file.");
}
RSACryptoServiceProvider rsaObj;
if(myCertificate.HasPrivateKey) {
rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey;
} else
throw new CryptographicException("Private key not contained within certificate.");
if(rsaObj == null)
return String.Empty;
byte[] decryptedBytes;
try{
decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false);
} catch {
throw new CryptographicException("Unable to decrypt data.");
}
// Check to make sure we decrpyted the string
if(decryptedBytes.Length == 0)
return String.Empty;
else
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}
How are you importing ClassA into your AppDelegate Class? Did you include the .h file in the main project? I had this problem for a while because I didn't copy the header file into the main project as well as the normal #include "ClassA.h."
Copying, or creating the .h solved it for me.
I would recommend to also look at the Thread Stack Size and see if you get more threads created. The default Thread Stack Size for JRockit 1.5/1.6 is 1 MB for 64-bit VM on Linux OS. 32K threads will require a significant amount of physical and virtual memory to honor this requirement.
Try to reduce the Stack Size to 512 KB as a starting point and see if it helps creating more threads for your application. I also recommend to explore horizontal scaling e.g. splitting your application processing across more physical or virtual machines.
When using a 64-bit VM, the true limit will depend on the OS physical and virtual memory availability and OS tuning parameters such as ulimitc. I also recommend the following article as a reference:
OutOfMemoryError: unable to create new native thread – Problem Demystified
Your postgres server configuration seems correct
That should grant access from the client to the postgres server. So that leads me to believe the username / password is whats failing.
host all all 127.0.0.1/32 md5
host all all 192.168.0.1/32 trust
Test this by creating a specific user for that database
createuser -a -d -W -U postgres chaosuser
Then adjust your perl script to use the newly created user
my $dbh = DBI->connect("DBI:PgPP:database=chaosLRdb;host=192.168.0.1;port=5433", "chaosuser", "chaos123");
From your above needs, you will need to use both Python (to export pandas data frame) and VBA (to delete existing worksheet content and copy/paste external data).
With Python: use the to_csv or to_excel methods. I recommend the to_csv method which performs better with larger datasets.
# DF TO EXCEL
from pandas import ExcelWriter
writer = ExcelWriter('PythonExport.xlsx')
yourdf.to_excel(writer,'Sheet5')
writer.save()
# DF TO CSV
yourdf.to_csv('PythonExport.csv', sep=',')
With VBA: copy and paste source to destination ranges.
Fortunately, in VBA you can call Python scripts using Shell (assuming your OS is Windows).
Sub DataFrameImport()
'RUN PYTHON TO EXPORT DATA FRAME
Shell "C:\pathTo\python.exe fullpathOfPythonScript.py", vbNormalFocus
'CLEAR EXISTING CONTENT
ThisWorkbook.Worksheets(5).Cells.Clear
'COPY AND PASTE TO WORKBOOK
Workbooks("PythonExport").Worksheets(1).Cells.Copy
ThisWorkbook.Worksheets(5).Range("A1").Select
ThisWorkbook.Worksheets(5).Paste
End Sub
Alternatively, you can do vice versa: run a macro (ClearExistingContent) with Python. Be sure your Excel file is a macro-enabled (.xlsm) one with a saved macro to delete Sheet 5 content only. Note: macros cannot be saved with csv files.
import os
import win32com.client
from pandas import ExcelWriter
if os.path.exists("C:\Full Location\To\excelsheet.xlsm"):
xlApp=win32com.client.Dispatch("Excel.Application")
wb = xlApp.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm")
# MACRO TO CLEAR SHEET 5 CONTENT
xlApp.Run("ClearExistingContent")
wb.Save()
xlApp.Quit()
del xl
# WRITE IN DATA FRAME TO SHEET 5
writer = ExcelWriter('C:\Full Location\To\excelsheet.xlsm')
yourdf.to_excel(writer,'Sheet5')
writer.save()
And for all input and select:
$("input[required], select[required]").attr("oninvalid", "this.setCustomValidity('Required!')");
$("input[required], select[required]").attr("oninput", "setCustomValidity('')");
This HowTo for CentOS was easy to follow and only took about 5 minutes: https://wiki.centos.org/HowTos/Https
I won't detail each step here, but the main steps are:
1.) Install the openssl module for apache, if not already installed
2.) Generate a self-signed certificate
--At this point, you should be able to visit https://localhost successfully
3.) Set up a virtual host if needed
you could submit all parameters with such naming:
params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]
then later you do something like this:
foreach ($_REQUEST['params'] as $item) {
echo $item['topdiameter'];
echo $item['bottomdiameter'];
}
This is working for me It's very simple
return $.ajax({
type: 'POST',
url: urlBaseUrl
data: {someData:someData},
dataType: "json",
success: function(resultData) {
}
});
You can use the get() on each dict. Make sure that you have added the None check for each access.
Bug still active. This happens when JS becomes the initiator for new page(200), or redirect(301/302) 1 possible way to fix it - it disable JavaScript on request. I.e. in puppeteer you can use: page.setJavaScriptEnabled(false) while intercepting request(page.on('request'))
var mouseX;
var mouseY;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
$(".classForHoverEffect").mouseover(function(){
$('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});
the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,
$(".classForHoverEffect").mouseout(function(){
$('#DivToShow').fadeOut('slow');
});
If you DIV is already positioned, you can simply use
$('.classForHoverEffect').hover(function(){
$('#DivToShow').fadeIn('slow');
});
Also, keep in mind, your DIV style needs to be set to display:none;
in order for it to fadeIn or show.
For the benefit of any future visitors who may have missed my comments:
br {
border-bottom:1px dashed black;
}
does not work.
It has been tested in IE 6, 7 & 8, Firefox 2, 3 & 3.5B4, Safari 3 & 4 for Windows, Opera 9.6 & 10 (alpha) and Google Chrome (version 2) and it didn't work in any of them. If at some point in the future someone finds a browser that does support a border on a <br>
element, please feel free to update this list.
Also note that I tried a number of other things:
br {
border-bottom:1px dashed black;
display:block;
}
br:before { /* and :after */
border-bottom:1px dashed black;
/* content and display added as per porneL's comment */
content: "";
display: block;
}
br { /* and :before and :after */
content: url(a_dashed_line_image);
}
Of those, the following does works in Opera 9.6 and 10 (alpha) (thanks porneL!):
br:after {
border-bottom:1px dashed black;
content: "";
display: block;
}
Not very useful when it is only supported in one browser, but I always find it interesting to see how different browsers implement the specification.
A foreach loop in php will iterate over a copy of the original array, making next()
and prev()
functions useless. If you have an associative array and need to fetch the next item, you could iterate over the array keys instead:
foreach (array_keys($items) as $index => $key) {
// first, get current item
$item = $items[$key];
// now get next item in array
$next = $items[array_keys($items)[$index + 1]];
}
Since the resulting array of keys has a continuous index itself, you can use that instead to access the original array.
Be aware that $next
will be null
for the last iteration, since there is no next item after the last. Accessing non existent array keys will throw a php notice. To avoid that, either:
$next
index + 1
exists with array_key_exists()
Using method 2 the complete foreach could look like this:
foreach (array_keys($items) as $index => $key) {
// first, get current item
$item = $items[$key];
// now get next item in array
$next = null;
if (array_key_exists($index + 1, array_keys($items))) {
$next = $items[array_keys($items)[$index + 1]];
}
}
All values of column A that are not present in column B will have a red background. Hope that it helps as starting point.
Sub highlight_missings()
Dim i As Long, lastA As Long, lastB As Long
Dim compare As Variant
Range("A:A").ClearFormats
lastA = Range("A65536").End(xlUp).Row
lastB = Range("B65536").End(xlUp).Row
For i = 2 To lastA
compare = Application.Match(Range("a" & i), Range("B2:B" & lastB), 0)
If IsError(compare) Then
Range("A" & i).Interior.ColorIndex = 3
End If
Next i
End Sub
How about something like:
includes = $(wildcard include/*.h)
%.o: %.c ${includes}
gcc -Wall -Iinclude ...
You could also use the wildcards directly, but I tend to find I need them in more than one place.
Note that this only works well on small projects, since it assumes that every object file depends on every header file.
Different ways:
Using SQL Server Agent (If local instance)
schedule a job in sql server agent with a new step having type as "T-SQL" then run the job.
Using SQLCMD
To use SQLCMD refer http://technet.microsoft.com/en-us/library/ms162773.aspx
Using SQLPS
To use SQLPS refer http://technet.microsoft.com/en-us/library/cc280450.aspx
Thank you all for your contribution! I found the problem:
ITS A FIREBUG BUG !!!
My code works. I have asked the PHP Dev to change the input types hidden in to input type text. The disabled feature works. But the firebug console does not update this status!
you can test out this firebug bug by your self here http://jsbin.com/uneti3/3#. Thx to aSeptik for the example page.
update: 2. June 2012: Firebug in FF11 still has this bug.
it is similar to jason lee as he mentioned earlier:
in Jupyter notebook, you can access the current working directory by
pwd()
or by import OS from library and running os.getcwd()
i.e. for example
In[ ]: import os
os.getcwd( )
out[ ]: :c\\users\\admin\\Desktop\\python
(#This is my working directory)
Changing Working Directory
For changing the Working Directory (much more similar to current W.d just you need to change from os.getcwd()
to os.chdir('desired location')
In[ ]: import os
os.chdir('c:user/chethan/Desktop') (#This is where i want to update my w.d,
like that choose your desired location)
out[ ]: 'c:user\\chethan\\Desktop'
A good option is AutoTable(a Table plugin for jsPDF), it includes themes, rowspan, colspan, extract data from html, works with json, you can also personalize your headers and make them horizontals. Here is a demo.
Here's an answer for those deploying a Node.js application to Amazon AWS Elastic Beanstalk. I haven't seen this documented anywhere else:
Under Configuration -> Software -> Environment Properties
, simply set the key value pair TZ
and your time zone e.g. America/Los Angeles
, and Apply the change.
You can verify the effect by outputting new Date().toString()
in your Node app and paying attention to the time zone suffix.
The only negative side of DateTimeOffset I see is that Microsoft "forgot" (by design) to support it in their XmlSerializer class. But it has since been added to the XmlConvert utility class.
I say go ahead and use DateTimeOffset and TimeZoneInfo because of all the benefits, just beware when creating entities which will or may be serialized to or from XML (all business objects then).
Add this in the head section of your html
<link rel="icon" type="image/gif/png" href="mouse_select_left.png">
You can also run exactly same command at Cmd.exe command-line using PowerShell. I'd go with this approach for simplicity...
C:\>PowerShell -Command "temperature | prismcom.exe usb"
Please read up on Understanding the Windows PowerShell Pipeline
You can also type in C:\>PowerShell
at the command-line and it'll put you in PS C:\>
mode instanctly, where you can directly start writing PS.
Select All Occurrences of Find Match editor.action.selectHighlights
.
Ctrl+Shift+L
Cmd+Shift+L or Cmd+Ctrl+G on Mac
Array Sorting without using built in functions in java ......just make new File unsing this name -> (ArraySorting.java) ..... Run the Project and Enjoy it !!!!!
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class ArraySorting
{
public static void main(String args[])
{
int temp=0;
Scanner user_input=new Scanner(System.in);
System.out.println("enter Size of Array...");
int Size=user_input.nextInt();
int[] a=new int[Size];
System.out.println("Enter element Of an Array...");
for(int j=0;j<Size;j++)
{
a[j]=user_input.nextInt();
}
for(int index=0;index<a.length;index++)
{
for(int j=index+1;j<a.length;j++)
{
if(a[index] > a[j] )
{
temp = a[index];
a[index] = a[j];
a[j] = temp;
}
}
}
System.out.print("Output is:- ");
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
Set the min SDK version within your project's AndroidManifest.xml file:
<uses-sdk android:minSdkVersion="4"/>
What exactly causes the crash? Iron out all crashes/bugs in minimum version and then test in higher versions.
Only you need to empty /tmp directory using command & hit reboot your system. now you are able to play on asterisk CLI whatever you want.
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
The data.table
package introduced the IDate
class some time ago and zoo
-package-like functions to retrieve months, days, etc (Check ?IDate
). so, you can extract the desired info now in the following ways:
require(data.table)
df <- data.frame(id = 1:3,
date = c("2004-02-06" , "2006-03-14" , "2007-07-16"))
setDT(df)
df[ , date := as.IDate(date) ] # instead of as.Date()
df[ , yrmn := paste0(year(date), '-', month(date)) ]
df[ , yrmn2 := format(date, '%Y-%m') ]
a piece of code who work with python to read rs232 just in case somedoby else need it
ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()
I threw this stored procedure together with a start from @lain's comments above, kind of nice if you need to call it more than a few times (and not needing php):
delimiter //
-- ------------------------------------------------------------
-- Use the inforamtion_schema to tell if a field exists.
-- Optional param dbName, defaults to current database
-- ------------------------------------------------------------
CREATE PROCEDURE fieldExists (
OUT _exists BOOLEAN, -- return value
IN tableName CHAR(255), -- name of table to look for
IN columnName CHAR(255), -- name of column to look for
IN dbName CHAR(255) -- optional specific db
) BEGIN
-- try to lookup db if none provided
SET @_dbName := IF(dbName IS NULL, database(), dbName);
IF CHAR_LENGTH(@_dbName) = 0
THEN -- no specific or current db to check against
SELECT FALSE INTO _exists;
ELSE -- we have a db to work with
SELECT IF(count(*) > 0, TRUE, FALSE) INTO _exists
FROM information_schema.COLUMNS c
WHERE
c.TABLE_SCHEMA = @_dbName
AND c.TABLE_NAME = tableName
AND c.COLUMN_NAME = columnName;
END IF;
END //
delimiter ;
Working with fieldExists
mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_option', NULL) //
Query OK, 0 rows affected (0.01 sec)
mysql> select @_exists //
+----------+
| @_exists |
+----------+
| 0 |
+----------+
1 row in set (0.00 sec)
mysql> call fieldExists(@_exists, 'jos_vm_product', 'child_options', 'etrophies') //
Query OK, 0 rows affected (0.01 sec)
mysql> select @_exists //
+----------+
| @_exists |
+----------+
| 1 |
+----------+
In your case, since you are only showing 3 columns:
Name Value Business
or
Name Business Ecommerce Pro
why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.
As of 8, May, 2019:
JVM heap size depends on system configuration, meaning:
a) client jvm vs server jvm
b) 32bit vs 64bit.
Links:
1) updation from J2SE5.0: https://docs.oracle.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
2) brief answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html
3) detailed answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#default_heap_size
4) client vs server: https://www.javacodegeeks.com/2011/07/jvm-options-client-vs-server.html
Summary: (Its tough to understand from the above links. So summarizing them here)
1) Default maximum heap size for Client jvm is 256mb (there is an exception, read from links above).
2) Default maximum heap size for Server jvm of 32bit is 1gb and of 64 bit is 32gb (again there are exceptions here too. Kindly read that from the links).
So default maximum jvm heap size is: 256mb or 1gb or 32gb depending on VM, above.
Solutions using enum within class/struct (struct defaults with public members) and overloaded operators:
struct Color
{
enum Enum { RED, GREEN, BLUE };
Enum e;
Color() {}
Color(Enum e) : e(e) {}
Color operator=(Enum o) { e = o; return *this; }
Color operator=(Color o) { e = o.e; return *this; }
bool operator==(Enum o) { return e == o; }
bool operator==(Color o) { return e == o.e; }
operator Enum() const { return e; }
std::string toString() const
{
switch (e)
{
case Color::RED:
return "red";
case Color::GREEN:
return "green";
case Color::BLUE:
return "blue";
default:
return "unknown";
}
}
};
From the outside it looks nearly exactly like a class enum:
Color red;
red = Color::RED;
Color blue = Color::BLUE;
cout << red.toString() << " " << Color::GREEN << " " << blue << endl;
This will output "red 1 2". You could possibly overload << to make blue output a string (although it might cause ambiguity so not possible), but it wouldn't work with Color::GREEN since it doesn't automatically convert to Color.
The purpose of having an implicit convert to Enum (which implicitly converts to int or type given) is to be able to do:
Color color;
switch (color) ...
This works, but it also means that this work too:
int i = color;
With an enum class it wouldn't compile. You ought to be careful if you overload two functions taking the enum and an integer, or remove the implicit conversion...
Another solution would involve using an actual enum class and static members:
struct Color
{
enum class Enum { RED, GREEN, BLUE };
static const Enum RED = Enum::RED, GREEN = Enum::GREEN, BLUE = Enum::BLUE;
//same as previous...
};
It possibly takes more space, and is longer to make, but causes a compile error for implicit int conversions. I'd use this one because of that!
There's surely overhead with this though, but I think it's just simpler and looks better than other code I've seen. There's also potential for adding functionality, which could all be scoped within the class.
Edit: this works and most can be compiled before execution:
class Color
{
public:
enum class Enum { RED, GREEN, BLUE };
static const Enum RED = Enum::RED, GREEN = Enum::GREEN, BLUE = Enum::BLUE;
constexpr Color() : e(Enum::RED) {}
constexpr Color(Enum e) : e(e) {}
constexpr bool operator==(Enum o) const { return e == o; }
constexpr bool operator==(Color o) const { return e == o.e; }
constexpr operator Enum() const { return e; }
Color& operator=(Enum o) { const_cast<Enum>(this->e) = o; return *this; }
Color& operator=(Color o) { const_cast<Enum>(this->e) = o.e; return *this; }
std::string toString() const
{
switch (e)
{
case Enum::RED:
return "red";
case Enum::GREEN:
return "green";
case Enum::BLUE:
return "blue";
default:
return "unknown";
}
}
private:
const Enum e;
};
First make sure the PHP files themselves are UTF-8 encoded.
The meta tag is ignored by some browser. If you only use ASCII-characters, it doesn't matter anyway.
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
header('Content-Type: text/html; charset=utf-8');
The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.
const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation
var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
For a specific column, there is an alternative with sapply
DF <- data.frame(A = letters[1:5],
B = letters[6:10],
C = c(2, 5, NA, 8, NA))
DF_NEW <- sapply(seq(1, nrow(DF)),
function(i) ifelse(is.na(DF[i,3]) ==
TRUE,
0,
DF[i,3]))
DF[,3] <- DF_NEW
DF
select ltrim('000045', '0') from dual;
LTRIM
-----
45
This should do.
This solve my problème:
$description = strip_tags($value['Description']);
$description=preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $description);
$description= preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $description);
$description=str_replace(' & ', ' & ', html_entity_decode((htmlspecialchars_decode($description))));
#include <sys/types.h>
#include <sys/stat.h>
int status;
...
status = mkdir("/tmp/a/b/c", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
From here. You may have to do separate mkdirs for /tmp, /tmp/a, /tmp/a/b/ and then /tmp/a/b/c because there isn't an equivalent of the -p flag in the C api. Be sure and ignore the EEXISTS errno while you're doing the upper level ones.
I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.
CSS 3 has a new property for UI elements that will allow you to do this. The property is the resize property. So you would add the following to your stylesheet to disable resizing of all textarea elements:
textarea { resize: none; }
This is a CSS 3 property; use a compatibility chart to see browser compatibility.
Personally, I would find it very annoying to have resizing disabled on textarea elements. This is one of those situations where the designer is trying to "break" the user's client. If your design can't accommodate a larger textarea, you might want to reconsider how your design works. Any user can add textarea { resize: both !important; }
to their user stylesheet to override your preference.
I know two methods:
List<int> myList1 = new List<int>(myArray);
Or,
List<int> myList2 = myArray.ToList();
I'm assuming you know about data types and will change the types as you please.
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
returns
WindowsProductName WindowsVersion OsHardwareAbstractionLayer
------------------ -------------- --------------------------
Windows 10 Enterprise 1709 10.0.16299.371
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.
From the website:
char * strtok ( char * str, const char * delimiters );
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.
Parameters
- str
- C string to truncate.
- Notice that this string is modified by being broken into smaller strings (tokens). Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
- delimiters
- C string containing the delimiter characters.
- These may vary from one call to another.
Return Value
A pointer to the last token found in string. A null pointer is returned if there are no tokens left to retrieve.
Example
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
This new package looks nice http://cran.r-project.org/web/packages/openxlsx/openxlsx.pdf It doesn't require rJava and is using 'Rcpp' for speed.
Here is an example which gets big numbers very quickly.
import java.math.BigInteger;
/*
250000th fib # is: 36356117010939561826426 .... 10243516470957309231046875
Time to compute: 3.5 seconds.
1000000th fib # is: 1953282128707757731632 .... 93411568996526838242546875
Time to compute: 58.1 seconds.
*/
public class Main {
public static void main(String... args) {
int place = args.length > 0 ? Integer.parseInt(args[0]) : 250 * 1000;
long start = System.nanoTime();
BigInteger fibNumber = fib(place);
long time = System.nanoTime() - start;
System.out.println(place + "th fib # is: " + fibNumber);
System.out.printf("Time to compute: %5.1f seconds.%n", time / 1.0e9);
}
private static BigInteger fib(int place) {
BigInteger a = new BigInteger("0");
BigInteger b = new BigInteger("1");
while (place-- > 1) {
BigInteger t = b;
b = a.add(b);
a = t;
}
return b;
}
}
Here comes the structure of template I used:
select
/*this is a row number counter*/
( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 )
as rownumber,
d3.*
from
( select d1.* from table_name d1 ) d3
And here is my working code:
select
( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 )
as rownumber,
d3.*
from
( select year( d1.date ), month( d1.date ), count( d1.id )
from maindatabase d1
where ( ( d1.date >= '2013-01-01' ) and ( d1.date <= '2014-12-31' ) )
group by YEAR( d1.date ), MONTH( d1.date ) ) d3
You can use monitorEvents function.
Just inspect your element (right mouse click
? Inspect
on visible element or go to Elements
tab in Chrome Developer Tools and select wanted element) then go to Console
tab and write:
monitorEvents($0)
Now when you move mouse over this element, focus or click it, the name of the fired event will be displayed with its data.
To stop getting this data just write this to console:
unmonitorEvents($0)
$0
is just the last DOM element selected by Chrome Developer Tools. You can pass any other DOM object there (for example result of getElementById
or querySelector
).
You can also specify event "type" as second parameter to narrow monitored events to some predefined set. For example:
monitorEvents(document.body, 'mouse')
List of this available types is here.
I made a small gif that illustrates how this feature works:
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
I also had to remove the SMSS before it would get past that step.
No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".
x = np.zeros((2,3,4))
Simply Means:
2 Sets, 3 Rows per Set, 4 Columns
Example:
Input
x = np.zeros((2,3,4))
Output
Set # 1 ---- [[[ 0., 0., 0., 0.], ---- Row 1
[ 0., 0., 0., 0.], ---- Row 2
[ 0., 0., 0., 0.]], ---- Row 3
Set # 2 ---- [[ 0., 0., 0., 0.], ---- Row 1
[ 0., 0., 0., 0.], ---- Row 2
[ 0., 0., 0., 0.]]] ---- Row 3
Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.
Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".
Can't upvote so I'll repost @jfs comment cause I think it should be more visible.
@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02
With jQuery, you can do it like this -
var dataArray = $.map(dataObject,function(v){
return v;
});
The naive solution, of course, is to write a function for each enumeration that performs the conversion to string:
enum OS_type { Linux, Apple, Windows };
inline const char* ToString(OS_type v)
{
switch (v)
{
case Linux: return "Linux";
case Apple: return "Apple";
case Windows: return "Windows";
default: return "[Unknown OS_type]";
}
}
This, however, is a maintenance disaster. With the help of the Boost.Preprocessor library, which can be used with both C and C++ code, you can easily take advantage of the preprocessor and let it generate this function for you. The generation macro is as follows:
#include <boost/preprocessor.hpp>
#define X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOSTRING_CASE(r, data, elem) \
case elem : return BOOST_PP_STRINGIZE(elem);
#define DEFINE_ENUM_WITH_STRING_CONVERSIONS(name, enumerators) \
enum name { \
BOOST_PP_SEQ_ENUM(enumerators) \
}; \
\
inline const char* ToString(name v) \
{ \
switch (v) \
{ \
BOOST_PP_SEQ_FOR_EACH( \
X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOSTRING_CASE, \
name, \
enumerators \
) \
default: return "[Unknown " BOOST_PP_STRINGIZE(name) "]"; \
} \
}
The first macro (beginning with X_
) is used internally by the second. The second macro first generates the enumeration, then generates a ToString
function that takes an object of that type and returns the enumerator name as a string (this implementation, for obvious reasons, requires that the enumerators map to unique values).
In C++ you could implement the ToString
function as an operator<<
overload instead, but I think it's a bit cleaner to require an explicit "ToString
" to convert the value to string form.
As a usage example, your OS_type
enumeration would be defined as follows:
DEFINE_ENUM_WITH_STRING_CONVERSIONS(OS_type, (Linux)(Apple)(Windows))
While the macro looks at first like it is a lot of work, and the definition of OS_type
looks rather foreign, remember that you have to write the macro once, then you can use it for every enumeration. You can add additional functionality to it (e.g., a string-form to enum conversion) without too much trouble, and it completely solves the maintenance problem, since you only have to provide the names once, when you invoke the macro.
The enumeration can then be used as if it were defined normally:
#include <iostream>
int main()
{
OS_type t = Windows;
std::cout << ToString(t) << " " << ToString(Apple) << std::endl;
}
The code snippets in this post, beginning with the #include <boost/preprocessor.hpp>
line, can be compiled as posted to demonstrate the solution.
This particular solution is for C++ as it uses C++-specific syntax (e.g., no typedef enum
) and function overloading, but it would be straightforward to make this work with C as well.
For those using a second view controller with a storyboard in a .xib file, you will want to use the name of the .xib file in your constructor (without the.xib suffix).
let settings_dialog:SettingsViewController = SettingsViewController(nibName: "SettingsViewController", bundle: nil)
self.presentViewController(settings_dialog, animated: true, completion: nil)
You can add destroy:true
to the configuration to make sure data table already present is removed before being reinitialized.
$('#example').dataTable({
destroy: true,
...
});
Add this method to a static class:
public static Rect GetAbsolutePlacement(this FrameworkElement element, bool relativeToScreen = false)
{
var absolutePos = element.PointToScreen(new System.Windows.Point(0, 0));
if (relativeToScreen)
{
return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
}
var posMW = Application.Current.MainWindow.PointToScreen(new System.Windows.Point(0, 0));
absolutePos = new System.Windows.Point(absolutePos.X - posMW.X, absolutePos.Y - posMW.Y);
return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
}
Set relativeToScreen
paramater to true
for placement from top left corner of whole screen or to false
for placement from top left corner of application window.
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause
:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
This should work:
String s = "123foo";
Character.isDigit(s.charAt(0));
I use open query to perform this task like so:
select top 1 *
INTO [DATABASE_TO_INSERT_INTO].[dbo].[TABLE_TO_SELECT_INTO]
from openquery(
[LINKED_SERVER_NAME],
'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)
The example above uses open query to select data from a database on a linked server into a database of your choosing.
Note: For completeness of reference, you may perform a simple select like so:
select top 1 * from openquery(
[LINKED_SERVER_NAME],
'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)
ALTER TABLE `table_name` AUTO_INCREMENT=1
As @Richard pointed out above, the onClick needs to have a capital 'C'.
$('#stop').click(function() {
$('next').attr('onClick','stopMoving()');
}
You can't. XSS protection. Cross site contents can not be read by javascript. No major browser will allow you that. I'm sorry, but this is a design flaw, you should drop the idea.
EDIT
Note that if you have editing access to the website loaded into the iframe, you can use postMessage (also see the browser compatibility)
In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH
), using named ranges and the EVALUATE
function as I found from this link.
For example, I put the following terms as text in a cell, $G$1
:
"PRB", "utilization", "alignment", "spectrum"
Then, I defined a named range named search_terms
for that cell as described in the link above and shown in the figure below:
In the Refers to:
field I put the following:
=EVALUATE("{" & TDoc_List!$G$1 & "}")
The above EVALUATE
expression is simple used to emulate the literal string
{"PRB", "utilization", "alignment", "spectrum"}
to be used as input to the SEARCH
function: using a direct reference to the SINGLE cell $G$1
(augmented with the curly braces in that case) inside SEARCH
does not work, hence the use of named ranges and EVALUATE
.
The trick now consists in replacing the direct reference to $G$1
by the EVALUATE
-augmented named range search_terms
.
It really works, and shows once more how powerful Excel really is!
Hope this helps.
Per now (February 2012) there's a new feature for this. Check here
Code sample (taken from the web):
<?php
$v8 = new V8Js();
/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;
try {
var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
var_dump($e);
}
?>
It's easier for me to think in these terms, but borrowing from other answers. The value you want is located in the series:
df[*column*][*row*]
where column and row point to the value you want returned. For your example, column is 'A' and for row you use a mask:
df['B'] == 3
To get the value from the series there are several options:
df['A'][df['B'] == 3].values[0]
df['A'][df['B'] == 3].iloc[0]
df['A'][df['B'] == 3].to_numpy()[0]
There are methods like WriteAllText
in the File
class for common operations on files.
Use the MapPath
method to get the physical path for a file in your web application.
File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);
var_dump($obj);
If you want more info you can use a ReflectionClass:
Underneath working solution with normal choice field. my problem was that each user have their own CUSTOM choicefield options based on few conditions.
class SupportForm(BaseForm):
affiliated = ChoiceField(required=False, label='Fieldname', choices=[], widget=Select(attrs={'onchange': 'sysAdminCheck();'}))
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
grid_id = get_user_from_request(self.request)
for l in get_all_choices().filter(user=user_id):
admin = 'y' if l in self.core else 'n'
choice = (('%s_%s' % (l.name, admin)), ('%s' % l.name))
self.affiliated_choices.append(choice)
super(SupportForm, self).__init__(*args, **kwargs)
self.fields['affiliated'].choices = self.affiliated_choice
The easiest solution is below:
.outer-div{_x000D_
width: 100%;_x000D_
height: 200px;_x000D_
display: flex;_x000D_
border:1px solid #000;_x000D_
}_x000D_
.inner-div{_x000D_
margin: auto;_x000D_
text-align:center;_x000D_
border:1px solid red;_x000D_
}
_x000D_
<div class="outer-div">_x000D_
<div class="inner-div">_x000D_
Hey there!_x000D_
</div>_x000D_
</div>
_x000D_
I have used the using Newtonsoft.Json as below. Create an object:
public class WorklistSortColumn
{
[JsonProperty(PropertyName = "field")]
public string Field { get; set; }
[JsonProperty(PropertyName = "dir")]
public string Direction { get; set; }
[JsonIgnore]
public string SortOrder { get; set; }
}
Now Call the below method to serialize to Json object as shown below.
string sortColumn = JsonConvert.SerializeObject(worklistSortColumn);
Use table-layout:fixed
in the table and word-wrap:break-word
in the td.
See this example:
<html>
<head>
<style>
table {border-collapse:collapse; table-layout:fixed; width:310px;}
table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
</style>
</head>
<body>
<table>
<tr>
<td>1</td>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>
</tr>
<tr>
<td>2</td>
<td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>
<td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>
</tr>
<tr>
<td>3</td>
<td></td>
<td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>
</tr>
</table>
</body>
</html>
table {border-collapse:collapse; table-layout:fixed; width:310px;}_x000D_
table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>Lorem Ipsum</td>_x000D_
<td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>_x000D_
<td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td></td>_x000D_
<td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
If you use a Custom format, rather than one of the pre-selected Date formats, the export to CSV will keep your selected format. Otherwise it defaults back to the US format
UPDATE:3 Now that I have upgraded to new Router, @borislemke's approach will not work if you use CanDeactivate
guard. I'm degrading to my old method, ie:
this answer
UPDATE2: Router events in new-router look promising and the answer by @borislemke seems to cover the main aspect of spinner implementation, I havent't tested it but I recommend it.
UPDATE1: I wrote this answer in the era of Old-Router
, when there used to be only one event route-changed
notified via router.subscribe()
. I also felt overload of the below approach and tried to do it using only router.subscribe()
, and it backfired because there was no way to detect canceled navigation
. So I had to revert back to lengthy approach(double work).
If you know your way around in Angular2, this is what you'll need
Boot.ts
import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';
bootstrap(MyApp, [SpinnerService]);
Root Component- (MyApp)
import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
@Component({
selector: 'my-app',
directives: [SpinnerComponent],
template: `
<spinner-component></spinner-component>
<router-outlet></router-outlet>
`
})
export class MyApp { }
Spinner-Component (will subscribe to Spinner-service to change the value of active accordingly)
import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
selector: 'spinner-component',
'template': '<div *ngIf="active" class="spinner loading"></div>'
})
export class SpinnerComponent {
public active: boolean;
public constructor(spinner: SpinnerService) {
spinner.status.subscribe((status: boolean) => {
this.active = status;
});
}
}
Spinner-Service (bootstrap this service)
Define an observable to be subscribed by spinner-component to change the status on change, and function to know and set the spinner active/inactive.
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';
@Injectable()
export class SpinnerService {
public status: Subject<boolean> = new Subject();
private _active: boolean = false;
public get active(): boolean {
return this._active;
}
public set active(v: boolean) {
this._active = v;
this.status.next(v);
}
public start(): void {
this.active = true;
}
public stop(): void {
this.active = false;
}
}
All Other Routes' Components
(sample):
import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
template: `<div *ngIf="!spinner.active" id="container">Nothing is Loading Now</div>`
})
export class SampleComponent {
constructor(public spinner: SpinnerService){}
ngOnInit(){
this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
}
ngOnDestroy(){
this.spinner.start();
}
}
Firstly, the level name to use is FINE
, not DEBUG
. Let's assume for a minute that DEBUG
is actually valid, as it makes the following explanation make a bit more sense...
In the Handler specific properties
section, you're setting the logging level for those handlers to DEBUG
. This means the handlers will handle any log messages with the DEBUG
level or higher. It doesn't necessarily mean any DEBUG
messages are actually getting passed to the handlers.
In the Facility specific properties
section, you're setting the logging level for a few explicitly-named loggers to DEBUG
. For those loggers, anything at level DEBUG
or above will get passed to the handlers.
The default logging level is INFO
, and apart from the loggers mentioned in the Facility specific properties
section, all loggers will have that level.
If you want to see all FINE
messages, add this:
.level = FINE
However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:
your.package.level = FINE
See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE
instead of DEBUG
:
...
1catalina.org.apache.juli.FileHandler.level = FINE
...
and also gives you examples of setting additional logging levels:
# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE
Found that using the following worked across most major browsers (Chrome, IE, Safari iOS/OSX) except Firefox (v50.0.2) when using flexbox and relying on width: auto
.
.your_element {
word-wrap: break-word;
overflow-wrap: break-word;
word-break: break-word;
}
Note: you may need to add browser vendor prefixes if you are not using an autoprefixer.
Another thing to watch out for is text using
for spacing can cause line breaks mid-word.
Yes, Guava provides this in the Resources
class. For example:
URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);
I agree with @adietisheim and the rest of people that suggest HttpClient.
I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.
An example of code to make a put http call is as follows:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(URI);
StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);
putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);
Surround it with an \mbox{}
Haider's answer is correct for pre-iOS 6. However, as of iOS 6 viewDidUnload and viewWillUnload are never called. The docs state: "Views are no longer purged under low-memory conditions and so this method is never called."
Beware of triggers. Maybe the issue is with some operation in the trigger for inserted rows.
The microsoft telnet.exe
is not scriptable without using another script (which needs keyboard focus), as shown in another answer to this question, but there is a free
Telnet Scripting Tool v.1.0 by Albert Yale
that you can google for and which is both scriptable and loggable and can be launched from a batch file without needing keyboard focus.
The problem with telnet.exe and a second script when keyboard focus is being used is that if someone is using the computer at the time the script runs, then it is highly likely that the script will fail due to mouse clicks and keyboard use at that moment in time.
You probably finally realized this between posting this question and today, but the very nature of selectors makes it impossible to navigate through hierarchically unrelated HTML elements.
Or, to put it simply, since you said in your comment that
there are no uniform parent containers
... it's just not possible with selectors alone, without modifying the markup in some way as shown by the other answers.
You have to use the jQuery .eq()
solution.
Indexing a list is done using double bracket, i.e. hypo_list[[1]]
(e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table
does not return a table but a dataframe (see value section in ?read.table
). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Table objects
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
This solution worked for me:
<body onload="setTimeout(function() { document.myform.submit() }, 5000)">
<form action=TripRecorder name="myform">
<textarea id="result1" name="res1" value="str1" cols="20" rows="1" ></textarea> <br> <br/>
<textarea id="result2" name="res2" value="str2" cols="20" rows="1" ></textarea>
</form>
</body>
Here is some code that will give you the general idea.
You need to create a custom ClientHttpRequestFactory
in order to trust the certificate.
It looks like this:
final ClientHttpRequestFactory clientHttpRequestFactory =
new MyCustomClientHttpRequestFactory(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER, serverInfo);
restTemplate.setRequestFactory(clientHttpRequestFactory);
This is the implementation for MyCustomClientHttpRequestFactory
:
public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
private final HostnameVerifier hostNameVerifier;
private final ServerInfo serverInfo;
public MyCustomClientHttpRequestFactory (final HostnameVerifier hostNameVerifier,
final ServerInfo serverInfo) {
this.hostNameVerifier = hostNameVerifier;
this.serverInfo = serverInfo;
}
@Override
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod)
throws IOException {
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setHostnameVerifier(hostNameVerifier);
((HttpsURLConnection) connection).setSSLSocketFactory(initSSLContext()
.getSocketFactory());
}
super.prepareConnection(connection, httpMethod);
}
private SSLContext initSSLContext() {
try {
System.setProperty("https.protocols", "TLSv1");
// Set ssl trust manager. Verify against our server thumbprint
final SSLContext ctx = SSLContext.getInstance("TLSv1");
final SslThumbprintVerifier verifier = new SslThumbprintVerifier(serverInfo);
final ThumbprintTrustManager thumbPrintTrustManager =
new ThumbprintTrustManager(null, verifier);
ctx.init(null, new TrustManager[] { thumbPrintTrustManager }, null);
return ctx;
} catch (final Exception ex) {
LOGGER.error(
"An exception was thrown while trying to initialize HTTP security manager.", ex);
return null;
}
}
In this case my serverInfo
object contains the thumbprint of the server.
You need to implement the TrustManager
interface to get
the SslThumbprintVerifier
or any other method you want to verify your certificate (you can also decide to also always return true
).
The value org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
allows all host names.
If you need to verify the host name,
you will need to implement it differently.
I'm not sure about the user and password and how you implemented it.
Often,
you need to add a header to the restTemplate
named Authorization
with a value that looks like this: Base: <encoded user+password>
.
The user+password
must be Base64
encoded.
I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.
As @Maloric mentioned in his answer to this question:
var jo = JObject.Parse(myJsonString);
To use JObject, you need the following in your class file
using Newtonsoft.Json.Linq;
This error comes when you append this line os.path.join(os.path.dirname(__file__))
in python interactive shell.
Python Shell
doesn't detect current file path in __file__
and it's related to your filepath
in which you added this line
So you should write this line os.path.join(os.path.dirname(__file__))
in file.py
. and then run python file.py
, It works because it takes your filepath.
The Bundler docs address this question as well:
ORIGINAL: http://gembundler.com/v1.3/rationale.html
EDIT: http://web.archive.org/web/20160309170442/http://bundler.io/v1.3/rationale.html
See the section called "Checking Your Code into Version Control":
After developing your application for a while, check in the application together with the Gemfile and Gemfile.lock snapshot. Now, your repository has a record of the exact versions of all of the gems that you used the last time you know for sure that the application worked. Keep in mind that while your Gemfile lists only three gems (with varying degrees of version strictness), your application depends on dozens of gems, once you take into consideration all of the implicit requirements of the gems you depend on.
This is important: the Gemfile.lock makes your application a single package of both your own code and the third-party code it ran the last time you know for sure that everything worked. Specifying exact versions of the third-party code you depend on in your Gemfile would not provide the same guarantee, because gems usually declare a range of versions for their dependencies.
The next time you run bundle install on the same machine, bundler will see that it already has all of the dependencies you need, and skip the installation process.
Do not check in the .bundle directory, or any of the files inside it. Those files are specific to each particular machine, and are used to persist installation options between runs of the bundle install command.
If you have run bundle pack, the gems (although not the git gems) required by your bundle will be downloaded into vendor/cache. Bundler can run without connecting to the internet (or the RubyGems server) if all the gems you need are present in that folder and checked in to your source control. This is an optional step, and not recommended, due to the increase in size of your source control repository.
You can use the function system
.
system("color *background**foreground*");
For background and foreground, type in a number from 0 - 9 or a letter from A - F.
For example:
system("color A1");
std::cout<<"hi"<<std::endl;
That would display the letters "hi" with a green background and blue text.
To see all the color choices, just type in:
system("color %");
to see what number or letter represents what color.
you should use the below update query
UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id IN(1, 2, 3, 4)
UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id <= 4
Either of the above queries should work.
Assuming the following method to test:
public boolean doSomething(SomeClass arg);
Mockito documentation says that you should not use captor in this way:
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));
Because you can just use matcher during stubbing:
when(someObject.doSomething(eq(expected))).thenReturn(true);
But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor
and this is the case for which it is designed:
ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));
SELECT SALARY
FROM (SELECT *
FROM EMPLOYEE
ORDER BY SALARY
DESC LIMIT ***2***) AS TOP_SALARY
ORDER BY SALARY ASC
LIMIT 1
You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you
s = requests.Session()
# all cookies received will be stored in the session object
s.post('http://www...',data=payload)
s.get('http://www...')
Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:
Goto IntelliJ -> Preferences -> Plugin
Search for maven, you will see 1. Maven Integration 2. Maven Integration Extension.
Select the Maven Integration option and restart your Intellij
If you want to disable ctrl+f5 , ctrl+R , f5 ,backspace then you can use this simple code. This code is working in Mozila as well as Chrome . Add this code inside your body tag:
<body onkeydown="return (event.keyCode == 154)">
Not sure why this worked for me while nothing else did but just in case anyone else is still looking...
In between head tags:
<script>
function myFunction() {
script code
}
</script>
Then for the < a > tag:
<a href='' onclick='myFunction()' > Call Function </a>
$(document).ready(function() {
$('#div_one').bind('click', function() {
$('#div_two').addClass('large');
});
});
If I understood your question.
Or you can modify css directly:
var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');
Upload sql file
Make sure to select your database in this award winning GUI:
The problem occurs in declaring context, while using Glide for ImageView or While using intent in recyclerview for item onClick. I Found this working for me which helps me to Declare context to use in Glide or Intent or Toast.
public class NoteAdapter extends FirestoreRecyclerAdapter<Note,NoteAdapter.NoteHolder> {
Context context;
public NoteAdapter(@NonNull FirestoreRecyclerOptions<Note> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull NoteHolder holder, int position, @NonNull Note model) {
holder.r_tv.setText(model.getTitle());
Glide.with(CategoryActivity.context).load(model.getImage()).into(holder.r_iv);
context = holder.itemView.getContext();
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(context, SuggestActivity.class);
context.startActivity(i);
}
});
}
@NonNull
@Override
public NoteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category,parent,false);
return new NoteHolder(v);
}
public static class NoteHolder extends RecyclerView.ViewHolder
{
TextView r_tv;
ImageView r_iv;
public NoteHolder(@NonNull View itemView) {
super(itemView);
r_tv = itemView.findViewById(R.id.r_tv);
r_iv = itemView.findViewById(R.id.r_iv);
}
}
}
And in my case it was simple: I used 'Add WCF Service' wizard in Visual Studio, which automatically created corresponding sections in app.config. Then I went on reading How to: Host a WCF Service in a Managed Application. The problem was: I didn't need to specify the url to run the web service.
Replace:
using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
With:
using (ServiceHost host = new ServiceHost(typeof(HelloWorldService))
And the error is gone.
Generic idea: if you provide base address as a param and specify it in config, you get this error. Most probably, that's not the only way to get the error, thou.
I think you are missing using System.Linq;
from this system class.
and also add using System.Data.Entity;
to the code
What you're trying to insert is not a date, I think, but a string. You need to use to_date()
function, like this:
insert into table t1 (id, date_field) values (1, to_date('20.06.2013', 'dd.mm.yyyy'));
There are 2 solutions for your problem:
mw.geometry('500x500')
OR
back.place(x = 0, y = 0, relwidth = 1, relheight = 1)
*The second option should be used in place of back.pack()
The index is nothing but a data structure that stores the values for a specific column in a table. An index is created on a column of a table.
Example: We have a database table called User
with three columns – Name
, Age
and Address
. Assume that the User
table has thousands of rows.
Now, let’s say that we want to run a query to find all the details of any users who are named 'John'. If we run the following query:
SELECT * FROM User
WHERE Name = 'John'
The database software would literally have to look at every single row in the User
table to see if the Name
for that row is ‘John’. This will take a long time.
This is where index
helps us: index is used to speed up search queries by essentially cutting down the number of records/rows in a table that needs to be examined.
How to create an index:
CREATE INDEX name_index
ON User (Name)
An index
consists of column values(Eg: John) from one table, and those values are stored in a data structure.
So now the database will use the index to find employees named John because the index will presumably be sorted alphabetically by the Users name. And, because it is sorted, it means searching for a name is a lot faster because all names starting with a “J” will be right next to each other in the index!
If you don't/can't keep the connection open you could use screen, if you have the rights to install it.
user@localhost $ screen -t remote-command
user@localhost $ ssh user@target # now inside of a screen session
user@remotehost $ cd /some/directory; program-to-execute &
To detach the screen session: ctrl-a d
To list screen sessions:
screen -ls
To reattach a session:
screen -d -r remote-command
Note that screen can also create multiple shells within each session. A similar effect can be achieved with tmux.
user@localhost $ tmux
user@localhost $ ssh user@target # now inside of a tmux session
user@remotehost $ cd /some/directory; program-to-execute &
To detach the tmux session: ctrl-b d
To list screen sessions:
tmux list-sessions
To reattach a session:
tmux attach <session number>
The default tmux control key, 'ctrl-b', is somewhat difficult to use but there are several example tmux configs that ship with tmux that you can try.
A global JS variable (object) can be used to pass data between components. Example: Passing data from Ammlogin.vue to Options.vue. In Ammlogin.vue rspData is set to the response from the server. In Options.vue the response from the server is made available via rspData.
index.html:
<script>
var rspData; // global - transfer data between components
</script>
Ammlogin.vue:
....
export default {
data: function() {return vueData},
methods: {
login: function(event){
event.preventDefault(); // otherwise the page is submitted...
vueData.errortxt = "";
axios.post('http://vueamm...../actions.php', { action: this.$data.action, user: this.$data.user, password: this.$data.password})
.then(function (response) {
vueData.user = '';
vueData.password = '';
// activate v-link via JS click...
// JSON.parse is not needed because it is already an object
if (response.data.result === "ok") {
rspData = response.data; // set global rspData
document.getElementById("loginid").click();
} else {
vueData.errortxt = "Felaktig avändare eller lösenord!"
}
})
.catch(function (error) {
// Wu oh! Something went wrong
vueData.errortxt = error.message;
});
},
....
Options.vue:
<template>
<main-layout>
<p>Alternativ</p>
<p>Resultat: {{rspData.result}}</p>
<p>Meddelande: {{rspData.data}}</p>
<v-link href='/'>Logga ut</v-link>
</main-layout>
</template>
<script>
import MainLayout from '../layouts/Main.vue'
import VLink from '../components/VLink.vue'
var optData = { rspData: rspData}; // rspData is global
export default {
data: function() {return optData},
components: {
MainLayout,
VLink
}
}
</script>
With Xcode 9 the interface has been updated and now the way I did to resolve the problem was this:
Three Step Process:
First:
open Terminal->$ whereis java
it would give output like this:
java: /usr/bin/java /usr/share/java /usr/share/man/man1/java.1.gz
Second:
ls -l /usr/bin/java
It would give output like this:
lrwxrwxrwx 1 root root 22 Feb 9 10:59 /usr/bin/java -> /etc/alternatives/java
Third:
ls -l /etc/alternatives/java
output is the JDK path:
lrwxrwxrwx 1 root root 46 Feb 9 10:59 /etc/alternatives/java -> /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html
Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html
Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm
Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html
In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).
In order to test your app on a real device rather than pay the Apple Developer fee (or jailbreak your device), you can use the new free provisioning that Xcode 7 and iOS 9 supports.
Here are the steps taken more or less from the documentation (which is pretty good, so give it a read):
1. Add your Apple ID in Xcode
Go to XCode > Preferences > Accounts tab > Add button (+) > Add Apple ID. See the docs for more help.
2. Click the General tab in the Project Navigator
3. Choose your Apple ID from the Team popup menu.
4. Connect your device and choose it in the scheme menu.
5. Click the Fix Issues button
If you get an error about the bundle name being invalid, change it to something unique.
6. Run your app
In Xcode, click the Build and run button.
7. Trust the app developer in the device settings
After running your app, you will get a security error because the app you want to run is not from the App Store.
On your device, go to Settings > General > Profile > your-Apple-ID-name > Trust your-Apple-ID-name > Trust.
8. Run your app on your device again.
That's it. You can now run your own (or any other apps that you have the source code for) without having to dish out the $99 dollars. Thank you, Apple, for finally allowing this.
Following this good answer, I'd use these options for a bar chart:
var chartOptions = {
animation: false,
responsive : true,
tooltipTemplate: "<%= value %>",
tooltipFillColor: "rgba(0,0,0,0)",
tooltipFontColor: "#444",
tooltipEvents: [],
tooltipCaretSize: 0,
onAnimationComplete: function()
{
this.showTooltip(this.datasets[0].bars, true);
}
};
window.myBar = new Chart(ctx1).Bar(chartData, chartOptions);
This still uses the tooltip system and his advantages (automatic positionning, templating, ...) but hiding the decorations (background color, caret, ...)
Easy solution:
$('.slick-slider').slick({
arrows: true,
prevArrow:"<img class='a-left control-c prev slick-prev' src='YOUR LEFT ARROW IMAGE URL'>",
nextArrow:"<img class='a-right control-c next slick-next' src='YOUR RIGHT ARROW IMAGE URL'>"
});
Image URLs can be local or cdn-type stuff (web icons, etc.).
Example CSS (adjust as needed here, this is just an example of what's possible):
.control-c {
width: 30px;
height: 30px;
}
This worked well for me!
With the excellent matplotlib
and numpy
packages
from matplotlib import pyplot as mp
import numpy as np
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
mp.plot(x_values, gaussian(x_values, mu, sig))
mp.show()
this solved my error
echo yes | $ANDROID_HOME/tools/bin/sdkmanager "build-tools;25.0.2"
Here is my solution which is further refined from one posted by @john-magnolia and solves some of its issues
/**
* Toggle on/off arrow for Twitter Bootstrap collapsibles.
*
* Multi-collapsible-friendly; supports several collapsibles in the same group, on the same page.
*/
function animateCollapsibles() {
$('.collapse').on('show', function() {
var $t = $(this);
var header = $("a[href='#" + $t.attr("id") + "']");
header.find(".icon-chevron-right").removeClass("icon-chevron-right").addClass("icon-chevron-down");
}).on('hide', function(){
var $t = $(this);
var header = $("a[href='#" + $t.attr("id") + "']");
header.find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-right");
});
}
And here is the example markup:
<div class="accordion" id="accordion-send">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion-send" href="#collapse-refund">
<i class="icon icon-chevron-right"></i> Send notice
</a>
</div>
<div id="collapse-refund" class="accordion-body collapse">
<div class="accordion-inner">
<p>Lorem ipsum Toholampi city</p>
</div>
</div>
</div>
</div>
Embed in a stack view. Stack view is a component recently added by Apple in their iOS SDK to reflect grid based implementations in java script web based front end libraries such as bootstrap.
If you need to set the new value based on the old field value that is do something like:
update my_table set field_1 = field_1 + 1 where pk_field = some_value
use query expressions:
MyModel.objects.filter(pk=some_value).update(field1=F('field1') + 1)
This will execute update atomically that is using one update request to the database without reading it first.
I have another suggestion. When you want myDiv to have a height of 100%, use these extra 3 attributes on your div:
myDiv {
min-height: 100%;
overflow-y: hidden;
position: relative;
}
That should do the job!
A simple method like below can also be used
public static String padString(String str, int leng,char chr) {
for (int i = str.length(); i <= leng; i++)
str += chr;
return str;
}
You can disable expandtab option from within Vim as below:
:set expandtab!
or
:set noet
PS: And set it back when you are done with inserting tab, with "set expandtab" or "set et"
PS: If you have tab set equivalent to 4 spaces in .vimrc (softtabstop), you may also like to set it to 8 spaces in order to be able to insert a tab by pressing tab key once instead of twice (set softtabstop=8).
It's doing exactly what you told it to do and is working correctly. Read more about floating point confusion and maybe try decimal objects instead.
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
I believe you need to specify "Option Infer On" for this to work.
Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.
Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.
Opinion incoming:
Also, you mention that you've got "Option Explicit Off". Please don't do this.
Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":
Dim X as Integer
Y = 3
This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.
You can declare an object of a class in another Class,that's possible but you cant initialize that object. For that you need to do something like this :--> (inside main)
Orderbook o1;
o1.m.check(side)
but that would be unnecessary. Keeping things short :-
You can't call functions inside a Class
Maybe this could inspire you, try to align to jbb conventions:
https://docs.openstack.org/infra/jenkins-job-builder/definition.html#inclusion-tags
- job:
name: test-job-include-raw-1
builders:
- shell:
!include-raw: include-raw001-hello-world.sh
SELECT GETDATE() + (hours / 24.00000000000000000)
Adding to GETDATE() defaults to additional days, but it will also convert down to hours/seconds/milliseconds using decimal.
I'll address any questions you have... but here is an improved pattern you should follow to reduce code duplication.
As a sidenote though, you should consider not doing pagination on client-side. Since if you have a huge dataset, it would mean you need to download all the data before your page loads. Better to implement server-side pagination instead.
Fiddle: http://jsfiddle.net/Lzp0dw83/
HTML
<div id="listingTable"></div>
<a href="javascript:prevPage()" id="btn_prev">Prev</a>
<a href="javascript:nextPage()" id="btn_next">Next</a>
page: <span id="page"></span>
Javascript (put anywhere):
var current_page = 1;
var records_per_page = 2;
var objJson = [
{ adName: "AdName 1"},
{ adName: "AdName 2"},
{ adName: "AdName 3"},
{ adName: "AdName 4"},
{ adName: "AdName 5"},
{ adName: "AdName 6"},
{ adName: "AdName 7"},
{ adName: "AdName 8"},
{ adName: "AdName 9"},
{ adName: "AdName 10"}
]; // Can be obtained from another source, such as your objJson variable
function prevPage()
{
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage()
{
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page)
{
var btn_next = document.getElementById("btn_next");
var btn_prev = document.getElementById("btn_prev");
var listing_table = document.getElementById("listingTable");
var page_span = document.getElementById("page");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
listing_table.innerHTML = "";
for (var i = (page-1) * records_per_page; i < (page * records_per_page); i++) {
listing_table.innerHTML += objJson[i].adName + "<br>";
}
page_span.innerHTML = page;
if (page == 1) {
btn_prev.style.visibility = "hidden";
} else {
btn_prev.style.visibility = "visible";
}
if (page == numPages()) {
btn_next.style.visibility = "hidden";
} else {
btn_next.style.visibility = "visible";
}
}
function numPages()
{
return Math.ceil(objJson.length / records_per_page);
}
window.onload = function() {
changePage(1);
};
UPDATE 2014/08/27
There is a bug above, where the for loop errors out when a particular page (the last page usually) does not contain records_per_page
number of records, as it tries to access a non-existent index.
The fix is simple enough, by adding an extra checking condition into the for loop to account for the size of objJson
:
Updated fiddle: http://jsfiddle.net/Lzp0dw83/1/
for (var i = (page-1) * records_per_page; i < (page * records_per_page) && i < objJson.length; i++)
Thought of writing this answer as nothing worked from above & you don't want to specify proxy location.
If you're using httpClient
then consider this.
HttpClientHandler handler = new HttpClientHandler();
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
handler.Proxy = proxy;
var client = new HttpClient(handler);
// your next steps...
And if you're using HttpWebRequest
:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + _endpoint);
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;
Kind referencce: https://medium.com/@siriphonnot/the-remote-server-returned-an-error-407-proxy-authentication-required-86ae489e401b
To supplement what everyone else has said above, your js file is being read on the client side when you have a path to it in your HTML file. At least that was the problem for me. I had it as a script in my tag in my index.html Hope this helps!
You can do it also in more 'object way' and still easy-to-read:
$('#content ul').append(
$('<li>').append(
$('<a>').attr('href','/user/messages').append(
$('<span>').attr('class', 'tab').append("Message center")
)));
You don't have to fight with quotes then, but must keep trace of braces :)
My best approach is:
var item = {...}
var items = [{id:2}, {id:2}, {id:2}];
items[items.findIndex(el => el.id === item.id)] = item;
Reference for findIndex
And in case you don't want to replace with new object, but instead to copy the fields of item
, you can use Object.assign
:
Object.assign(items[items.findIndex(el => el.id === item.id)], item)
as an alternative with .map()
:
Object.assign(items, items.map(el => el.id === item.id? item : el))
Don't modify the array, use a new one, so you don't generate side effects
const updatedItems = items.map(el => el.id === item.id ? item : el)
Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...
Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]
Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.
In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.
What is a Crash (technically)... in ASP.NET and what to do if it happens?
If you are using a DbContext, use the following constructor to set the command timeout:
public class MyContext : DbContext
{
public MyContext ()
{
var adapter = (IObjectContextAdapter)this;
var objectContext = adapter.ObjectContext;
objectContext.CommandTimeout = 1 * 60; // value in seconds
}
}
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
It basically occours when you return from a loop you can only return from function
I am assuming: If you sent the JSON value through browser then any number you sent that will be the type float64 so you cant get the value directly int in golang.
So do the conversion like:
//As that says:
fmt.Fprintf(w, "Type = %v", val) // <--- Type = float64
var iAreaId int = int(val.(float64))
This way you can get exact value what you wanted.
Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0
public class ThreadClass {
volatile int i = 1;
volatile boolean state=true;
synchronized public void printOddNumbers(){
try {
while (!state) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+i);
state = false;
i++;
notifyAll();
}
synchronized public void printEvenNumbers(){
try {
while (state) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+i);
state = true;
i++;
notifyAll();
}
}
Then call the above class like this
// I am ttying to print 10 values.
ThreadClass threadClass=new ThreadClass();
Thread t1=new Thread(){
int k=0;
@Override
public void run() {
while (k<5) {
threadClass.printOddNumbers();
k++;
}
}
};
t1.setName("Thread1");
Thread t2=new Thread(){
int j=0;
@Override
public void run() {
while (j<5) {
threadClass.printEvenNumbers();
j++;
}
}
};
t2.setName("Thread2");
t1.start();
t2.start();
out put:
System.out: Thread1 1
System.out: Thread2 2
System.out: Thread1 3
System.out: Thread2 4
System.out: Thread1 5
System.out: Thread2 6
System.out: Thread1 7
System.out: Thread2 8
System.out: Thread1 9
System.out: Thread2 10
This is most likely not an answer to the issue itself but this question pops up as first result when searching for Sql declare scalar variable
hence i share a possible solution to this error.
In my case this error was caused by the use of ;
after a SQL statement. Just remove it and the error will be gone.
I guess the cause is the same as @IronSean already posted in an comment above:
it's worth noting that using GO (or in this case ;) causes a new branch where declared variables aren't visible past the statement.
For example:
DECLARE @id int
SET @id = 78
SELECT * FROM MyTable WHERE Id = @var; <-- remove this character to avoid the error message
SELECT * FROM AnotherTable WHERE MyTableId = @var
Relative paths can be best understood if you know how Java runs the program.
There is a concept of working directory when running programs in Java. Assuming you have a class, say, FileHelper
that does the IO under
/User/home/Desktop/projectRoot/src/topLevelPackage/
.
Depending on the case where you invoke java
to run the program, you will have different working directory. If you run your program from within and IDE, it will most probably be projectRoot
.
In this case $ projectRoot/src : java topLevelPackage.FileHelper
it will be src
.
In this case $ projectRoot : java -cp src topLevelPackage.FileHelper
it will be projectRoot
.
In this case $ /User/home/Desktop : java -cp ./projectRoot/src topLevelPackage.FileHelper
it will be Desktop
.
(Assuming $ is your command prompt with standard Unix-like FileSystem. Similar correspondence/parallels with Windows system)
So, your relative path root (.)
resolves to your working directory. Thus to be better sure of where to write files, it's said to consider below approach.
package topLevelPackage
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileHelper {
// Not full implementation, just barebone stub for path
public void createLocalFile() {
// Explicitly get hold of working directory
String workingDir = System.getProperty("user.dir");
Path filePath = Paths.get(workingDir+File.separator+"sampleFile.txt");
// In case we need specific path, traverse that path, rather using . or ..
Path pathToProjectRoot = Paths.get(System.getProperty("user.home"), "Desktop", "projectRoot");
System.out.println(filePath);
System.out.println(pathToProjectRoot);
}
}
Hope this helps.
https://developer.mozilla.org/en/CSS/vertical-align
<table style="height: 275px; width: 188px">
<tr>
<td style="width: 259px; vertical-align:top">
main page
</td>
</tr>
</table>
?
There's not a way as of 11/2012, HOWEVER
Highlight Text (In visual Studio.net)
ctrl + k + c, ctrl + k + u
Will comment / uncomment, respectively
Try
expect(new ThrowableMessageMatcher(new StringContains(message)))
instead of
expectMessage(message)
You may write a custom ExpectedException
or utility method to wrap up the code.
Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio
# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
# Grab the image size and initialize dimensions
dim = None
(h, w) = image.shape[:2]
# Return original image if no need to resize
if width is None and height is None:
return image
# We are resizing height if width is none
if width is None:
# Calculate the ratio of the height and construct the dimensions
r = height / float(h)
dim = (int(w * r), height)
# We are resizing width if height is none
else:
# Calculate the ratio of the width and construct the dimensions
r = width / float(w)
dim = (width, int(h * r))
# Return the resized image
return cv2.resize(image, dim, interpolation=inter)
Usage
import cv2
image = cv2.imread('1.png')
cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
cv2.waitKey()
Using this example image
Simply downscale to width=100
(left) or upscale to width=300
(right)
Here lies your problem:
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text); // tv is null
}
--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.
The error message is very clear and even tells you at what method. From the documentation:
public final View findViewById (int id)
Look for a child view with the given id. If this view has the given id, return this view.
Parameters
id The id to search for.
Returns
The view that has the given id in the hierarchy or null
http://developer.android.com/reference/android/view/View.html#findViewById%28int%29
In other words: You have no view with the id you give as a parameter.
You want something like the cex=1.5
argument to scale fonts 150 percent. But do see help(par)
as there are also cex.lab
, cex.axis
, ...
you can also put labels inside plot:
plot(spline(sub$day, sub$counts), type ='l', labels = FALSE)
you'll get a warning. i think this is because labels is actually a parameter that's being passed down to a subroutine that plot runs (axes?). the warning will pop up because it wasn't directly a parameter of the plot function.
\w\-
is probably the best but here just another alternative
Use [:alnum:]
if(!preg_match("/[^[:alnum:]\-_]/",$str)) echo "valid";
Just install python newest version's installer it will automatically detect your python version and will say upgrade python and starts upgrading
I created a simple scheduler that is easy to use and you do not need to use external library. TaskScheduler is a singleton that keeps references on the timers so timers will not be garbage collected, it can schedule multiple tasks. You can set the first run (hour and minute), if at the time of scheduling this time is over scheduling start on the next day this at that time. But it is easy to customize the code.
Scheduling a new task is so simple. Example: At 11:52 the first task is for every 15 secunds, the second example is for every 5 secunds. For daily execution set 24 to the 3 parameter.
TaskScheduler.Instance.ScheduleTask(11, 52, 0.00417,
() =>
{
Debug.WriteLine("task1: " + DateTime.Now);
//here write the code that you want to schedule
});
TaskScheduler.Instance.ScheduleTask(11, 52, 0.00139,
() =>
{
Debug.WriteLine("task2: " + DateTime.Now);
//here write the code that you want to schedule
});
My debug window:
task2: 07.06.2017 11:52:00
task1: 07.06.2017 11:52:00
task2: 07.06.2017 11:52:05
task2: 07.06.2017 11:52:10
task1: 07.06.2017 11:52:15
task2: 07.06.2017 11:52:15
task2: 07.06.2017 11:52:20
task2: 07.06.2017 11:52:25
...
Just add this class to your project:
public class TaskScheduler
{
private static TaskScheduler _instance;
private List<Timer> timers = new List<Timer>();
private TaskScheduler() { }
public static TaskScheduler Instance => _instance ?? (_instance = new TaskScheduler());
public void ScheduleTask(int hour, int min, double intervalInHour, Action task)
{
DateTime now = DateTime.Now;
DateTime firstRun = new DateTime(now.Year, now.Month, now.Day, hour, min, 0, 0);
if (now > firstRun)
{
firstRun = firstRun.AddDays(1);
}
TimeSpan timeToGo = firstRun - now;
if (timeToGo <= TimeSpan.Zero)
{
timeToGo = TimeSpan.Zero;
}
var timer = new Timer(x =>
{
task.Invoke();
}, null, timeToGo, TimeSpan.FromHours(intervalInHour));
timers.Add(timer);
}
}
And this is if copying a single property to another list is needed:
targetList.AddRange(sourceList.Select(i => i.NeededProperty));
// Turn on output buffering
ob_start();
//Get the ipconfig details using system commond
system('ipconfig /all');
// Capture the output into a variable
$mycomsys=ob_get_contents();
// Clean (erase) the output buffer
ob_clean();
$find_mac = "Physical";
//find the "Physical" & Find the position of Physical text
$pmac = strpos($mycomsys, $find_mac);
// Get Physical Address
$macaddress=substr($mycomsys,($pmac+36),17);
//Display Mac Address
echo $macaddress;
This works for me on Windows, as ipconfig /all
is Windows system command.
For Windows:
Save the following as MSFT.vbs:
set SOAPClient = createobject("MSSOAP.SOAPClient")
SOAPClient.mssoapinit "https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc?wsdl"
WScript.Echo "MSFT = " & SOAPClient.GetQuote("MSFT")
Then from a command prompt, run:
C:\>MSFT.vbs
Reference: http://blogs.msdn.com/b/bgroth/archive/2004/10/21/246155.aspx