Are you changing the primary key value of a User object somewhere? You shouldn't do that. Check that your mapping for the primary key is correct.
What does your mapping XML file or mapping annotations look like?
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
How about:
DELETE guide_category
WHERE id_guide_category IN (
SELECT id_guide_category
FROM guide_category AS gc
LEFT JOIN guide AS g
ON g.id_guide = gc.id_guide
WHERE g.title IS NULL
)
If you have some problems with virtualenv,
You can use it:
sudo ln -sf python2 /usr/bin/python
and
sudo ln -sf python3 /usr/bin/python
This is how I do it...
public class ThreadA {
public ThreadA(object[] args) {
...
}
public void Run() {
while (true) {
Thread.sleep(1000); // wait 1 second for something to happen.
doStuff();
if(conditionToExitReceived) // what im waiting for...
break;
}
//perform cleanup if there is any...
}
}
Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)
private void FireThread(){
Thread thread = new Thread(new ThreadStart(this.startThread));
thread.start();
}
private void (startThread){
new ThreadA(args).Run();
}
The thread is created by calling "FireThread()"
The newly created thread will run until its condition to stop is met, then it dies...
You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...
Best to read through : This MSDN Article
Without JS, I am doing it like this:
My HTML:
<div class="container">
<div class="sometext">Some text here</div>
<div class="someothertext">Some other text here</div>
<a href="#" class="mylink">text of my link</a>
</div>
My CSS:
.container{
position: relative;
}
.container.a{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-indent: -9999px; //these two lines are to hide my actual link text.
overflow: hidden; //these two lines are to hide my actual link text.
}
Listen to the change event.
input.onchange = function(e) {
..
};
Flex layout modes are not (fully) natively supported in IE yet. IE10 implements the "tween" version of the spec which is not fully recent, but still works.
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
This CSS-Tricks article has some advice on cross-browser use of flexbox (including IE): http://css-tricks.com/using-flexbox/
edit: after a bit more research, IE10 flexbox layout mode implemented current to the March 2012 W3C draft spec: http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/
The most current draft is a year or so more recent: http://dev.w3.org/csswg/css-flexbox/
/bin/sh
is usually a link to the system's default shell, which is often bash
but on, e.g., Debian systems is the lighter weight dash
. Either way, the original Bourne shell is sh
, so if your script uses some bash
(2nd generation, "Bourne Again sh") specific features ([[ ]]
tests, arrays, various sugary things, etc.), then you should be more specific and use the later. This way, on systems where bash is not installed, your script won't run. I understand there may be an exciting trilogy of films about this evolution...but that could be hearsay.
Also note that when evoked as sh
, bash
to some extent behaves as POSIX standard sh
(see also the GNU docs about this).
var outImage ="imagenFondo";_x000D_
function preview_2(obj)_x000D_
{_x000D_
if (FileReader)_x000D_
{_x000D_
var reader = new FileReader();_x000D_
reader.readAsDataURL(obj.files[0]);_x000D_
reader.onload = function (e) {_x000D_
var image=new Image();_x000D_
image.src=e.target.result;_x000D_
image.onload = function () {_x000D_
document.getElementById(outImage).src=image.src;_x000D_
};_x000D_
}_x000D_
}_x000D_
else_x000D_
{_x000D_
// Not supported_x000D_
}_x000D_
}
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>preview photo</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<form>_x000D_
<input type="file" onChange="preview_2(this);"><br>_x000D_
<img id="imagenFondo" style="height: 300px;width: 300px;">_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
There is no problem with displaying HTML code in blade templates.
For test, you can add to routes.php only one route:
Route::get('/', function () {
$data = new stdClass();
$data->page_desc
= '<strong>aaa</strong><em>bbb</em>
<p>New paragaph</p><script>alert("Hello");</script>';
return View::make('hello')->with('content', $data);
}
);
and in hello.blade.php
file:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
{{ $content->page_desc }}
</body>
</html>
For the following code you will get output as on image
So probably page_desc
in your case is not what you expect. But as you see it can be potential dangerous if someone uses for example '` tag so you should probably in your route before assigning to blade template filter some tags
EDIT
I've also tested it with putting the same code into database:
Route::get('/', function () {
$data = User::where('id','=',1)->first();
return View::make('hello')->with('content', $data);
}
);
Output is exactly the same in this case
Edit2
I also don't know if Pages
is your model or it's a vendor model. For example it can have accessor inside:
public function getPageDescAttribute($value)
{
return htmlspecialchars($value);
}
and then when you get page_desc
attribute you will get modified page_desc
with htmlspecialchars
. So if you are sure that data in database is with raw html (not escaped) you should look at this Pages
class
Your for loop doesn't need to just add one. You can loop by three.
for(int i = 0; i < theData.Length; i+=3)
{
string value1 = theData[i];
string value2 = theData[i+1];
string value3 = theData[i+2];
}
Basically, you are just using indexes to grab the values in your array. One point to note here, I am not checking to see if you go past the end of your array. Make sure you are doing bounds checking!
There is a workaround.
That's it.
For me, I found the suggestion in the following thread helped:
It suggested running the following command in the Terminal application:
sudo /usr/sbin/DevToolsSecurity --enable
The criterium should be "?*"
and not "<>"
because the latter will also count formulas that contain empty results, like ""
So the simplest formula would be
=COUNTIF(Range,"?*")
Vim has a branch operator \&
that is useful when searching for a line containing a set of words, in any order. Moreover, extending the set of required words is trivial.
For example,
/.*jack\&.*james
will match a line containing jack
and james
, in any order.
See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.
It means that you have to have PHP installed as a module in Apache, instead of starting it as a CGI script.
Adding a link with the thumbnail, originally used by YouTube is a solution, that works. The thumbnail, used by YouTube is accessible the following way:
https://www.youtube.com/watch?v=5yLzZikS15k
https://img.youtube.com/vi/5yLzZikS15k/0.jpg
Following this logic, the code below produces flawless results:
<div align="left">
<a href="https://www.youtube.com/watch?v=5yLzZikS15k">
<img src="https://img.youtube.com/vi/5yLzZikS15k/0.jpg" style="width:100%;">
</a>
</div>
_x000D_
In the newer version of mongodb v2.6.4 try:
grep dbpath /etc/mongod.conf
It will give you something like this:
dbpath=/var/lib/mongodb
And that is where it stores the data.
Starting from Angular version 9:
Breaking changes:
Components can no longer be imported through "@angular/material". Use the individual secondary entry-points, such as @angular/material/button.
This means that:
import { MatInputModule, MatCardModule } from "@angular/material";
becomes:
import { MatInputModule } from "@angular/material/input";
import { MatCardModule } from "@angular/material/card";
This works for me:
var table = new DataTable();
table.Rows.Add();
You need to check put method in Hash map first as HashSet is backed up by HashMap
from chromedriver_py import binary_path
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--window-size=1280x1696')
chrome_options.add_argument('--user-data-dir=/tmp/user-data')
chrome_options.add_argument('--hide-scrollbars')
chrome_options.add_argument('--enable-logging')
chrome_options.add_argument('--log-level=0')
chrome_options.add_argument('--v=99')
chrome_options.add_argument('--single-process')
chrome_options.add_argument('--data-path=/tmp/data-path')
chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument('--homedir=/tmp')
chrome_options.add_argument('--disk-cache-dir=/tmp/cache-dir')
chrome_options.add_argument('user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36')
driver = webdriver.Chrome(executable_path = binary_path,options=chrome_options)
Start your XAMPP server by using:
{XAMPP}\xampp-control.exe
{XAMPP}\apache_start.bat
Then you have to use the URI http://localhost/index.html
because htdocs
is the document root of the Apache server.
If you're getting redirected to http://localhost/xampp/*
, then index.php
located in the htdocs
folder is the problem because index.php files have a higher priority than index.html files.
You could temporarily rename index.php.
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
ReDim Preserve arr (3)
arr(3)=newItem
for more info Redim
look at familiar main method which takes string array as param
and the convolution is defined through a multiplication in transform domain:
conv2(x,y) = fftshift(ifft2(fft2(x).*fft2(y)))
if one channel is considered... for more channels this has to be done every channel
You are missing a :selected
on the selector for show()
- see the jQuery documentation for an example of how to use this.
In your case it will probably look something like this:
$('#'+$('#colorselector option:selected').val()).show();
Sounds like autocomplete is being called before the library that defines it is actually loaded - if that makes sense?
If your script is inline, rather than referenced, move it to the bottom of the page. Or (my preferred option) place the script in an external .js file and then reference it:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="yourNewJSFile"></script>
Edit: if you externalise your script, ensure it is referenced AFTER any JQuery libraries it relies on :)
It depends on the GC your java is using. Parallel GCs might work better on larger memory settings - I'm no expert on that though.
In general, if you have larger memory the less frequent it needs to be GC-ed - there is lots of room for garbage. However, when it comes to a GC, the GC has to work on more memory - which in turn might be slower.
or //div[@id='id-74385'][@class='guest clearfix']
I'd bet you're asking this question because you've tried pg_ctl start
and received the following error:
pg_ctl: no database directory specified and environment variable PGDATA unset
In other words, you're looking for the directory to put after -D
in your pg_ctl start
command.
In this case, the directory you're looking for contains these files.
PG_VERSION pg_dynshmem pg_multixact
pg_snapshots pg_tblspc postgresql.conf
base pg_hba.conf pg_notify
pg_stat pg_twophase postmaster.opts
global pg_ident.conf pg_replslot
pg_stat_tmp pg_xlog postmaster.pid
pg_clog pg_logical pg_serial
pg_subtrans postgresql.auto.conf server.log
You can locate it by locating any of the files and directories above using the search provided with your OS.
For example in my case (a HomeBrew install on Mac OS X), these files are located in /usr/local/var/postgres
. To start the server I type:
pg_ctl -D /usr/local/var/postgres -w start
... and it works.
Simple HTML trick to get this :
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row" >_x000D_
_x000D_
<div class="col-md-6">_x000D_
<div class="row">_x000D_
<div class="col-md-4" >_x000D_
<label for="hours">Hours</label>_x000D_
<select class="form-control" required>_x000D_
<option> </option>_x000D_
<option value="1"> 1 </option>_x000D_
<option value="2"> 2 </option>_x000D_
<option value="3"> 3 </option>_x000D_
<option value="4"> 4 </option>_x000D_
<option value="5"> 5 </option>_x000D_
<option value="6"> 6 </option>_x000D_
<option value="7"> 7 </option>_x000D_
<option value="8"> 8 </option>_x000D_
<option value="9"> 9 </option>_x000D_
<option value="10"> 10 </option>_x000D_
<option value="11"> 11 </option>_x000D_
<option value="12"> 12 </option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="col-md-4" >_x000D_
<label for="minutes">Minutes</label>_x000D_
<select class="form-control" required="">_x000D_
<option selected disabled> </option>_x000D_
<option value="00"> 00 </option>_x000D_
<option value="10"> 10 </option>_x000D_
<option value="20"> 20 </option>_x000D_
<option value="30"> 30 </option>_x000D_
<option value="40"> 40 </option>_x000D_
<option value="50"> 50 </option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="col-md-4" >_x000D_
<label for="hours">Select Meridiem</label>_x000D_
<select class="form-control" required="" >_x000D_
<option selected="" value="AM"> AM </option>_x000D_
<option value="PM"> PM </option>_x000D_
</select>_x000D_
</div>_x000D_
</div></div>_x000D_
</div>
_x000D_
There's actually seven variants of this:
char description unicode html html entity utf-8 · Middle Dot U+00B7 · · C2 B7 · Greek Ano Teleia U+0387 · CE 87 • Bullet U+2022 • • E2 80 A2 ‧ Hyphenation Point U+2027 ₁ E2 80 A7 ∙ Bullet Operator U+2219 ∙ E2 88 99 ● Black Circle U+25CF ● E2 97 8F ⬤ Black Large Circle U+2B24 ⬤ E2 AC A4
Depending on your viewing application or font, the Bullet Operator may seem very similar to either the Middle Dot or the Bullet.
improving on user1697128 (because I cant yet comment on it)
<script>
function ConfirmDelete()
{
var x = confirm("Are you sure you want to delete?");
if (x)
return true;
else
return false;
}
</script>
<button Onclick="return ConfirmDelete();" type="submit" name="actiondelete" value="1"><img src="images/action_delete.png" alt="Delete"></button>
will cancel form submission if cancel is pressed
if you are using Carbon, you can use the defined spec "RFC3339_EXTENDED". or customize it.
Carbon::RFC3339_EXTENDED = 'Y-m-d\TH:i:s.vP';
Oddly. but in my experience TeamViewer is not faster/more responsive than VNC, only easier to setup. I have a couple of win-boxen that I VNC over OpenVPN into (so there is another overhead layer) and that's on cheap Cable (512 up) and I find properly setup TightVNC to be much more responsive than TeamViewer to same boxen. RDP (naturally) even more so since by large part it sends GUI draw commands instead of bitmap tiles.
Which brings us to:
Why are you not using VNC? There are plethora of open source solutions, and Tight is probably on top of it's game right now.
Advanced VNC implementations use lossy compression and that seems to achieve better results than your choice of PNG. Also, IIRC the rest of the payload is also squashed using zlib. Bothj Tight and UltraVNC have very optimized algos, especially for windows. On top of that Tight is open-source.
If win boxen are your primary target RDP may be a better option, and has an opensource implementation (rdesktop)
If *nix boxen are your primary target NX may be a better option and has an open source implementation (FreeNX, albeit not as optimised as NoMachine's proprietary product).
If compressing JPEG is a performance issue for your algo, I'm pretty sure that image comparison would still take away some performance. I'd bet they use best-case compression for every specific situation ie lossy for large frames, some quick and dirty internall losless for smaller ones, compare bits of images and send only diffs of sort and bunch of other optimisation tricks.
And a lot of those tricks must be present in Tight > 2.0 since again, in my experience it beats the hell out of TeamViewer performance wyse, YMMV.
Also the choice of a JIT compiled runtime over something like C++ might take a slice from your performance edge, especially in memory constrained machines (a lot of performance tuning goes to the toilet when windows start using the pagefile intensively). And you will need memory to keep previous image states for internal comparison atop of what DF mirage gives you.
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
This is working nicely.
UPDATE state SET name = CONCAT(UCASE(LEFT(name, 1)), LCASE(SUBSTRING(name, 2)));
As Jon said, for me this is the best solution and you dont need to set any text at runtime, only use this custom class HtmlTextView
public class HtmlTextView extends TextView {
public HtmlTextView(Context context) {
super(context);
}
public HtmlTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
@TargetApi(21)
public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void setText(CharSequence s,BufferType b){
super.setText(Html.fromHtml(s.toString()),b);
}
}
and thats it, now only put it in your XML
<com.fitc.views.HtmlTextView
android:id="@+id/html_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/example_html" />
with your Html String
<string name="example_html">
<![CDATA[
<b>Author:</b> Mr Donuthead<br/>
<b>Contact:</b> [email protected]<br/>
<i>Donuts for life </i>
]]>
Maybe you are out of inodes. Try df -i
2591792 136322 2455470 6% /home
/dev/sdb1 1887488 1887488 0 100% /data
Disk used 6% but inode table full.
The ThreadPoolExecutor
class is the base implementation for the executors that are returned from many of the Executors
factory methods. So let's approach Fixed and Cached thread pools from ThreadPoolExecutor
's perspective.
The main constructor of this class looks like this:
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
)
The corePoolSize
determines the minimum size of the target thread pool. The implementation would maintain a pool of that size even if there are no tasks to execute.
The maximumPoolSize
is the maximum number of threads that can be active at once.
After the thread pool grows and becomes bigger than the corePoolSize
threshold, the executor can terminate idle threads and reach to the corePoolSize
again.
If allowCoreThreadTimeOut
is true, then the executor can even terminate core pool threads if they were idle more than keepAliveTime
threshold.
So the bottom line is if threads remain idle more than keepAliveTime
threshold, they may get terminated since there is no demand for them.
What happens when a new task comes in and all core threads are occupied? The new tasks will be queued inside that BlockingQueue<Runnable>
instance. When a thread becomes free, one of those queued tasks can be processed.
There are different implementations of the BlockingQueue
interface in Java, so we can implement different queuing approaches like:
Bounded Queue: New tasks would be queued inside a bounded task queue.
Unbounded Queue: New tasks would be queued inside an unbounded task queue. So this queue can grow as much as the heap size allows.
Synchronous Handoff: We can also use the SynchronousQueue
to queue the new tasks. In that case, when queuing a new task, another thread must already be waiting for that task.
Here's how the ThreadPoolExecutor
executes a new task:
corePoolSize
threads are running, tries to start a
new thread with the given task as its first job.BlockingQueue#offer
method. The offer
method won't block if the queue is full and immediately returns false
.offer
returns false
), then it tries to add a new thread to the thread pool with this task as its first job.RejectedExecutionHandler
.The main difference between the fixed and cached thread pools boils down to these three factors:
+-----------+-----------+-------------------+---------------------------------+ | Pool Type | Core Size | Maximum Size | Queuing Strategy | +-----------+-----------+-------------------+---------------------------------+ | Fixed | n (fixed) | n (fixed) | Unbounded `LinkedBlockingQueue` | +-----------+-----------+-------------------+---------------------------------+ | Cached | 0 | Integer.MAX_VALUE | `SynchronousQueue` | +-----------+-----------+-------------------+---------------------------------+
Excutors.newFixedThreadPool(n)
works:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
As you can see:
OutOfMemoryError
.When should I use one or the other? Which strategy is better in terms of resource utilization?
A fixed-size thread pool seems to be a good candidate when we're going to limit the number of concurrent tasks for resource management purposes.
For example, if we're going to use an executor to handle web server requests, a fixed executor can handle the request bursts more reasonably.
For even better resource management, it's highly recommended to create a custom ThreadPoolExecutor
with a bounded BlockingQueue<T>
implementation coupled with reasonable RejectedExecutionHandler
.
Here's how the Executors.newCachedThreadPool()
works:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
As you can see:
Integer.MAX_VALUE
. Practically, the thread pool is unbounded.SynchronousQueue
always fails when there is no one on the other end to accept it! When should I use one or the other? Which strategy is better in terms of resource utilization?
Use it when you have a lot of predictable short-running tasks.
Perfectly described here https://www.smashingmagazine.com/2014/05/moving-git-repository-new-server/
First, we have to fetch all of the remote branches and tags from the existing repository to our local index:
git fetch origin
We can check for any missing branches that we need to create a local copy of:
git branch -a
Let’s use the SSH-cloned URL of our new repository to create a new remote in our existing local repository:
git remote add new-origin [email protected]:manakor/manascope.git
Now we are ready to push all local branches and tags to the new remote named new-origin:
git push --all new-origin
git push --tags new-origin
Let’s make new-origin the default remote:
git remote rm origin
Rename new-origin to just origin, so that it becomes the default remote:
git remote rename new-origin origin
This problem is vectorizable with SIMD for the ASCII character set.
Preliminary testing with x86-64 gcc 5.2 -O3 -march=native
on a Core2Duo (Merom). The same string of 120 characters (mixed lowercase and non-lowercase ASCII), converted in a loop 40M times (with no cross-file inlining, so the compiler can't optimize away or hoist any of it out of the loop). Same source and dest buffers, so no malloc overhead or memory/cache effects: data is hot in L1 cache the whole time, and we're purely CPU-bound.
boost::to_upper_copy<char*, std::string>()
: 198.0s. Yes, Boost 1.58 on Ubuntu 15.10 is really this slow. I profiled and single-stepped the asm in a debugger, and it's really, really bad: there's a dynamic_cast of a locale variable happening per character!!! (dynamic_cast takes multiple calls to strcmp). This happens with LANG=C
and with LANG=en_CA.UTF-8
.
I didn't test using a RangeT other than std::string. Maybe the other form of to_upper_copy
optimizes better, but I think it will always new
/malloc
space for the copy, so it's harder to test. Maybe something I did differs from a normal use-case, and maybe normally stopped g++ can hoist the locale setup stuff out of the per-character loop. My loop reading from a std::string
and writing to a char dstbuf[4096]
makes sense for testing.
loop calling glibc toupper
: 6.67s (not checking the int
result for potential multi-byte UTF-8, though. This matters for Turkish.)
cmov
, with the table hot in L1 anyway.See also this question about toupper()
being slow on Windows when a locale is set.
I was shocked that Boost is an order of magnitude slower than the other options. I double-checked that I had -O3
enabled, and even single-stepped the asm to see what it was doing. It's almost exactly the same speed with clang++ 3.8. It has huge overhead inside the per-character loop. The perf record
/ report
result (for the cycles
perf event) is:
32.87% flipcase-clang- libstdc++.so.6.0.21 [.] _ZNK10__cxxabiv121__vmi_class_type_info12__do_dyncastElNS_17__class_type_info10__sub_kindEPKS1_PKvS4_S6_RNS1_16
21.90% flipcase-clang- libstdc++.so.6.0.21 [.] __dynamic_cast
16.06% flipcase-clang- libc-2.21.so [.] __GI___strcmp_ssse3
8.16% flipcase-clang- libstdc++.so.6.0.21 [.] _ZSt9use_facetISt5ctypeIcEERKT_RKSt6locale
7.84% flipcase-clang- flipcase-clang-boost [.] _Z16strtoupper_boostPcRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
2.20% flipcase-clang- libstdc++.so.6.0.21 [.] strcmp@plt
2.15% flipcase-clang- libstdc++.so.6.0.21 [.] __dynamic_cast@plt
2.14% flipcase-clang- libstdc++.so.6.0.21 [.] _ZNKSt6locale2id5_M_idEv
2.11% flipcase-clang- libstdc++.so.6.0.21 [.] _ZNKSt6locale2id5_M_idEv@plt
2.08% flipcase-clang- libstdc++.so.6.0.21 [.] _ZNKSt5ctypeIcE10do_toupperEc
2.03% flipcase-clang- flipcase-clang-boost [.] _ZSt9use_facetISt5ctypeIcEERKT_RKSt6locale@plt
0.08% ...
Gcc and clang will only auto-vectorize loops when the iteration count is known ahead of the loop. (i.e. search loops like plain-C implementation of strlen
won't autovectorize.)
Thus, for strings small enough to fit in cache, we get a significant speedup for strings ~128 chars long from doing strlen
first. This won't be necessary for explicit-length strings (like C++ std::string
).
// char, not int, is essential: otherwise gcc unpacks to vectors of int! Huge slowdown.
char ascii_toupper_char(char c) {
return ('a' <= c && c <= 'z') ? c^0x20 : c; // ^ autovectorizes to PXOR: runs on more ports than paddb
}
// gcc can only auto-vectorize loops when the number of iterations is known before the first iteration. strlen gives us that
size_t strtoupper_autovec(char *dst, const char *src) {
size_t len = strlen(src);
for (size_t i=0 ; i<len ; ++i) {
dst[i] = ascii_toupper_char(src[i]); // gcc does the vector range check with psubusb / pcmpeqb instead of pcmpgtb
}
return len;
}
Any decent libc will have an efficient strlen
that's much faster than looping a byte at a time, so separate vectorized strlen and toupper loops are faster.
Baseline: a loop that checks for a terminating 0 on the fly.
Times for 40M iterations, on a Core2 (Merom) 2.4GHz. gcc 5.2 -O3 -march=native
. (Ubuntu 15.10). dst != src
(so we make a copy), but they don't overlap (and aren't nearby). Both are aligned.
Some results are a bit different with clang.
The microbenchmark loop that calls the function is in a separate file. Otherwise it inlines and strlen()
gets hoisted out of the loop, and it runs dramatically faster, esp. for 16 char strings (0.187s).
This has the major advantage that gcc can auto-vectorize it for any architecture, but the major disadvantage that it's slower for the usually-common case of small strings.
So there are big speedups, but compiler auto-vectorization doesn't make great code, esp. for cleanup of the last up-to-15 characters.
Based on my case-flip function that inverts the case of every alphabetic character. It takes advantage of the "unsigned compare trick", where you can do low < a && a <= high
with a single unsigned comparison by range shifting, so that any value less than low
wraps to a value that's greater than high
. (This works if low
and high
aren't too far apart.)
SSE only has a signed compare-greater, but we can still use the "unsigned compare" trick by range-shifting to the bottom of the signed range: Subtract 'a'+128, so the alphabetic characters range from -128 to -128+25 (-128+'z'-'a')
Note that adding 128 and subtracting 128 are the same thing for 8bit integers. There's nowhere for the carry to go, so it's just xor (carryless add), flipping the high bit.
#include <immintrin.h>
__m128i upcase_si128(__m128i src) {
// The above 2 paragraphs were comments here
__m128i rangeshift = _mm_sub_epi8(src, _mm_set1_epi8('a'+128));
__m128i nomodify = _mm_cmpgt_epi8(rangeshift, _mm_set1_epi8(-128 + 25)); // 0:lower case -1:anything else (upper case or non-alphabetic). 25 = 'z' - 'a'
__m128i flip = _mm_andnot_si128(nomodify, _mm_set1_epi8(0x20)); // 0x20:lcase 0:non-lcase
// just mask the XOR-mask so elements are XORed with 0 instead of 0x20
return _mm_xor_si128(src, flip);
// it's easier to xor with 0x20 or 0 than to AND with ~0x20 or 0xFF
}
Given this function that works for one vector, we can call it in a loop to process a whole string. Since we're already targeting SSE2, we can do a vectorized end-of-string check at the same time.
We can also do much better for the "cleanup" of the last up-to-15 bytes left over after doing vectors of 16B: upper-casing is idempotent, so re-processing some input bytes is fine. We do an unaligned load of the last 16B of the source, and store it into the dest buffer overlapping the last 16B store from the loop.
The only time this doesn't work is when the whole string is under 16B: Even when dst=src
, non-atomic read-modify-write is not the same thing as not touching some bytes at all, and can break multithreaded code.
We have a scalar loop for that, and also to get src
aligned. Since we don't know where the terminating 0 will be, an unaligned load from src
might cross into the next page and segfault. If we need any bytes in an aligned 16B chunk, it's always safe to load the whole aligned 16B chunk.
Full source: in a github gist.
// FIXME: doesn't always copy the terminating 0.
// microbenchmarks are for this version of the code (with _mm_store in the loop, instead of storeu, for Merom).
size_t strtoupper_sse2(char *dst, const char *src_begin) {
const char *src = src_begin;
// scalar until the src pointer is aligned
while ( (0xf & (uintptr_t)src) && *src ) {
*(dst++) = ascii_toupper(*(src++));
}
if (!*src)
return src - src_begin;
// current position (p) is now 16B-aligned, and we're not at the end
int zero_positions;
do {
__m128i sv = _mm_load_si128( (const __m128i*)src );
// TODO: SSE4.2 PCMPISTRI or PCMPISTRM version to combine the lower-case and '\0' detection?
__m128i nullcheck = _mm_cmpeq_epi8(_mm_setzero_si128(), sv);
zero_positions = _mm_movemask_epi8(nullcheck);
// TODO: unroll so the null-byte check takes less overhead
if (zero_positions)
break;
__m128i upcased = upcase_si128(sv); // doing this before the loop break lets gcc realize that the constants are still in registers for the unaligned cleanup version. But it leads to more wasted insns in the early-out case
_mm_storeu_si128((__m128i*)dst, upcased);
//_mm_store_si128((__m128i*)dst, upcased); // for testing on CPUs where storeu is slow
src += 16;
dst += 16;
} while(1);
// handle the last few bytes. Options: scalar loop, masked store, or unaligned 16B.
// rewriting some bytes beyond the end of the string would be easy,
// but doing a non-atomic read-modify-write outside of the string is not safe.
// Upcasing is idempotent, so unaligned potentially-overlapping is a good option.
unsigned int cleanup_bytes = ffs(zero_positions) - 1; // excluding the trailing null
const char* last_byte = src + cleanup_bytes; // points at the terminating '\0'
// FIXME: copy the terminating 0 when we end at an aligned vector boundary
// optionally special-case cleanup_bytes == 15: final aligned vector can be used.
if (cleanup_bytes > 0) {
if (last_byte - src_begin >= 16) {
// if src==dest, this load overlaps with the last store: store-forwarding stall. Hopefully OOO execution hides it
__m128i sv = _mm_loadu_si128( (const __m128i*)(last_byte-15) ); // includes the \0
_mm_storeu_si128((__m128i*)(dst + cleanup_bytes - 15), upcase_si128(sv));
} else {
// whole string less than 16B
// if this is common, try 64b or even 32b cleanup with movq / movd and upcase_si128
#if 1
for (unsigned int i = 0 ; i <= cleanup_bytes ; ++i) {
dst[i] = ascii_toupper(src[i]);
}
#else
// gcc stupidly auto-vectorizes this, resulting in huge code bloat, but no measurable slowdown because it never runs
for (int i = cleanup_bytes - 1 ; i >= 0 ; --i) {
dst[i] = ascii_toupper(src[i]);
}
#endif
}
}
return last_byte - src_begin;
}
Times for 40M iterations, on a Core2 (Merom) 2.4GHz. gcc 5.2 -O3 -march=native
. (Ubuntu 15.10). dst != src
(so we make a copy), but they don't overlap (and aren't nearby). Both are aligned.
(Actually timed with _mm_store
in the loop, not _mm_storeu
, because storeu is slower on Merom even when the address is aligned. It's fine on Nehalem and later. I've also left the code as-is for now, instead of fixing the failure to copy the terminating 0 in some cases, because I don't want to re-time everything.)
So for short strings longer than 16B, this is dramatically faster than auto-vectorized. Lengths one-less-than-a-vector-width don't present a problem. They might be a problem when operating in-place, because of a store-forwarding stall. (But note that it's still fine to process our own output, rather than the original input, because toupper is idempotent).
There's a lot of scope for tuning this for different use-cases, depending on what the surrounding code wants, and the target microarchitecture. Getting the compiler to emit nice code for the cleanup portion is tricky. Using ffs(3)
(which compiles to bsf or tzcnt on x86) seems to be good, but obviously that bit needs a re-think since I noticed a bug after writing up most of this answer (see the FIXME comments).
Vector speedups for even smaller strings can be obtained with movq
or movd
loads/stores. Customize as necessary for your use-case.
We can detect when our vector has any bytes with the high bit set, and in that case fall back to a scalar utf-8-aware loop for that vector. The dst
point can advance by a different amount than the src
pointer, but once we get back to an aligned src
pointer, we'll still just do unaligned vector stores to dst
.
For text that's UTF-8, but mostly consists of the ASCII subset of UTF-8, this can be good: high performance in the common case with correct behaviour in all cases. When there's a lot of non-ASCII, it will probably be worse than staying in the scalar UTF-8 aware loop all the time, though.
Making English faster at the expense of other languages is not a future-proof decision if the downside is significant.
In the Turkish locale (tr_TR
), the correct result from toupper('i')
is 'I'
(U0130), not 'I'
(plain ASCII). See Martin Bonner's comments on a question about tolower()
being slow on Windows.
We can also check for an exception-list and fallback to scalar there, like for multi-byte UTF8 input characters.
With this much complexity, SSE4.2 PCMPISTRM
or something might be able to do a lot of our checks in one go.
To get e.g the value from column 'test' and row 1 it works like
df[['test']].values[0][0]
as only df[['test']].values[0]
gives back a array
Exec time for the 3 answers :
Remove the first letter by replacing the case
$str = "hello";
$str[0] = "";
// $str[0] = false;
// $str[0] = null;
// replaced by ?, but ok for echo
Exec time for 1.000.000 tests : 0.39602184295654
sec
Remove the first letter with substr()
$str = "hello";
$str = substr($str, 1);
Exec time for 1.000.000 tests : 5.153294801712
sec
Remove the first letter with ltrim()
$str = "hello";
$str= ltrim ($str,'h');
Exec time for 1.000.000 tests : 5.2393000125885
sec
Remove the first letter with preg_replace()
$str = "hello";
$str = preg_replace('/^./', '', $str);
Exec time for 1.000.000 tests : 6.8543920516968
sec
Getting the correct line (example for line no. 6) is done with head and tail and the correct word (word no. 4) can be captured with awk:
command|head -n 6|tail -n 1|awk '{print $4}'
Use GNU parted
and print free
command:
root@sandbox:~# parted
GNU Parted 2.3
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print free
Model: VMware Virtual disk (scsi)
Disk /dev/sda: 64.4GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
32.3kB 1049kB 1016kB Free Space
1 1049kB 256MB 255MB primary ext2 boot
256MB 257MB 1048kB Free Space
2 257MB 64.4GB 64.2GB extended
5 257MB 64.4GB 64.2GB logical lvm
64.4GB 64.4GB 1049kB Free Space
You can add your own css property for button size as follows:
.btn {
min-width: 250px;
}
This question is a bit old, but here's another way in C++11 of "doing more work" in the constructor before initialising your member variables:
BigMommaClass::BigMommaClass(int numba1, int numba2)
: thingOne([](int n1, int n2){return n1+n2;}(numba1,numba2)),
thingTwo(numba1, numba2) {}
The lambda function above will be invoked and the result passed to thingOnes constructor. You can of course make the lambda as complex as you like.
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
It seems to have to do with context wrapping. Most classes derived from Context
are actually a ContextWrapper
, which essentially delegates to another context, possibly with changes by the wrapper.
The context is a general abstraction that supports mocking and proxying. Since many contexts are bound to a limited-lifetime object such as an Activity
, there needs to be a way to get a longer-lived context, for purposes such as registering for future notifications. That is achieved by Context.getApplicationContext()
. A logical implementation is to return the global Application
object, but nothing prevents a context implementation from returning a wrapper or proxy with a suitable lifetime instead.
Activities and services are more specifically associated with an Application
object. The usefulness of this, I believe, is that you can create and register in the manifest a custom class derived from Application
and be certain that Activity.getApplication()
or Service.getApplication()
will return that specific object of that specific type, which you can cast to your derived Application
class and use for whatever custom purpose.
In other words, getApplication()
is guaranteed to return an Application
object, while getApplicationContext()
is free to return a proxy instead.
You might want to use Scanner to parse through and find the specific sections you want to modify. There's also Split and StringTokenizer that may work, but at the level you're working at Scanner might be what's needed.
Here's some additional info on what the difference is between them: Scanner vs. StringTokenizer vs. String.Split
Also I use Tomcat GUI app (in my case: C:\tomcat\bin\Tomcat9w.bin).
Go to Java tab:
Set your Java properties, for example:
Java virtual machine
C:\Program Files\Java\jre-10.0.2\bin\server\jvm.dll
Java virtual machine
C:\tomcat\bin\bootstrap.jar;C:\tomcat\bin\tomcat-juli.jar
Java Options:
-Dcatalina.home=C:\tomcat
-Dcatalina.base=C:\tomcat
-Djava.io.tmpdir=C:\tomcat\temp
-Djava.util.logging.config.file=C:\tomcat\conf\logging.properties
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000
Java 9 options:
--add-opens=java.base/java.lang=ALL-UNNAMED
--add-opens=java.base/java.io=ALL-UNNAMED
--add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
I wrote a similar answer to a similar question on Stack Overflow, but here is part of that answer.
The new version of Android Studio (2.1) has support for Java 8 features. Here is an extract from the Android Developers blogspot post:
... Android Studio 2.1 release includes support for the new Jack compiler and support for Java 8.
...
To use Java 8 language features when developing with the N Developer Preview, you need to use the Jack compiler. The New Project Wizard [File? New? Project] generates the correct configurations for projects targeting the N.
Android does not support Java 1.8 yet (it only supports up to 1.7), so you cannot use Java 8 features like lambdas.
This answer gives more detail on Android Studio's compatibility; it states:
If you want to use lambdas, one of the major features of Java 8 in Android, you can use gradle-retrolamba
If you want to know more about using gradle-retrolambda
, this answer gives a lot of detail on doing that.
Just in case anyone is suffering from this predicament and happens to make the same asanine mistake that I did, here is what it was in my case. After banging my head against the wall for an hour, I realized that I had my json incorrectly nested, and the key "dependencies" was inside of the key "repository".
Needless to say, no errors were evident, and no modules were installed.
In httpd.conf
on /Applications/MAMP/conf/apache
, find:
<Directory />
Options Indexes FollowSymLinks
AllowOverride None
</Directory>
Replace None
with All
.
Restart MAMP servers.
You need the following functions to do this in PHP:
strpos
Find the position of the first occurrence of a substring in a string
strrpos
Find the position of the last occurrence of a substring in a string
substr
Return part of a string
Here's the signature of the substr
function:
string substr ( string $string , int $start [, int $length ] )
The signature of the substring
function (Java) looks a bit different:
string substring( int beginIndex, int endIndex )
substring
(Java) expects the end-index as the last parameter, but substr
(PHP) expects a length.
It's not hard, to get the desired length by the end-index in PHP:
$sub = substr($str, $start, $end - $start);
Here is the working code
$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
$pt_password = substr($message, $start);
}
else {
$end = strrpos($message, '-');
$pt_password = substr($message, $start, $end - $start);
}
My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.
{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)
#data wrangling
library(dplyr)
#text processing
library(stringi)
You can animate the scrolltop of the page with jQuery.
$('html, body').animate({
scrollTop: $(".middle").offset().top
}, 2000);
See this site: http://papermashup.com/jquery-page-scrolling/
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
This function normalizes down all whitespace, including line breaks, to single spaces. Not exactly what the original question asked for, but likely to do exactly what is needed in many cases:
import org.apache.commons.lang3.StringUtils;
final String cleansedString = StringUtils.normalizeSpace(rawString);
Just do what the message is asking for, create the user pma@localhost in the phpMyAdmin panel with no password
Couldn't you use the server variables to do this?
Or would this work?:
unset($_GET['page']);
$url = $_SERVER['SCRIPT_NAME'] ."?".http_build_query($_GET);
Just a thought.
My G drive stopped being shared with Docker after a recent Windows 10 update. I was getting the same problem saying it was blocked by the Windows firewall when attempting to reshare it.
Then I had tried to solve this issues by couple of suggestion but i cant resolve that issue after that I have tried to Reset credentials below of Shared Drives and my issue was solved.
So If you want then you can try to do this-
The reason for this is that you are trying to use an IntentService. Here is the line from the API Docs
The IntentService does the following:
Stops the service after all start requests have been handled, so you never have to call stopSelf().
Thus if you want your service to run indefinitely i suggest you extend the Service class instead. However this does not guarantee your service will run indefinitely. Your service will still have a chance of being killed by the kernel in a state of low memory if it is low priority.So you have two options:
1)Keep it running in the foreground by calling the startForeground()
method.
2)Restart the service if it gets killed.
Here is a part of the example from the docs where they talk about restarting the service after it is killed
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
At the first site is a dropdown field to select the language of phpmyadmin.
In the config.inc.php you can set:
$cfg['Lang'] = '';
More details you can find in the documentation: http://www.phpmyadmin.net/documentation/
Your Data
DECLARE @OrderDetails TABLE
(ProductID INT,ProductName VARCHAR(10), OrderQuantity INT)
INSERT INTO @OrderDetails VALUES
(1001,'abc',5),(1002,'abc',23),(2002,'xyz',8),
(3004,'ytp',15),(4001,'aze',19),(1001,'abc',7)
Query
Select ProductID, ProductName, Sum(OrderQuantity) AS Total
from @OrderDetails
Group By ProductID, ProductName ORDER BY ProductID
Result
+---------------------------------+
¦ ProductID ¦ ProductName ¦ Total ¦
¦-----------+-------------+-------¦
¦ 1001 ¦ abc ¦ 12 ¦
¦ 1002 ¦ abc ¦ 23 ¦
¦ 2002 ¦ xyz ¦ 8 ¦
¦ 3004 ¦ ytp ¦ 15 ¦
¦ 4001 ¦ aze ¦ 19 ¦
+---------------------------------+
<script type="text/javascript">_x000D_
function get_param(param) {_x000D_
var search = window.location.search.substring(1);_x000D_
var compareKeyValuePair = function(pair) {_x000D_
var key_value = pair.split('=');_x000D_
var decodedKey = decodeURIComponent(key_value[0]);_x000D_
var decodedValue = decodeURIComponent(key_value[1]);_x000D_
if(decodedKey == param) return decodedValue;_x000D_
return null;_x000D_
};_x000D_
_x000D_
var comparisonResult = null;_x000D_
_x000D_
if(search.indexOf('&') > -1) {_x000D_
var params = search.split('&');_x000D_
for(var i = 0; i < params.length; i++) {_x000D_
comparisonResult = compareKeyValuePair(params[i]); _x000D_
if(comparisonResult !== null) {_x000D_
break;_x000D_
}_x000D_
}_x000D_
} else {_x000D_
comparisonResult = compareKeyValuePair(search);_x000D_
}_x000D_
_x000D_
return comparisonResult;_x000D_
}_x000D_
_x000D_
var parcelNumber = get_param('parcelNumber'); //abc_x000D_
var registryId = get_param('registryId'); //abc_x000D_
var registrySectionId = get_param('registrySectionId'); //abc_x000D_
var apartmentNumber = get_param('apartmentNumber'); //abc_x000D_
_x000D_
_x000D_
</script>
_x000D_
then in the page i call the values like so:
<td class="tinfodd"> <script type="text/javascript">_x000D_
document.write(registrySectionId)_x000D_
</script></td>
_x000D_
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
Using iTextSharp.dll
protected void Page_Load(object sender, EventArgs e)
{
String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
if (System.IO.File.Exists(destinationFile))
System.IO.File.Delete(destinationFile);
string[] sSrcFile;
sSrcFile = new string[2];
string[] arr = new string[2];
for (int i = 0; i <= sourceFiles.Length - 1; i++)
{
if (sourceFiles[i] != null)
{
if (sourceFiles[i].Trim() != "")
arr[i] = sourceFiles[i].ToString();
}
}
if (arr != null)
{
sSrcFile = new string[2];
for (int ic = 0; ic <= arr.Length - 1; ic++)
{
sSrcFile[ic] = arr[ic].ToString();
}
}
try
{
int f = 0;
PdfReader reader = new PdfReader(sSrcFile[f]);
int n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
while (f < sSrcFile.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(PageSize.A4);
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
Response.Write("\n Processed page " + i);
}
f++;
if (f < sSrcFile.Length)
{
reader = new PdfReader(sSrcFile[f]);
n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
}
}
Response.Write("Success");
document.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
}
Declare @phoneNumber int
select @phoneNumber=Isnull('08041159620',0);
Give error :
The conversion of the varchar value '8041159620' overflowed an int column.: select cast('8041159620' as int)
AS
Integer is defined as :
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.
Solution
Declare @phoneNumber bigint
None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.
/**
* Prevent automatic scrolling of page to anchor by browser after loading of page.
* Do not call this function in $(...) or $(window).on('load', ...),
* it should be called earlier, as soon as possible.
*/
function preventAnchorScroll() {
var scrollToTop = function () {
$(window).scrollTop(0);
};
if (window.location.hash) {
// handler is executed at most once
$(window).one('scroll', scrollToTop);
}
// make sure to release scroll 1 second after document readiness
// to avoid negative UX
$(function () {
setTimeout(
function () {
$(window).off('scroll', scrollToTop);
},
1000
);
});
}
awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'
An update to @jrgns (with some slight syntax differences) solution.
$result = mysql_query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
You can also do it from the storyboard. Click the table view cell and in the attributes inspector under Table View Cell, change the drop down next to Selection to None.
This is to do with JavaScript's +
in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the +
unary operator, or use parseInt()
:
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary +
operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt()
is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt()
to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat()
if you need to convert decimals in strings to their numeric value - +
can do that too but it behaves slightly differently: that's another story though.
You can download the 32bit or 64bit version of "Express With Tools" or "SQL Server Management Studio Express" (SSMSE tools only) from:
This link is for SQL Server 2012 Express Service Pack 1 released 11/09/2012 (11.0.3000.00) The original RTM release was 11.0.2100.60 from March or May of 2012.
What we do, is to create two tables for each multilingual object.
E.g. the first table contains only language-neutral data (primary key, etc.) and the second table contains one record per language, containing the localized data plus the ISO code of the language.
In some cases we add a DefaultLanguage field, so that we can fall-back to that language if no localized data is available for a specified language.
Example:
Table "Product":
----------------
ID : int
<any other language-neutral fields>
Table "ProductTranslations"
---------------------------
ID : int (foreign key referencing the Product)
Language : varchar (e.g. "en-US", "de-CH")
IsDefault : bit
ProductDescription : nvarchar
<any other localized data>
With this approach, you can handle as many languages as needed (without having to add additional fields for each new language).
Update (2014-12-14): please have a look at this answer, for some additional information about the implementation used to load multilingual data into an application.
Use as.integer
:
set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819
as.integer(x)
[1] 26 37 57 90 20
Test for class:
xx <- as.integer(x)
str(xx)
int [1:5] 26 37 57 90 20
Use microtime(true)
in PHP 5, or the following modification in PHP 4:
array_sum(explode(' ', microtime()));
A portable way to write that code would be:
function getMicrotime()
{
if (version_compare(PHP_VERSION, '5.0.0', '<'))
{
return array_sum(explode(' ', microtime()));
}
return microtime(true);
}
^([A-Z][a-z]+)+$
This looks for sequences of an uppercase letter followed by one or more lowercase letters. Consecutive uppercase letters will not match, as only one is allowed at a time, and it must be followed by a lowercase one.
Hi the answer that @anu posted is right, but it wont completely work as required. By making a slight change to child_open() function it works properly.
<html>
<head>
<script type="text/javascript">
var popupWindow=null;
function child_open()
{
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
else
popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
</script>
</head>
<body onFocus="parent_disable();" onclick="parent_disable();">
<a href="javascript:child_open()">Click me</a>
</body>
</html>
I know this question is a little old but the following worked for me in a Jupyter Notebook running pandas 0.22.0 and Python 3:
import pandas as pd
pd.set_option('display.max_columns', <number of columns>)
You can do the same for the rows too:
pd.set_option('display.max_rows', <number of rows>)
This saves importing IPython, and there are more options in the pandas.set_option documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.set_option.html
Best approach is to undo the merge and perform the merge again. Often you get the order of things messed up. Try and fix the conflicts and get yourself into a mess.
So undo do it and merge again.
Make sure that you have the appropriate diff tools setup for your environment. I am on a mac and use DIFFMERGE. I think DIFFMERGE is available for all environments. Instructions are here: Install DIFF Merge on a MAC
I have this helpful resolving my conflicts: Git Basic-Merge-Conflicts
Change *.cs to .cs in the excludefileslist.txt
First of all, don't try the following command as suggested by Germain above.
`sudo apt-get remove 'python3.*'`
In Ubuntu, many software depends upon Python3 so if you will execute this command it will remove all of them as it happened with me. I found following answer useful to recover it.
If you want to use different python versions for different projects then create virtual environments it will be very useful. refer to the following link to create virtual environments.
Creating Virtual Environment also helps in using Tensorflow and Keras in Jupyter Notebook.
https://linoxide.com/linux-how-to/setup-python-virtual-environment-ubuntu/
Add following in onCreate
method:
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
CORRELATED SUBQUERIES: Is evaluated for each row processed by the Main query. Execute the Inner query based on the value fetched by the Outer query. Continues till all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query
Ex:
SELECT empno,fname,sal,deptid FROM emp e WHERE sal=(SELECT AVG(sal) FROM emp WHERE deptid=e.deptid)
The Correlated subquery specifically computes the AVG(sal)
for each department.
SUBQUERY: Runs first,executed once,returns values to be used by the MAIN Query. The OUTER Query is driven by the INNER QUERY
If u r using eclipse then delete tomcat server and Server folder then reconfigure those two..
CREATE TABLE t (d1 timestamp, d2 timestamp);
INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 05:00:00');
INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-11 00:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-04-01 13:00:00');
SELECT d2, d1, DATEDIFF(d2, d1) AS diff FROM t;
+---------------------+---------------------+------+
| d2 | d1 | diff |
+---------------------+---------------------+------+
| 2010-03-30 05:00:00 | 2010-03-11 12:00:00 | 19 |
| 2010-03-30 13:00:00 | 2010-03-11 12:00:00 | 19 |
| 2010-03-30 13:00:00 | 2010-03-11 00:00:00 | 19 |
| 2010-03-30 13:00:00 | 2010-03-10 12:00:00 | 20 |
| 2010-04-01 13:00:00 | 2010-03-10 12:00:00 | 22 |
+---------------------+---------------------+------+
5 rows in set (0.00 sec)
I faced the same problem while installing Eclipse for c/c++ applications .I downloaded Mingw GCC ,put its bin folder in your path ,used it in toolchains while making new C++ project in Eclipse and build which solved my problem. Referred to this video
Java 8: Base64 available:
MessageDigest md = MessageDigest.getInstance( "SHA-512" );
md.update( inbytes );
byte[] aMessageDigest = md.digest();
String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
return( outEncoded );
!=
, despite being non-ANSI, is more in the true spirit of SQL as a readable language. It screams not equal.
<>
says it's to me (less than, greater than) which is just weird. I know the intention is that it's either less than or greater than hence not equal, but that's a really complicated way of saying something really simple.
I've just had to take some long SQL queries and place them lovingly into an XML file for a whole bunch of stupid reasons I won't go into.
Suffice to say XML is not down with <>
at all and I had to change them to !=
and check myself before I riggedy wrecked myself.
GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).
This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.
Only three lines of relevant code.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with
curl
or other clients) then a possible cause could be that the endpoint expects aUser-Agent
header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g.System.setProperty("http.agent", "Netscape 1.0");
.
Generally speaking, you can update your index mapping using the put mapping api (reference here) :
curl -XPUT 'http://localhost:9200/advert_index/_mapping/advert_type' -d '
{
"advert_type" : {
"properties" : {
//your new mapping properties
}
}
}
'
It's especially useful for adding new fields. However, in your case, you will try to change the location type, which will cause a conflict and prevent the new mapping from being used.
You could use the put mapping api to add another property containing the location as a lat/lon array, but you won't be able to update the previous location field itself.
Finally, you will have to reindex your data for your new mapping to be taken into account.
The best solution would really be to create a new index.
If your problem with creating another index is downtime, you should take a look at aliases to make things go smoothly.
Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:
Option Explicit
Dim StdIn: Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
Main()
Sub Main()
Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false
Do until objInputFile.AtEndOfStream
tmpStr = objInputFile.ReadLine
If foundStrMatch(tmpStr)=true Then
If foundFirstMatch = false Then
index = getIndex(tmpStr)
foundFirstMatch = true
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
If index = getIndex(tmpStr) Then
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
ElseIf index < getIndex(tmpStr) Then
index = getIndex(tmpStr)
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
Else
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub
Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function
Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
getIndex = CInt(char1 & char2)
Else
getIndex = CInt(char1)
End If
End Function
Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
foundStrMatch = true
Else
foundStrMatch = false
End If
End Function
This is the original txt file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
And this is the result I'm expecting
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.
If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.
AutoService
class AutoService extends IntentService {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
public onCreate() {
timer = new Timer();
timer = new TimerTask() {
public void run()
{
System.out.println("done");
}
}
}
protected void onHandleIntent(Intent i) {
Log.d(TAG, "onHandleIntent");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer.scheduleAtFixedRate(timerTask, delay, period);
}
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
A programmatically solution will be:
TextView textView = new TextView(context);
textView.setId(android.R.id.empty);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setText("No result found");
listView.setEmptyView(textView);
Instead of getopt()
, you may also consider using argp_parse()
(an alternative interface to the same library).
From libc manual:
getopt
is more standard (the short-option only version of it is a part of the POSIX standard), but usingargp_parse
is often easier, both for very simple and very complex option structures, because it does more of the dirty work for you.
But I was always happy with the standard getopt
.
N.B. GNU getopt
with getopt_long
is GNU LGPL.
Handlebars can use an array as the context. You can use .
as the root of the data. So you can loop through your array data with {{#each .}}
.
var data = [_x000D_
{_x000D_
Category: "General",_x000D_
DocumentList: [_x000D_
{_x000D_
DocumentName: "Document Name 1 - General",_x000D_
DocumentLocation: "Document Location 1 - General"_x000D_
},_x000D_
{_x000D_
DocumentName: "Document Name 2 - General",_x000D_
DocumentLocation: "Document Location 2 - General"_x000D_
}_x000D_
]_x000D_
},_x000D_
{_x000D_
Category: "Unit Documents",_x000D_
DocumentList: [_x000D_
{_x000D_
DocumentName: "Document Name 1 - Unit Documents",_x000D_
DocumentList: "Document Location 1 - Unit Documents"_x000D_
}_x000D_
]_x000D_
},_x000D_
{_x000D_
Category: "Minutes"_x000D_
}_x000D_
];_x000D_
_x000D_
$(function() {_x000D_
var source = $("#document-template").html();_x000D_
var template = Handlebars.compile(source);_x000D_
var html = template(data);_x000D_
$('#DocumentResults').html(html);_x000D_
});
_x000D_
.row {_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="DocumentResults">pos</div>_x000D_
<script id="document-template" type="text/x-handlebars-template">_x000D_
<div>_x000D_
{{#each .}}_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<h2>{{Category}}</h2>_x000D_
{{#DocumentList}}_x000D_
<p>{{DocumentName}} at {{DocumentLocation}}</p>_x000D_
{{/DocumentList}}_x000D_
</div>_x000D_
</div>_x000D_
{{/each}}_x000D_
</div>_x000D_
</script>
_x000D_
Instead of flex: 1 0 auto
just use flex: 1
main, aside, article {_x000D_
margin: 10px;_x000D_
border: solid 1px #000;_x000D_
border-bottom: 0;_x000D_
height: 50px;_x000D_
}_x000D_
main {_x000D_
display: flex;_x000D_
}_x000D_
aside {_x000D_
flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
flex: 1;_x000D_
}
_x000D_
<main>_x000D_
<aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
<article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
Looks a lot like Oracle, but that doesn't work on SQL Server.
You can, instead, adopt the following syntax...
SELECT
*
INTO
new_table
FROM
old_source(s)
Here's a full featured TimeOfDay class.
This is overkill for simple cases, but if you need more advanced functionality like I did, this may help.
It can handle the corner cases, some basic math, comparisons, interaction with DateTime, parsing, etc.
Below is the source code for the TimeOfDay class. You can see usage examples and learn more here:
This class uses DateTime for most of its internal calculations and comparisons so that we can leverage all of the knowledge already embedded in DateTime.
// Author: Steve Lautenschlager, CambiaResearch.com
// License: MIT
using System;
using System.Text.RegularExpressions;
namespace Cambia
{
public class TimeOfDay
{
private const int MINUTES_PER_DAY = 60 * 24;
private const int SECONDS_PER_DAY = SECONDS_PER_HOUR * 24;
private const int SECONDS_PER_HOUR = 3600;
private static Regex _TodRegex = new Regex(@"\d?\d:\d\d:\d\d|\d?\d:\d\d");
public TimeOfDay()
{
Init(0, 0, 0);
}
public TimeOfDay(int hour, int minute, int second = 0)
{
Init(hour, minute, second);
}
public TimeOfDay(int hhmmss)
{
Init(hhmmss);
}
public TimeOfDay(DateTime dt)
{
Init(dt);
}
public TimeOfDay(TimeOfDay td)
{
Init(td.Hour, td.Minute, td.Second);
}
public int HHMMSS
{
get
{
return Hour * 10000 + Minute * 100 + Second;
}
}
public int Hour { get; private set; }
public int Minute { get; private set; }
public int Second { get; private set; }
public double TotalDays
{
get
{
return TotalSeconds / (24d * SECONDS_PER_HOUR);
}
}
public double TotalHours
{
get
{
return TotalSeconds / (1d * SECONDS_PER_HOUR);
}
}
public double TotalMinutes
{
get
{
return TotalSeconds / 60d;
}
}
public int TotalSeconds
{
get
{
return Hour * 3600 + Minute * 60 + Second;
}
}
public bool Equals(TimeOfDay other)
{
if (other == null) { return false; }
return TotalSeconds == other.TotalSeconds;
}
public override bool Equals(object obj)
{
if (obj == null) { return false; }
TimeOfDay td = obj as TimeOfDay;
if (td == null) { return false; }
else { return Equals(td); }
}
public override int GetHashCode()
{
return TotalSeconds;
}
public DateTime ToDateTime(DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day, Hour, Minute, Second);
}
public override string ToString()
{
return ToString("HH:mm:ss");
}
public string ToString(string format)
{
DateTime now = DateTime.Now;
DateTime dt = new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
return dt.ToString(format);
}
public TimeSpan ToTimeSpan()
{
return new TimeSpan(Hour, Minute, Second);
}
public DateTime ToToday()
{
var now = DateTime.Now;
return new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
}
#region -- Static --
public static TimeOfDay Midnight { get { return new TimeOfDay(0, 0, 0); } }
public static TimeOfDay Noon { get { return new TimeOfDay(12, 0, 0); } }
public static TimeOfDay operator -(TimeOfDay t1, TimeOfDay t2)
{
DateTime now = DateTime.Now;
DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
DateTime dt2 = dt1 - ts;
return new TimeOfDay(dt2);
}
public static bool operator !=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds != t2.TotalSeconds;
}
}
public static bool operator !=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 != dt2;
}
public static bool operator !=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 != dt2;
}
public static TimeOfDay operator +(TimeOfDay t1, TimeOfDay t2)
{
DateTime now = DateTime.Now;
DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
DateTime dt2 = dt1 + ts;
return new TimeOfDay(dt2);
}
public static bool operator <(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds < t2.TotalSeconds;
}
}
public static bool operator <(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 < dt2;
}
public static bool operator <(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 < dt2;
}
public static bool operator <=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
if (t1 == t2) { return true; }
return t1.TotalSeconds <= t2.TotalSeconds;
}
}
public static bool operator <=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 <= dt2;
}
public static bool operator <=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 <= dt2;
}
public static bool operator ==(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else { return t1.Equals(t2); }
}
public static bool operator ==(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 == dt2;
}
public static bool operator ==(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 == dt2;
}
public static bool operator >(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds > t2.TotalSeconds;
}
}
public static bool operator >(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 > dt2;
}
public static bool operator >(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 > dt2;
}
public static bool operator >=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds >= t2.TotalSeconds;
}
}
public static bool operator >=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 >= dt2;
}
public static bool operator >=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 >= dt2;
}
/// <summary>
/// Input examples:
/// 14:21:17 (2pm 21min 17sec)
/// 02:15 (2am 15min 0sec)
/// 2:15 (2am 15min 0sec)
/// 2/1/2017 14:21 (2pm 21min 0sec)
/// TimeOfDay=15:13:12 (3pm 13min 12sec)
/// </summary>
public static TimeOfDay Parse(string s)
{
// We will parse any section of the text that matches this
// pattern: dd:dd or dd:dd:dd where the first doublet can
// be one or two digits for the hour. But minute and second
// must be two digits.
Match m = _TodRegex.Match(s);
string text = m.Value;
string[] fields = text.Split(':');
if (fields.Length < 2) { throw new ArgumentException("No valid time of day pattern found in input text"); }
int hour = Convert.ToInt32(fields[0]);
int min = Convert.ToInt32(fields[1]);
int sec = fields.Length > 2 ? Convert.ToInt32(fields[2]) : 0;
return new TimeOfDay(hour, min, sec);
}
#endregion
private void Init(int hour, int minute, int second)
{
if (hour < 0 || hour > 23) { throw new ArgumentException("Invalid hour, must be from 0 to 23."); }
if (minute < 0 || minute > 59) { throw new ArgumentException("Invalid minute, must be from 0 to 59."); }
if (second < 0 || second > 59) { throw new ArgumentException("Invalid second, must be from 0 to 59."); }
Hour = hour;
Minute = minute;
Second = second;
}
private void Init(int hhmmss)
{
int hour = hhmmss / 10000;
int min = (hhmmss - hour * 10000) / 100;
int sec = (hhmmss - hour * 10000 - min * 100);
Init(hour, min, sec);
}
private void Init(DateTime dt)
{
Init(dt.Hour, dt.Minute, dt.Second);
}
}
}
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
If you are running Redis locally on a windows machine, try to "run as administrator" and see if it works. With me, the problem was that Redis was located in the "Program Files" folder, which restricts permissions by default. As it should.
However, do not automatically run Redis as an administrator You don't want to grant it more rights that it is supposed to have. You want to solve this by the book.
So, we have been able to quickly identify the problem by running it as an administrator, but this is not the cure. A likely scenario is that you have put Redis in a folder that doesn't have write rights and as a consequence the DB file is stored in that same location.
You can solve this by opening the redis.windows.conf
and to search for the following configuration:
# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir ./
Change dir ./
to a path you have regular read/write permissions for
You could also just move the Redis folder in it's entirety to a folder you know has the right permissions.
Always keep in mind that 'size' is variable if not explicitly specified so if you declare
int i = 10;
On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).
In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across
typedef short INT16;
typedef int INT32;
typedef long INT64;
Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.
On a windows based system, you may see entries in stdin.h header file as
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.
Anyone trying to manually enter the date to sql server 'date type' variable use this format while entering :
'yyyy-mm-dd'
For me I just needed to add the following:
if let popoverController = alertController.popoverPresentationController {
popoverController.barButtonItem = navigationItem.rightBarButtonItem
}
1.Just Disable signing from the properties of your project it will solve issue :)
2.The other method is to purchase the certificate for your product from Digicert or Comodo or any other you want. You can get some free certificates for One pc use.
For those people to whom none of the answers worked.... try closing the chrome://inspect/#devices tab in chrome if opened... This worked for me.
Here's how to determine a local user:
public bool IsLocalUser()
{
return windowsIdentity.AuthenticationType == "NTLM";
}
You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.
Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:
Why the NTLM Plug-in is Needed
NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.
Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.
By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.
How the Plug-in Works
The Verifier plug detects the following errors:
The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).
The target name in the call to InitializeSecurityContext is NULL.
The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.
The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).
The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.
NTLM Stops
5000 – Application Has Explicitly Selected NTLM Package
Severity – Error
The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.
How to Fix this Error
The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.
APIs(parameter) Used by Application Incorrect Value Correct Value ===================================== =============== ======================== AcquireCredentialsHandle (pszPackage) “NTLM” NEGOSSP_NAME “Negotiate”
Here's a way to pass a dynamic object to a view (or partial view)
Add the following class anywhere in your solution (use System namespace, so its ready to use without having to add any references) -
namespace System
{
public static class ExpandoHelper
{
public static ExpandoObject ToExpando(this object anonymousObject)
{
IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}
}
}
When you send the model to the view, convert it to Expando :
return View(new {x=4, y=6}.ToExpando());
Cheers
In computer science there is another meaning for "loose coupling" that no one else has posted about here, so... Here goes - hopefully you'll give me some votes up so this isn't lost at the bottom of the heap! SURELY the subject of my answer belongs in any comprehensive answer to the question... To wit:
The term "Loose Coupling" first entered computing as a term used as an adjective regarding CPU architecture in a multi-CPU configuration. Its counterpart term is "tight coupling". Loose Coupling is when CPUs do not share many resources in common and Tight Coupling is when they do.
The term "system" can be confusing here so please parse the situation carefully.
Usually, but not always, multiple CPUs in a hardware configuration in which they exist within one system (as in individual "PC" boxes) would be tightly coupled. With the exception of some super-high-performance systems that have subsystems that actually share main memory across "systems", all divisible systems are loosely coupled.
The terms Tightly Coupled and Loosely Coupled were introduced before multi-threaded and multi-core CPUs were invented, so these terms may need some companions to fully articulate the situation today. And, indeed, today one may very well have a system that encompases both types in one overall system. Regarding current software systems, there are two common architectures, one of each variety, that are common enough these should be familliar.
First, since it was what the question was about, some examples of Loosely Coupled systems:
In contrast, some Tightly Coupled examples:
In today's computing, examples of both operating in a single overall system is not uncommon. For example, take modern Pentium dual or quad core CPUs running Fedora 9 - these are tightly-coupled computing systems. Then, combine several of them in a loosely coupled Linux Cluster and you now have both loosely and tightly coupled computing going on! Oh, isn't modern hardware wonderful!
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
I did it! :)
Works fine without C++11
class MyClass {
typedef std::map<std::string, int> MyMap;
struct T {
const char* Name;
int Num;
operator MyMap::value_type() const {
return std::pair<std::string, int>(Name, Num);
}
};
static const T MapPairs[];
static const MyMap TheMap;
};
const MyClass::T MyClass::MapPairs[] = {
{ "Jan", 1 }, { "Feb", 2 }, { "Mar", 3 }
};
const MyClass::MyMap MyClass::TheMap(MapPairs, MapPairs + 3);
function addDays (date, daysToAdd) {_x000D_
var _24HoursInMilliseconds = 86400000;_x000D_
return new Date(date.getTime() + daysToAdd * _24HoursInMilliseconds);_x000D_
};_x000D_
_x000D_
var now = new Date();_x000D_
_x000D_
var yesterday = addDays(now, - 1);_x000D_
_x000D_
var tomorrow = addDays(now, 1);
_x000D_
"Permission denied" prevents your script from being invoked at all. Thus, the only syntax that could be possibly pertinent is that of the first line (the "shebang"), which should look like #!/usr/bin/env bash
, or #!/bin/bash
, or similar depending on your target's filesystem layout.
Most likely the filesystem permissions not being set to allow execute. It's also possible that the shebang references something that isn't executable, but this is far less likely.
Mooted by the ease of repairing the prior issues.
The simple reading of
docker: Error response from daemon: oci runtime error: exec: "/usr/src/app/docker-entrypoint.sh": permission denied.
...is that the script isn't marked executable.
RUN ["chmod", "+x", "/usr/src/app/docker-entrypoint.sh"]
will address this within the container. Alternately, you can ensure that the local copy referenced by the Dockerfile is executable, and then use COPY
(which is explicitly documented to retain metadata).
By default VS is not made to run PHP, but you can do it with extensions:
You can install an add-on with the extension manager, PHP Tools for Visual Studio.
If you want to install it inside VS, go to Tools > Extension Manager > Online Gallery > Search for PHP where you will find PHP Tools (the link above) for Visual Studio. Also you have VS.Php for Visual Studio. Both are not free.
You have also a cool PHP compiler called Phalanger:
If I'm not mistaken, the code you wrote above is JavaScript (jQuery) and not PHP.
If you want cool standalone IDE's for PHP: (Free)
Simply create it as new byte[100]
it will be initialized with 0 by default
as of now, with win 1909 and using Git-2.24.0.2-64-bit installer the process is very friendly towards user configuration. Seems like the earlier problems may now be catered for.
This usually happens when using Cocoapods and you are building from the xcproject which doesn't know about the cocoapod libraries.
Yes, that is safe and recommended.
The only caveat from the page you referred is that you can't be modifying configuration of the mapper once it is shared; but you are not changing configuration so that is fine. If you did need to change configuration, you would do that from the static block and it would be fine as well.
EDIT: (2013/10)
With 2.0 and above, above can be augmented by noting that there is an even better way: use ObjectWriter
and ObjectReader
objects, which can be constructed by ObjectMapper
.
They are fully immutable, thread-safe, meaning that it is not even theoretically possible to cause thread-safety issues (which can occur with ObjectMapper
if code tries to re-configure instance).
I have found that wget does not properly authenticate with some servers, perhaps because it is only HTTP 1.0 compliant. In such cases, curl (which is HTTP 1.1 compliant) usually does the trick:
curl -o <filename-to-save-as> -u <username>:<password> <url>
I know that it's an old question, but you can change the Response using a parameter (P):
public class Response<P> implements Serializable{
private static final long serialVersionUID = 1L;
public enum MessageCode {
SUCCESS, ERROR, UNKNOWN
}
private MessageCode code;
private String message;
private P payload;
...
public P getPayload() {
return payload;
}
public void setPayload(P payload) {
this.payload = payload;
}
}
The method would be
public Response<Departments> getDepartments(){...}
I can't try it now but it should works.
Otherwise it's possible to extends Response
@XmlRootElement
public class DepResponse extends Response<Department> {<no content>}
For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"
For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"
SyntaxError: non-default argument follows default argument
If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come after.
In Python 3 however, you may do the following:
def fun1(a="who is you", b="True", *, x, y):
pass
which makes x
and y
keyword only so you can do this:
fun1(x=2, y=2)
This works because there is no longer any ambiguity. Note you still can't do fun1(2, 2)
(that would set the default arguments).
On Windows you need to include the gl.h
header for OpenGL 1.1 support and link against OpenGL32.lib. Both are a part of the Windows SDK. In addition, you might want the following headers which you can get from http://www.opengl.org/registry .
<GL/glext.h>
- OpenGL 1.2 and above compatibility profile and extension interfaces..<GL/glcorearb.h>
- OpenGL core profile and ARB extension interfaces, as described in appendix G.2 of the OpenGL 4.3 Specification. Does not include interfaces found only in the compatibility profile.<GL/glxext.h>
- GLX 1.3 and above API and GLX extension interfaces.<GL/wglext.h>
- WGL extension interfaces.On Linux you need to link against libGL.so, which is usually a symlink to libGL.so.1, which is yet a symlink to the actual library/driver which is a part of your graphics driver. For example, on my system the actual driver library is named libGL.so.256.53, which is the version number of the nvidia driver I use. You also need to include the gl.h
header, which is usually a part of a Mesa or Xorg package. Again, you might need glext.h
and glxext.h
from http://www.opengl.org/registry . glxext.h
holds GLX extensions, the equivalent to wglext.h
on Windows.
If you want to use OpenGL 3.x or OpenGL 4.x functionality without the functionality which were moved into the GL_ARB_compatibility
extension, use the new gl3.h
header from the registry webpage. It replaces gl.h
and also glext.h
(as long as you only need core functionality).
Last but not the least, glaux.h
is not a header associated with OpenGL. I assume you've read the awful NEHE tutorials and just went along with it. Glaux is a horribly outdated Win32 library (1996) for loading uncompressed bitmaps. Use something better, like libPNG, which also supports alpha channels.
References are not objects. They don't have storage of their own, they just reference existing objects. For this reason it doesn't make sense to have arrays of references.
If you want a light-weight object that references another object then you can use a pointer. You will only be able to use a struct
with a reference member as objects in arrays if you provide explicit initialization for all the reference members for all struct
instances. References cannot be default initalized.
Edit: As jia3ep notes, in the standard section on declarations there is an explicit prohibition on arrays of references.
I could use console to push/pull the repositories, but no in eclipse. In my case, eclipse seems can't read my SSH private key, my key started with:
-----BEGIN OPENSSH PRIVATE KEY-----
And I noticed my colleague's key started with:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
I think currently eclipse can't take this new kind of key (OPENSSH PRIVATE KEY).
I solved it by: Regenerate your ssh key by using command:
ssh-keygen -m PEM -t rsa -b 2048
This will use the old way to generate the key: so it will starts with the headers:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
see more information on:
https://github.com/duplicati/duplicati/issues/3360
Then you can load the key again in eclilpse by using Preferences -> Network connections -> SSH2, click "Add Private Key" (still select your private key, even you already see the name in the list of private keys, because eclipse has to reload it)
color: transparent;
make the tricks for me
#videos-part:before{
font-size: 35px;
line-height: 33px;
width: 16px;
color: transparent;
content: 'AS YOU LIKE';
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUwIDUwIiBoZWlnaHQ9IjUwcHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MCA1MCIgd2lkdGg9IjUwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik04LDE0TDQsNDloNDJsLTQtMzVIOHoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbWl0ZXJsaW1pdD0iMTAiIHN0cm9rZS13aWR0aD0iMiIvPjxyZWN0IGZpbGw9Im5vbmUiIGhlaWdodD0iNTAiIHdpZHRoPSI1MCIvPjxwYXRoIGQ9Ik0zNCwxOWMwLTEuMjQxLDAtNi43NTksMC04ICBjMC00Ljk3MS00LjAyOS05LTktOXMtOSw0LjAyOS05LDljMCwxLjI0MSwwLDYuNzU5LDAsOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1taXRlcmxpbWl0PSIxMCIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIxOSIgcj0iMiIvPjxjaXJjbGUgY3g9IjE2IiBjeT0iMTkiIHI9IjIiLz48L3N2Zz4=');
background-size: 25px;
background-repeat: no-repeat;
}
you can display easly in a html page like this
<embed src="path_of_your_pdf/your_pdf_file.pdf" type="application/pdf" height="700px" width="500">
_x000D_
Using button.titleLabel.frame.size.width
works fine only as long the label is short enough not to be truncated. When the label text gets truncated positioning doesn't work though. Taking
CGSize titleSize = [[[button titleLabel] text] sizeWithFont:[[button titleLabel] font]];
works for me even when the label text is truncated.
The easier way to do it is just:
ul li:after {
content: url('../images/small_triangle.png');
}
I did this class for that purpose. it produces a variable size matrix ( expandable) when more items are added
'''
#pragma once
#include<vector>
#include<iostream>
#include<iomanip>
using namespace std;
template <class T>class Matrix
{
public:
Matrix() = default;
bool AddItem(unsigned r, unsigned c, T value)
{
if (r >= Rows_count)
{
Rows.resize(r + 1);
Rows_count = r + 1;
}
else
{
Rows.resize(Rows_count);
}
if (c >= Columns_Count )
{
for (std::vector<T>& row : Rows)
{
row.resize(c + 1);
}
Columns_Count = c + 1;
}
else
{
for (std::vector<T>& row : Rows)
{
row.resize(Columns_Count);
}
}
if (r < Rows.size())
if (c < static_cast<std::vector<T>>(Rows.at(r)).size())
{
(Rows.at(r)).at(c) = value;
}
else
{
cout << Rows.at(r).size() << " greater than " << c << endl;
}
else
cout << "ERROR" << endl;
return true;
}
void Show()
{
std::cout << "*****************"<<std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " <<setw(5)<< c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
void Show(size_t n)
{
std::cout << "*****************" << std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " << setw(n) << c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
// ~Matrix();
public:
std::vector<std::vector<T>> Rows;
unsigned Rows_count;
unsigned Columns_Count;
};
'''
df = df_try
for i in range(4):
df = df.append(df_try)
# Here, we have df_try times 5
df = df.append(df)
# Here, we have df_try times 10
My VPN connection was not enabled. I was trying all possible way to open up the Firwall and Ports until I realized, I am working from home and my VPN connection was down. But yes, Firewall and ssh configurations can be a reason.
you can try
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));
Document doc = db.parse(is);
refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm
You should include the repository where you want to deploy in the distribution management section of the pom.xml
.
Example:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
...
<distributionManagement>
<repository>
<uniqueVersion>false</uniqueVersion>
<id>corp1</id>
<name>Corporate Repository</name>
<url>scp://repo/maven2</url>
<layout>default</layout>
</repository>
...
</distributionManagement>
...
</project>
Log into on your Server/PC with administrator account
Log into SQL Server Management Studio as "Windows Authentication"
Click Security -> Logins -> choose your -> right click then choose Properties or Double click -> click Server Roles -> then checklist 'dbcreator' and 'sysadmin' then click the OK button.
Refresh your databases.
Now, you can create new database.
The accepted answer explains already well why the warning occurs. If you simply want to control the warnings, one could use precision_recall_fscore_support
. It offers a (semi-official) argument warn_for
that could be used to mute the warnings.
(_, _, f1, _) = metrics.precision_recall_fscore_support(y_test, y_pred,
average='weighted',
warn_for=tuple())
As mentioned already in some comments, use this with care.
Swift 3:
override func didMove(toParentViewController parent: UIViewController?) {
super.didMove(toParentViewController: parent)
if parent == nil{
print("Back button was clicked")
}
}
@{
int proID = 123;
int nonProID = 456;
}
<script>
var nonID = '@nonProID';
var proID = '@proID';
window.nonID = '@nonProID';
window.proID = '@proID';
</script>
You can also create a borderless window, and make the borders and title bar yourself
Yes VBA is the way to go.
But, if you don't need to have a cell with formula that auto-counts/updates the number of cells with a particular colour, an alternative is simply to use the 'Find and Replace' function and format the cell to have the appropriate colour fill.
Hitting 'Find All' will give you the total number of cells found at the bottom left of the dialogue box.
This becomes especially useful if your search range is massive. The VBA script will be very slow but the 'Find and Replace' function will still be very quick.
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
Your table width is 90% which is relative to it's container.
If you squeeze the page, you are probably squeezing the table width as well. The width of the cells reduce too and the browser compensate by increasing the height.
To have the height untouched, you have to make sure the widths of the cells can hold the intented content. Fixing the table width is probably something you want to try. Or perhaps play around with the min-width of the table.
You can create a new queue item to do your removing of the class:
$("#div").addClass("error").delay(1000).queue(function(next){
$(this).removeClass("error");
next();
});
Or using the dequeue method:
$("#div").addClass("error").delay(1000).queue(function(){
$(this).removeClass("error").dequeue();
});
The reason you need to call next
or dequeue
is to let jQuery know that you are done with this queued item and that it should move on to the next one.
Oracle documentation quoted the difference precisely.
inheritance: A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits. (Note that hiding fields is generally bad programming practice.)
polymorphism: polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.
polymorphism is not applicable for fields.
Related post:
Can use either json or ast python modules:
Using json :
=============
import json
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_data = json.loads(jsonStr)
print(f"json_data: {json_data}")
print(f"json_data['two']: {json_data['two']}")
Output:
json_data: {'one': '1', 'two': '2', 'three': '3'}
json_data['two']: 2
Using ast:
==========
import ast
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_dict = ast.literal_eval(jsonStr)
print(f"json_dict: {json_dict}")
print(f"json_dict['two']: {json_dict['two']}")
Output:
json_dict: {'one': '1', 'two': '2', 'three': '3'}
json_dict['two']: 2
Enclose Link component inside BrowserRouter component
export default () => (
<div>
<h1>
<BrowserRouter>
<Link to="/">Redux example</Link>
</BrowserRouter>
</h1>
</div>
)
Gustavomcls's solution to change com.google.* version to same version worked for me .
I change both dependancies to 9.2.1 in buid.gradle (Module:app)
compile 'com.google.firebase:firebase-ads:9.2.1'
compile 'com.google.android.gms:play-services:9.2.1'
DENSE_RANK() is a rank with no gaps, i.e. it is “dense”.
select Name,EmailId,salary,DENSE_RANK() over(order by salary asc) from [dbo].[Employees]
RANK()-It contain gap between the rank.
select Name,EmailId,salary,RANK() over(order by salary asc) from [dbo].[Employees]
I created the following Method to create reusable One Liner:
public void oneMethodToCloseThemAll(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
if (!resultSet.isClosed()) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
if (!statement.isClosed()) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
if (!connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I use this Code in a parent Class thats inherited to all my classes that send DB Queries. I can use the Oneliner on all Queries, even if i do not have a resultSet.The Method takes care of closing the ResultSet, Statement, Connection in the correct order. This is what my finally block looks like.
finally {
oneMethodToCloseThemAll(resultSet, preStatement, sqlConnection);
}
This probably isn't the most elegant way to do it, but it gets the job done.
In[1]: import numpy as np
In[2]: import pandas as pd
In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])
In[4]: df
Out[4]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
Just replace '/Users/spencerlyon2/Desktop/test.csv'
with the path to your file
I get this error whenever I use np.concatenate
the wrong way:
>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index
The correct way is to input the two arrays as a tuple:
>>> np.concatenate((a, a))
array([[1., 0.],
[0., 1.],
[1., 0.],
[0., 1.]])
Date#parse
is deprecated . The alternative is :
java.text.DateFormat#parse
thereFore :
new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)
Netscape ANSI encoded files use 0D 0D 0A for their line breaks.
typedef struct{
char name[30];
char surname[30];
int age;
} data;
defines that data
should be a block of memory that fits 60 chars plus 4 for the int (see note)
[----------------------------,------------------------------,----]
^ this is name ^ this is surname ^ this is age
This allocates the memory on the stack.
data s1;
Assignments just copies numbers, sometimes pointers.
This fails
s1.name = "Paulo";
because the compiler knows that s1.name
is the start of a struct 64 bytes long, and "Paulo"
is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.
To copy "Paulo" into the struct at the point name
and "Rossi" into the struct at point surname
.
memcpy(s1.name, "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;
You end up with
[Paulo0----------------------,Rossi0-------------------------,0001]
strcpy
does the same thing but it knows about \0
termination so does not need the length hardcoded.
Alternatively you can define a struct which points to char arrays of any length.
typedef struct {
char *name;
char *surname;
int age;
} data;
This will create
[----,----,----]
This will now work because you are filling the struct with pointers.
s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;
Something like this
[---4,--10,---1]
Where 4 and 10 are pointers.
Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.
not sure if my code is efficeient, anyone care to comment?
from math import isqrt
def isPrime(n):
if n >= 2: # cheating the 2, is 2 even prime?
for i in range(3, int(n / 2 + 1),2): # dont waste time with even numbers
if n % i == 0:
return False
return True
def primesTo(n):
x = [2] if n >= 2 else [] # cheat the only even prime
if n >= 2:
for i in range(3, n + 1,2): # dont waste time with even numbers
if isPrime(i):
x.append(i)
return x
def primes2(n): # trying to do this using set methods and the "Sieve of Eratosthenes"
base = {2} # again cheating the 2
base.update(set(range(3, n + 1, 2))) # build the base of odd numbers
for i in range(3, isqrt(n) + 1, 2): # apply the sieve
base.difference_update(set(range(2 * i, n + 1 , i)))
return list(base)
print(primesTo(10000)) # 2 different methods for comparison
print(primes2(10000))
If the purpose is to simply print coarse timing information to your program logs, then the easy solution for Java projects is not to write your own stopwatch or timer classes, but just use the org.apache.commons.lang.time.StopWatch
class that is part of Apache Commons Lang.
final StopWatch stopwatch = new StopWatch();
stopwatch.start();
LOGGER.debug("Starting long calculations: {}", stopwatch);
...
LOGGER.debug("Time after key part of calcuation: {}", stopwatch);
...
LOGGER.debug("Finished calculating {}", stopwatch);
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
This error message seems to come up in various situations.
In my case, on top of my application's Web.Config file I had an extra Web.Config file in the root folder (C:\Inetpub\www.root). Probably left there after some testing, I had forgotten all about it, and couldn't figure out what the problem was.
Removing it solved the problem for me.
It indeed sets the stack size on a JVM.
You should touch it in either of these two situations:
The latter usually comes when your Xss is set too large - then you need to balance it (testing!)
Use the setAttribute
method:
document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");
But you really should be using data followed with a dash and with its property, like:
<li ... data-icon="base.gif" ...>
And to do it in JS use the dataset
property:
document.getElementById('item1').dataset.icon = "base.gif";
Check out http://mywiki.wooledge.org/DotFiles for an excellent resource on the topic aside from man bash
.
Summary:
~/.bash_profile
or ~/.profile
is read and executed. Since everything you run from your login shell inherits the login shell's environment, you should put all your environment variables in there. Like LESS
, PATH
, MANPATH
, LC_*
, ... For an example, see: My .profile
~/.bashrc
, not /.profile
or ~/.bash_profile
, for this exact reason, so in there define everything that only applies to bash. That's functions, aliases, bash-only variables like HISTSIZE (this is not an environment variable, don't export it!), shell options with set
and shopt
, etc. For an example, see: My .bashrc
~/.bashrc
but only ~/.profile
or ~/.bash_profile
, so you should source that one manually from the latter. You'll see me do that in my ~/.profile
too: source ~/.bashrc
.First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter
to your simple format and convert it back to a String.
Swift 3
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
The printed result is: Dateobj: 10-22-2015
Simplistically malloc
and free
work like this:
malloc
provides access to a process's heap. The heap is a construct in the C core library (commonly libc) that allows objects to obtain exclusive access to some space on the process's heap.
Each allocation on the heap is called a heap cell. This typically consists of a header that hold information on the size of the cell as well as a pointer to the next heap cell. This makes a heap effectively a linked list.
When one starts a process, the heap contains a single cell that contains all the heap space assigned on startup. This cell exists on the heap's free list.
When one calls malloc
, memory is taken from the large heap cell, which is returned by malloc
. The rest is formed into a new heap cell that consists of all the rest of the memory.
When one frees memory, the heap cell is added to the end of the heap's free list. Subsequent malloc
's walk the free list looking for a cell of suitable size.
As can be expected the heap can get fragmented and the heap manager may from time to time, try to merge adjacent heap cells.
When there is no memory left on the free list for a desired allocation, malloc
calls brk
or sbrk
which are the system calls requesting more memory pages from the operating system.
Now there are a few modification to optimize heap operations.
In the accepted answer PREMKUMAR there are a couple of errors in his Complete code in Swift answer. First print should read (appendString) and Second print should read (appendString1). Also, updated println deprecated in Swift 2.0
His
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
println("APPEND STRING1:\(appendString1)")
println("APPEND STRING2:\(appendString2)")
Corrected
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING:\(appendString)")
print("APPEND STRING1:\(appendString1)")
With all credit to LukeH, I've put together some extension methods for easy use:
public static DateTime FromUnixTime(this long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddSeconds(unixTime);
}
public static long ToUnixTime(this DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64((date - epoch).TotalSeconds);
}
Note the comment below from CodesInChaos that the above FromUnixTime
returns a DateTime
with a Kind
of Utc
, which is fine, but the above ToUnixTime
is much more suspect in that doesn't account for what kind of DateTime
the given date
is. To allow for date
's Kind
being either Utc
or Local
, use ToUniversalTime
:
public static long ToUnixTime(this DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}
ToUniversalTime
will convert a Local
(or Unspecified
) DateTime
to Utc
.
if you dont want to create the epoch DateTime instance when moving from DateTime to epoch you can also do:
public static long ToUnixTime(this DateTime date)
{
return (date.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}
You might want to try install bs4 with
pip install --ignore-installed BeautifulSoup4
if the methods above didn't work for you.
Not as complicated as they say, check this you will not regret.
String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";
if ( sentence.toLowerCase().indexOf(search.toLowerCase()) != -1 ) {
System.out.println("I found the keyword");
} else {
System.out.println("not found");
}
You can change the toLowerCase()
if you want.
I have been an hour with headache trying to close the infoWindow! My final (and working) option has been closing the infoWindow with a SetTimeout (a few seconds) It's not the best way... but it works easely
marker.addListener('click', function() {
infowindow.setContent(html);
infowindow.open(map, this);
setTimeout(function(){
infowindow.close();
},5000);
});
Windows
python -c "import pandas as pd; print(pd.__version__)"
conda list | findstr pandas # Anaconda / Conda
pip freeze | findstr pandas
pip show pandas | findstr Version
Linux
python -c "import pandas as pd; print(pd.__version__)"
conda list | grep numpy # Anaconda / Conda
pip freeze | grep numpy # pip
In ASP.NET MVC 5 you could use the [DataType(DataType.MultilineText)]
attribute. It will render a TextArea tag.
public class MyModel
{
[DataType(DataType.MultilineText)]
public string MyField { get; set; }
}
Then in the view if you need to specify the rows you can do it like this:
@Html.EditorFor(model => model.MyField, new { htmlAttributes = new { rows = 10 } })
Or just use the TextAreaFor with the right overload:
@Html.TextAreaFor(model => model.MyField, 10, 20, null)
Since the desired page will be called from a different domain you need to return jsonp instead of a json.
$.get("http://theSource", {callback : "?" }, "jsonp", function(data) {
$('#summary').text(data.result);
});
It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.
For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.
To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.
Pseudo code
ratio = 300.0 / 72.0 // 4.167
image.width * ratio
image.height * ratio
I know there is an accepted answer for this question and many other answers also but I just wanted to add an another case which happened with me was Updating the django and django rest framework to the latest versions to make them work properly without any error.
So all you have to do is just uninstall both django and django rest framework using:
pip uninstall django
pip uninstall djangorestframework
and then install it again using:
pip install django
pip install djangorestframework
I found that useful, stabbing service function as sinon.stub().returns($q.when({})):
this.myService = {
myFunction: sinon.stub().returns( $q.when( {} ) )
};
this.scope = $rootScope.$new();
this.angularStubs = {
myService: this.myService,
$scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );
controller:
this.someMethod = function(someObj) {
myService.myFunction( someObj ).then( function() {
someObj.loaded = 'bla-bla';
}, function() {
// failure
} );
};
and test
const obj = {
field: 'value'
};
this.ctrl.someMethod( obj );
this.scope.$digest();
expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );
There is a fundamental concept of IP routing: You must have a unique IP address if you want your machine to be reachable via the Internet. This is called a "Public IP Address". "www.whatismyipaddress.com" will give you this. If your server is behind some default gateway, IP packets would reach you via that router. You can not be reached via your private IP address from the outside world. You should note that private IP addresses of client and server may be same as long as their corresponding default gateways have different addresses (that's why IPv4 is still in effect) I guess you're trying to ping from your private address of your client to the public IP address of the server (provided by whatismyipaddress.com). This is not feasible. In order to achieve this, a mapping from private to public address is required, a process called Network Address Translation or NAT in short. This is configured in Firewall or Router. You can create your own private network (say via wifi). In this case, since your client and server would be on the same logical network, no private to public address translation would be required and hence you can communicate using your private IP addresses only.
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
I tried several of the options here. For all that I tried, the spacing was uneven, or was even but when I shrank the window width enough for the subviews to stack, there was no space between stacked views.
Here is what worked for me.
.col-sm-12 {
margin-bottom: 2em;
}
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="col-sm-12">
</div>
</div>
<div class="col-sm-6">
<div class="col-sm-12">
</div>
</div>
</div>
</div>
I think you are using the machine-name instead of the ip of the host.
I got the same error when i tried with machine's name. Because, It is allowed only when both the client and host are under same network and they have the same Operating system installed.
Go to the DBMS Output window (View->DBMS Output).
The sponge
util avoids the need for juggling a temp file:
tail -n +2 "$FILE" | sponge "$FILE"
inspect.signature
is very slow. Fastest way is
def f(a, b=1, *args, c, d=1, **kwargs):
pass
f_code = f.__code__
f_code.co_varnames[:f_code.co_argcount + f_code.co_kwonlyargcount] # ('a', 'b', 'c', 'd')
This worked me for UNICODE (UTF8) sentences too:
function myUTF8truncate($string, $width){
if (mb_str_word_count($string) > $width) {
$string= preg_replace('/((\w+\W*|| [\p{L}]+\W*){'.($width-1).'}(\w+))(.*)/', '${1}', $string);
}
return $string;
}
In my case I had all these worked except for the correct character recognition.
But you need to consider these few things:
ocr.Init(@"c:\tessdata", "eng", true);
hope that this helps
Firewalld is a bit non-intuitive for the iptables veteran. For those who prefer an iptables-driven firewall with iptables-like syntax in an easy configurable tree, try replacing firewalld with fwtree: https://www.linuxglobal.com/fwtree-flexible-linux-tree-based-firewall/ and then do the following:
echo '-p tcp --dport 80 -m conntrack --cstate NEW -j ACCEPT' > /etc/fwtree.d/filter/INPUT/80-allow.rule
systemctl reload fwtree
I use one main Javascript function that I had found at Mozilla Developer Network site https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications, along with another function with AJAX and changed according to my needs. It receives a document element id regarding the place in my html code where I want to write the file size.
<Javascript>
function updateSize(elementId) {
var nBytes = 0,
oFiles = document.getElementById(elementId).files,
nFiles = oFiles.length;
for (var nFileId = 0; nFileId < nFiles; nFileId++) {
nBytes += oFiles[nFileId].size;
}
var sOutput = nBytes + " bytes";
// optional code for multiples approximation
for (var aMultiples = ["K", "M", "G", "T", "P", "E", "Z", "Y"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
sOutput = " (" + nApprox.toFixed(3) + aMultiples[nMultiple] + ")";
}
return sOutput;
}
</Javascript>
<HTML>
<input type="file" id="inputFileUpload" onchange="uploadFuncWithAJAX(this.value);" size="25">
</HTML>
<Javascript with XMLHttpRequest>
document.getElementById('spanFileSizeText').innerHTML=updateSize("inputFileUpload");
</XMLHttpRequest>
Cheers
While plain old JavaScript objects can be used as maps, they are usually implemented in a way to preserve insertion-order for compatibility with most browsers (see Craig Barnes's answer) and are thus not simple hash maps.
ES6 introduces proper Maps (see MDN JavaScript Map) of which the standard says:
Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection.
If your are using IntelliJ, go to setting => compiler and change the version to your current java version.
import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')
# read bytes from archive
img_data = archive.read('img_01.png')
# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)
img = pygame.image.load(bytes_io)
I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.
You can use javascript's document.evaluate to run an XPath expression on the DOM. I think it's supported in one way or another in browsers back to IE 6.
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate
IE supports selectNodes instead.
MSDN: https://msdn.microsoft.com/en-us/library/ms754523(v=vs.85).aspx
I experienced this error when running some very memory-expensive processes. When the system started to run short of memory, I begun to notice this kind of error. I had to change the algorithm in order to make a better use of RAM.
To be noted that while some threads threw this exception, some other threw:
System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement. This could be because the pre-login handshake failed or the server was unable to respond back in time. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=43606; handshake=560; ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
Both problems disappeared after the system was changed so that it could run using less RAM.
Anti-aliasing cannot be turned on or off, and is controlled by the browser.
if you add your remote repository by using git clone then follow the steps:-
git clone <repo_url>
then
git init
git add *
*means add all files
git commit -m 'your commit'
git remote -v
for check any branch run or not if not then nothing show then we add or fetch the repository.
"fetch first". You need to run git pull origin <branch>
or git pull -r origin <branch>
before a next push.
then
git remote add origin <git url>
git pull -r origin master
git push -u origin master```
There are two facts :
1) Component scrollIntoView is not supported by safari.
2) JS framework jQuery can do the job like this:
parent = 'some parent div has css position==="fixed"' || 'html, body';
$(parent).animate({scrollTop: $(child).offset().top}, duration)
You can use browser default prompt window.
Instead of basic <input type="submit" (...) >
try:
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
OSX's Python binary (version 2) is located at /usr/bin/python
if you use which python
it will tell you where the python
command is being resolved to. Typically, what happens is third parties redefine things in /usr/local/bin
(which takes precedence, by default over /usr/bin
). To fix, you can either run /usr/bin/python
directly to use 2.x or find the errant redefinition (probably in /usr/local/bin
or somewhere else in your PATH
)
I assume by "key" and "value" you mean:
<select>
<option value="KEY">VALUE</option>
</select>
If that's the case, this will get you the "VALUE":
$(this).find('option:selected').text();
And you can get the "KEY" like this:
$(this).find('option:selected').val();
As UncleBens and Naveen have shown, there are good reasons for both. Which one is "better" depends on what behavior you want: Do you want to guarantee constant-time behavior, or do you want it to fall back to linear time when necessary?
it - vec.begin()
takes constant time, but the operator -
is only defined on random access iterators, so the code won't compile at all with list iterators, for example.
std::distance(vec.begin(), it)
works for all iterator types, but will only be a constant-time operation if used on random access iterators.
Neither one is "better". Use the one that does what you need.