I found another strange reason and i thought maybe another developer confused as me. I did run install.bat that created to install my service in developer Command Prompt of VS2010 but my service generated in VS2012. it was going to this error and drives me to crazy but i try VS2012 Developer Command Prompt tools and everything gone to be OK. I don't no why but my problem was solved. so you can test it and if anyone know reason of that please share with us. Thanks.
You might be better off to use memory-mapped files handling here.. The memory mapped file support will be around in .NET 4 (I think...I heard that through someone else talking about it), hence this wrapper which uses p/invokes to do the same job..
Edit: See here on the MSDN for how it works, here's the blog entry indicating how it is done in the upcoming .NET 4 when it comes out as release. The link I have given earlier on is a wrapper around the pinvoke to achieve this. You can map the entire file into memory, and view it like a sliding window when scrolling through the file.
If you are using Spring 3, the easiest way is:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request, Principal principal) {
final String currentUser = principal.getName();
}
Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:
INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'
In the above query, there are 2 extra columns named email & current_time.
See the code below, adapted from this article, which demonstrates the simplest example code I could find. It includes both file and memory (faster) uploads.
public HttpResponseMessage Post()
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count < 1)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
foreach(string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
// NOTE: To store in memory use postedFile.InputStream
}
return Request.CreateResponse(HttpStatusCode.Created);
}
You don't have any data that you're submitting! Try adding this line to your ajax:
data: $('form').serialize(),
Make sure you change the name to match!
Also your data should be submitted inside of a form submit function.
Your code should look something like this:
<script>_x000D_
$(function () {_x000D_
$('form').on('submit', function (e) {_x000D_
e.preventDefault();_x000D_
$.ajax({_x000D_
type: 'post',_x000D_
url: 'company.php',_x000D_
data: $('form').serialize(),_x000D_
success: function () {_x000D_
alert('form was submitted');_x000D_
}_x000D_
});_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
I agree with @aaronasterling's answer. However, if you want a non-binary string that you can cast into an int, then you can use the canonical algorithm:
def decToBin(n):
if n==0: return ''
else:
return decToBin(n/2) + str(n%2)
Escape your HTML tags ...
<resources>
<string name="somestring">
<B>Title</B><BR/>
Content
</string>
</resources>
You need to specify the -vb option to increase the video bitrate, otherwise you get the default which produces smaller videos but with more artifacts.
Try something like this:
ffmpeg -r 25 -i %4d.png -vb 20M myvideo.mpg
This might be helpful
http://opencvuser.blogspot.in/2011/08/creating-haar-cascade-classifier-aka.html
Using Task, futurize, and a traversable List, you can simply do
async function printFiles() {
const files = await getFiles();
List(files).traverse( Task.of, f => readFile( f, 'utf-8'))
.fork( console.error, console.log)
}
Here is how you'd set this up
import fs from 'fs';
import { futurize } from 'futurize';
import Task from 'data.task';
import { List } from 'immutable-ext';
const future = futurizeP(Task)
const readFile = future(fs.readFile)
Another way to have structured the desired code would be
const printFiles = files =>
List(files).traverse( Task.of, fn => readFile( fn, 'utf-8'))
.fork( console.error, console.log)
Or perhaps even more functionally oriented
// 90% of encodings are utf-8, making that use case super easy is prudent
// handy-library.js
export const readFile = f =>
future(fs.readFile)( f, 'utf-8' )
export const arrayToTaskList = list => taskFn =>
List(files).traverse( Task.of, taskFn )
export const readFiles = files =>
arrayToTaskList( files, readFile )
export const printFiles = files =>
readFiles(files).fork( console.error, console.log)
Then from the parent function
async function main() {
/* awesome code with side-effects before */
printFiles( await getFiles() );
/* awesome code with side-effects after */
}
If you really wanted more flexibility in encoding, you could just do this (for fun, I'm using the proposed Pipe Forward operator )
import { curry, flip } from 'ramda'
export const readFile = fs.readFile
|> future,
|> curry,
|> flip
export const readFileUtf8 = readFile('utf-8')
PS - I didn't try this code on the console, might have some typos... "straight freestyle, off the top of the dome!" as the 90s kids would say. :-p
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
Delete the unit testing from your project follow the below steps this will solve the issue.
select your project from the project navigator to open the project editor. From the target delete the test from the left side of the project editor and press the Delete key.
Asking about "a class" in the question title, the answer is getElementsByClassName
:
var hrefs = document.getElementsByClassName("YOUR-CLASS-NAME-HERE");
for (var i = 0; i < hrefs.length; i++) {
hrefs.item(i).addEventListener('click', function(e){
e.preventDefault(); /*use if you want to prevent the original link following action*/
alert('hohoho');
});
}
It is more that the media validates the string encoding, so we want to ensure that the data is acceptable by a handling application (and doesn't contain a binary sequence representing EOL for example)
Imagine you want to send binary data in an email with encoding UTF-8 -- The email may not display correctly if the stream of ones and zeros creates a sequence which isn't valid Unicode in UTF-8 encoding.
The same type of thing happens in URLs when we want to encode characters not valid for a URL in the URL itself:
http://www.foo.com/hello my friend -> http://www.foo.com/hello%20my%20friend
This is because we want to send a space over a system that will think the space is smelly.
All we are doing is ensuring there is a 1-to-1 mapping between a known good, acceptable and non-detrimental sequence of bits to another literal sequence of bits, and that the handling application doesn't distinguish the encoding.
In your example, man
may be valid ASCII in first form; but often you may want to transmit values that are random binary (ie sending an image in an email):
MIME-Version: 1.0
Content-Description: "Base64 encode of a.gif"
Content-Type: image/gif; name="a.gif"
Content-Transfer-Encoding: Base64
Content-Disposition: attachment; filename="a.gif"
Here we see that a GIF image is encoded in base64 as a chunk of an email. The email client reads the headers and decodes it. Because of the encoding, we can be sure the GIF doesn't contain anything that may be interpreted as protocol and we avoid inserting data that SMTP or POP may find significant.
A stateful server keeps state between connections. A stateless server does not.
So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.
When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.
HTTP and NFS are stateless protocols. Each request stands on its own.
Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.
SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.
Try this:
urlString=Request.RawUrl.ToString.Substring(0, Request.RawUrl.ToString.IndexOf("?"))
from this: http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye you'll get this: mypage.aspx
Symfony 2.1 has a JsonResponse class.
return new JsonResponse(array('name' => $name));
The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.
There is also a handy setCallback
function for JSONP.
So it's throwing up that error message because you have apache2
running on port 80.
If this is for development, I would just leave it as it is on port 5000.
If it's for production either:
Not Recommended
apache2
first; Not recommended as it states in the documentation:
You can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)
Recommended
HTTP
traffic through apache2
to Flask.This way, apache2
can handle all your static files (which it's very good at - much better than the debug server built into Flask) and act as a reverse proxy for your dynamic content, passing those requests to Flask.
Here's a link to the official documentation about setting up Flask with Apache + mod_wsgi.
Edit 1 - Clarification for @Djack
Proxy HTTP traffic to Flask through apache2
When a request comes to the server on port 80 (HTTP
) or port 443 (HTTPS
) a web server like Apache or Nginx handles the connection of the request and works out what to do with it. In our case a request received should be configured to be passed through to Flask on the WSGI protocol and handled by the Python code. This is the "dynamic" part.
reverse proxy for dynamic content
There are a few advantages to configuring your web server like the above;
It may have been because I am still new to VS and definitely new to C, but the only thing that allowed me to build was adding
#pragma warning(disable:4996)
At the top of my file, this suppressed the C4996 error I was getting with sprintf
A bit annoying but perfect for my tiny bit of code and by far the easiest.
I read about it here: https://msdn.microsoft.com/en-us/library/2c8f766e.aspx
I believe this can be done very easily. You can always extract the source files (Java files) of a jar file into a zip.
Steps to get sources of a jar file as a zip :
Hope this helps.
The link is dead due to some reason so adding the link from where you can download the JDGUI
$(document).ready(function(){
$("input[type=search]").attr("placeholder","this is a test");
});
This simple command works like a charm:
git name-rev <SHA>
For example (where test-branch is the branch name):
git name-rev 651ad3a
251ad3a remotes/origin/test-branch
Even this is working for complex scenarios, like:
origin/branchA/
/branchB
/commit<SHA1>
/commit<SHA2>
Here git name-rev commit<SHA2>
returns branchB.
You can't cast explicitly anything to a String
that isn't a String
. You should use either:
"" + myInt;
or:
Integer.toString(myInt);
or:
String.valueOf(myInt);
I prefer the second form, but I think it's personal choice.
Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer
(in Java 1.4) or a StringBuilder
in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix)
that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.
Edit 2 I assumed you meant that your integer was an int
and not an Integer
. If it's already an Integer
, just use toString()
on it and be done.
Hide the file input. Create a new input to capture a click event and forward it to the hidden input:
<input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file"/>
First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.
Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.
How to decide whether to use Tomcat or a full stack Java EE
application server:
When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:
In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.
Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.
my 2 cent
This is my aproximation:
Declare
Variableclob Clob;
Temp_Save Varchar2(32767); //whether it is greater than 4000
Begin
Select reportClob Into Temp_Save From Reporte Where Id=...;
Variableclob:=To_Clob(Temp_Save);
Dbms_Output.Put_Line(Variableclob);
End;
You can use the bit
column type.
I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else
To test multiple variables with one single value: if 1 in {a,b,c}:
To test multiple values with one variable: if a in {1, 2, 3}:
Check out array_merge()
.
$array3 = array_merge($array1, $array2);
function handle_change(
evt: React.ChangeEvent<HTMLInputElement>
): string {
evt.persist(); // This is needed so you can actually get the currentTarget
const inputValue = evt.currentTarget.value;
return inputValue
}
And make sure you have "lib": ["dom"]
in your tsconfig
.
Might be, more safe alternative to "_ORACLE_SCRIPT"=true
is to change "_common_user_prefix"
from C##
to an empty string. When it's null - any name can be used for common user. Found there.
During changing that value you may face another issue - ORA-02095 - parameter cannot be modified, that can be fixed in a several ways, based on your configuration (source).
So for me worked that:
alter system set _common_user_prefix = ''; scope=spfile;
Looks like I got all the possible issues with that installation.
Troubleshooting: look at actual log file (in the log provided by the installer look for LOGFILE=...):
Process.Start: C:\Windows\system32\msiexec.exe /quiet /norestart /i "c:\2964b29c3cd7dcb37c9e\Packages\AppFabric-1.1-for-Windows-Server-64.msi" ADDDEFAULT=Worker,WorkerAdmin,CacheService,CacheClient,CacheAdmin,Setup /l*vx "c:\Temp\AppServerSetup1_1(2014-07-09 11-58-09).log" LOGFILE="c:\Temp\AppServerSetup1_1_CustomActions(2014-07-09 11-58-09).log" INSTALLDIR="C:\Program Files\AppFabric 1.1 for Windows Server" LANGID=en-US
After you located the actual log file, check for errors. I had to:
done. Hope that helps.
To me, the following is more readable (thus preferable) way to do it:
git reset HEAD~1
Instead of 1
, there could be any number of commits you want to unstage.
It needs to be placed inside a different thread that allows the UI to update as soon as execution of thread function completes:
Modern Swift:
DispatchQueue.main.async {
// Update UI
}
Older versions of Swift, pre Swift 3.
dispatch_async(dispatch_get_main_queue(){
// code here
})
Objective-C:
dispatch_async(dispatch_get_main_queue(), ^{
// code here
});
If you have two facets hospital
and room
but want to rename just one, you can use:
facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names)))
For renaming two facets using the vector-based approach (as in naught101's answer), you can do:
facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names),
room = as_labeller(room_names)))
Well,
Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!
Non programmatically, you can just open the archive using the 7zip UI to add/remove or extract/replace files without the structure changing. I didn't know it was a problem using other things until now :)
May be with:
SELECT count(*) FROM `table`
where
created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';
or use between
:
SELECT count(*) FROM `table`
where
created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';
You can change the datetime as per your need. May be use curdate()
or now()
to get the desired dates.
If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
got this from cloud service documentation
pip install --upgrade google-cloud-translate
Worked for me !
I have written a C# method that url-encodes ALL symbols:
/// <summary>
/// !#$345Hf} ? %21%23%24%33%34%35%48%66%7D
/// </summary>
public static string UrlEncodeExtended( string value )
{
char[] chars = value.ToCharArray();
StringBuilder encodedValue = new StringBuilder();
foreach (char c in chars)
{
encodedValue.Append( "%" + ( (int)c ).ToString( "X2" ) );
}
return encodedValue.ToString();
}
I like s3fs which lets you use s3 (almost) like a local filesystem.
You can do this:
import s3fs
bytes_to_write = df.to_csv(None).encode()
fs = s3fs.S3FileSystem(key=key, secret=secret)
with fs.open('s3://bucket/path/to/file.csv', 'wb') as f:
f.write(bytes_to_write)
s3fs
supports only rb
and wb
modes of opening the file, that's why I did this bytes_to_write
stuff.
Abstraction is hiding the information or providing only necessary details to the client.
e.g Car Brakes- You just know that pressing the pedals will stop the vehicle but you don't need to know how it works internally.
Advantage of Abstraction Tomorrow if brake implementation changes from drum brake to disk brake, as a client, you don't need to change(i.e your code will not change)
Encapsulation is binding the data and behaviors together in a single unit. Also it is a language mechanism for restricting access to some components(this can be achieved by access modifiers like private,protected etc.)
For e.g. Class has attributes(i.e data) and behaviors (i.e methods that operate on that data)
FFWD to 2019. Although this code worketh in 2011 too.
// g++ prog.cc -Wall -std=c++11
#include <iostream>
#include <vector>
using namespace std;
template<size_t N>
inline
constexpr /* compile time */
array<char,N> string_literal_to_array ( char const (&charrar)[N] )
{
return std::to_array( charrar) ;
}
template<size_t N>
inline
/* run time */
vector<char> string_literal_to_vector ( char const (&charrar)[N] )
{
return { charrar, charrar + N };
}
int main()
{
constexpr auto arr = string_literal_to_array("Compile Time");
auto cv = string_literal_to_vector ("Run Time") ;
return 42;
}
Advice: try optimizing the use of std::string
. For char buffering std::array<char,N>
is the fastest, std::vector<char>
is faster.
matplotlib
is somewhat different from when the original answer was postedmatplotlib.pyplot.text
matplotlib.axes.Axes.text
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')
# or
fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')
import matplotlib.pyplot as plt
# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)
ax.text(left, bottom, 'left top',
horizontalalignment='left',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, bottom, 'left bottom',
horizontalalignment='left',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right bottom',
horizontalalignment='right',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right top',
horizontalalignment='right',
verticalalignment='top',
transform=ax.transAxes)
ax.text(right, bottom, 'center top',
horizontalalignment='center',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'right center',
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'left center',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
horizontalalignment='center',
verticalalignment='center',
transform=ax.transAxes)
ax.text(right, 0.5 * (bottom + top), 'centered',
horizontalalignment='center',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, top, 'rotated\nwith newlines',
horizontalalignment='center',
verticalalignment='center',
rotation=45,
transform=ax.transAxes)
plt.axis('off')
plt.show()
I know that question is a bit old but
pipenv --venv
/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
Frank's example confused me a bit - it didn't work in my case because I didn't understand positioning well enough yet. It's important to note that the parent container element needs to have a non-static position (he mentioned this but I overlooked it, and it wasn't in his example).
Here's an example where the child - given padding and a border - uses absolute positioning to fill the parent 100%. The parent uses relative positioning in order to provide a point of reference for the child's position while remaining in the normal flow - the next element "more-content" is not affected:
#box {
position: relative;
height: 300px;
width: 600px;
}
#box p {
position: absolute;
border-style: dashed;
padding: 1em;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
<div id="box">
<p>100% height and width!</p>
</div>
<div id="more-content">
</div>
A useful link for quickly learning CSS positioning
To still be able to scroll this worked for me
if (e.changedTouches.length > 1) e.preventDefault();
I came to this question after writing a one-liner for this purpose, so I share my code in case it helps somebody. Works for a string with only one level depth and possible empty values (but not nil), like:
"{ :key_a => 'value_a', :key_b => 'value_b', :key_c => '' }"
The code is:
the_string = '...'
the_hash = Hash.new
the_string[1..-2].split(/, /).each {|entry| entryMap=entry.split(/=>/); value_str = entryMap[1]; the_hash[entryMap[0].strip[1..-1].to_sym] = value_str.nil? ? "" : value_str.strip[1..-2]}
SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.
Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html
I added the DOCTYPE
directive you see here:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [
<!ENTITY nl "
">
]>
<xsl:stylesheet xmlns:x="http://www.w3.org/2005/02/query-test-XQTSCatalog"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
This allows me to use &nl;
instead of 

to produce a newline in the output. Like other solutions, this is typically placed inside a <xsl:text>
tag.
You should be extend a class from View.OnTouchListener
and handle the onTouch
method by overriding it.
interface SwipeListener {
fun onSwipeLeft()
fun onSwipeRight()
}
class SwipeGestureListener internal constructor(
private val listener: SwipeListener,
private val minDistance: Int = DEFAULT_SWIPE_MIN_DISTANCE
) : View.OnTouchListener {
companion object {
const val DEFAULT_SWIPE_MIN_DISTANCE = 200
}
private var anchorX = 0F
override fun onTouch(view: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
anchorX = event.x
return true
}
MotionEvent.ACTION_UP -> {
if (abs(event.x - anchorX) > minDistance) {
if (event.x > anchorX) {
listener.onSwipeRight()
} else {
listener.onSwipeLeft()
}
}
return true
}
}
return view.performClick()
}
}
You can just easily implement it like this in your Activity
or Fragment
.
class MainActivity : AppCompatActivity(), SwipeListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewGroup.setOnTouchListener(SwipeGestureListener(this))
}
override fun onSwipeLeft() {
Toast.makeText(this, "Swipe Left", Toast.LENGTH_SHORT).show()
}
override fun onSwipeRight() {
Toast.makeText(this, "Swipe Right", Toast.LENGTH_SHORT).show()
}
}
def month_num2abbr(month):
month = int(month)
import calendar
months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
for abbr, month_num in months_abbr.items():
if month_num==month:
return abbr
return False
print(month_num2abbr(7))
You can use CSS gradient - although there are not consistent across browsers so You would have to code it for every one
Like that: CSS3 Transparency + Gradient
Gradient should be more transparent on top or on top right corner (depending on capabilities)
You could write a convenience method:
public PrintStream print(String format, Object... arguments) {
return System.out.format(format, arguments);
}
But as you can see, you've simply just renamed format
(or printf
).
Here's how you could use it:
private void printScores(Player... players) {
for (int i = 0; i < players.length; ++i) {
Player player = players[i];
String name = player.getName();
int score = player.getScore();
// Print name and score followed by a newline
System.out.format("%s: %d%n", name, score);
}
}
// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);
// Output
Abe: 11
Bob: 22
Cal: 33
Dan: 44
Abe: 11
Bob: 22
Cal: 33
Dan: 44
Note there's also the similar System.out.printf
method that behaves the same way, but if you peek at the implementation, printf
just calls format
, so you might as well use format
directly.
Your best bet is to right click > inspect the element.
I am using Bootstrap 4 and none of the suggestions worked until I did this.
Once I found where the relevant code was in the inspect window, I copied and pasted the relevant code that was causing the :focus to be outlined blue and changed it accordingly.
This is the code that worked in my css
.btn.focus, .btn:focus
{
outline: 0;
box-shadow: 0 0 0 0;
}
All the other solutions work for Microsoft Edge (legacy) and on Windows 10 only. As of 2020, it will be discontinued and replaced by Microsoft Edge (Chromium based).
The solution that works with the new Edge on Windows 7, 8 and 10 is :
start msedge URL
Source :
This worked for me.
ssh-agent /bin/sh
ssh-add /path/to/your/key
You can simply add this CSS to your header
<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>
next add this code in place where you want to display a glyph symbol.
<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->
Have fun.
This rule
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
is wrong. It says to create a file named producer.o (with -o producer.o
), but you want to create a file named main
. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
As Shahbaz rightly points out, the gmake professionals would also use $^
which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ $^
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
Although there is the RFC 2965 (Set-Cookie2
, had already obsoleted RFC 2109) that should define the cookie nowadays, most browsers don’t fully support that but just comply to the original specification by Netscape.
There is a distinction between the Domain attribute value and the effective domain: the former is taken from the Set-Cookie
header field and the latter is the interpretation of that attribute value. According to the RFC 2965, the following should apply:
.
it will be added by the client).Having the effective domain it must also domain-match the current requested domain for being set; otherwise the cookie will be revised. The same rule applies for choosing the cookies to be sent in a request.
Mapping this knowledge onto your questions, the following should apply:
Domain=.example.com
will be available for www.example.comDomain=.example.com
will be available for example.comDomain=example.com
will be converted to .example.com
and thus will also be available for www.example.comDomain=example.com
will not be available for anotherexample.comAnd to set and read a cookie for/by www.example.com and example.com, set it for .www.example.com
and .example.com
respectively. But the first (.www.example.com
) will only be accessible for other domains below that domain (e.g. foo.www.example.com or bar.www.example.com) where .example.com
can also be accessed by any other domain below example.com (e.g. foo.example.com or bar.example.com).
My favourite method is using a clearfix class for parent element
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {
display: inline-block;
}
* html .clearfix {
height: 1%;
}
.clearfix {
display: block;
}
To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.
A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.
One way would be to just escape the quotes properly:
<input type="button" value="click" id="mybtn"
onclick="myfunction('/myController/myAction',
'myfuncionOnOK(\'/myController2/myAction2\',
\'myParameter2\');',
'myfuncionOnCancel(\'/myController3/myAction3\',
\'myParameter3\');');">
In this case, though, I think a better way to handle this would be to wrap the two handlers in anonymous functions:
<input type="button" value="click" id="mybtn"
onclick="myfunction('/myController/myAction',
function() { myfuncionOnOK('/myController2/myAction2',
'myParameter2'); },
function() { myfuncionOnCancel('/myController3/myAction3',
'myParameter3'); });">
And then, you could call them from within myfunction
like this:
function myfunction(url, onOK, onCancel)
{
// Do whatever myfunction would normally do...
if (okClicked)
{
onOK();
}
if (cancelClicked)
{
onCancel();
}
}
That's probably not what myfunction
would actually look like, but you get the general idea. The point is, if you use anonymous functions, you have a lot more flexibility, and you keep your code a lot cleaner as well.
In addition to Shane Kms answer, if you've activated Nuget Package Restore, you edit the NuGet.config located in the .nuget-folder as follows:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<repositoryPath>..\..\ExtLibs\Packages</repositoryPath>
</configuration>
Notice the extra "..\", as it backtracks from the .nuget-folder and not the solution folder.
#include <algorithm>
static const size_t v_size = 2000;
int v[v_size];
// Fill the array by values
std::sort(v,v+v_size);
In C++11:
#include <algorithm>
#include <array>
std::array<int, 2000> v;
// Fill the array by values
std::sort(v.begin(),v.end());
You can do this with html5 very easily:
var link = document.createElement('a');
link.href = "/WWW/test.pdf";
link.download = "file_" + new Date() + ".pdf";
link.click();
link.remove()
Re-review the Android Activity Lifecycle reference. There is a nice picture, and the table showing what methods get called. reference Link google
https://developer.android.com/reference/android/app/Activity.html
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.
This version calculates a list of primes square roots and only checks if the list of prime numbers below the square root, and uses a binarysearch in the list to find known primes. I looped through to check the first 1,000,000 primes, and it took about 7 seconds.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
//test();
testMax();
Console.ReadLine();
}
static void testMax()
{
List<int> CheckPrimes = Enumerable.Range(2, 1000000).ToList();
PrimeChecker pc = new PrimeChecker(1000000);
foreach (int i in CheckPrimes)
{
if (pc.isPrime(i))
{
Console.WriteLine(i);
}
}
}
}
public class PrimeChecker{
public List<int> KnownRootPrimesList;
public int HighestKnownPrime = 3;
public PrimeChecker(int Max=1000000){
KnownRootPrimesList = new List<int>();
KnownRootPrimesList.Add(2);
KnownRootPrimesList.Add(3);
isPrime(Max);
}
public bool isPrime(int value)
{
int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value))));
if(srt > HighestKnownPrime)
{
for(int i = HighestKnownPrime + 1; i <= srt; i++)
{
if (i > HighestKnownPrime)
{
if(isPrimeCalculation(i))
{
KnownRootPrimesList.Add(i);
HighestKnownPrime = i;
}
}
}
}
bool isValuePrime = isPrimeCalculation(value);
return(isValuePrime);
}
private bool isPrimeCalculation(int value)
{
if (value < HighestKnownPrime)
{
if (KnownRootPrimesList.BinarySearch(value) > -1)
{
return (true);
}
else
{
return (false);
}
}
int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value))));
bool isPrime = true;
List<int> CheckList = KnownRootPrimesList.ToList();
if (HighestKnownPrime + 1 < srt)
{
CheckList.AddRange(Enumerable.Range(HighestKnownPrime + 1, srt));
}
foreach(int i in CheckList)
{
isPrime = ((value % i) != 0);
if(!isPrime)
{
break;
}
}
return (isPrime);
}
public bool isPrimeStandard(int value)
{
int srt = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(value))));
bool isPrime = true;
List<int> CheckList = Enumerable.Range(2, srt).ToList();
foreach (int i in CheckList)
{
isPrime = ((value % i) != 0);
if (!isPrime)
{
break;
}
}
return (isPrime);
}
}
}
You can solve this by unchecking contextswitchdeadlock from
Debug->Exceptions ... -> Expand MDA node -> uncheck -> contextswitchdeadlock
I just found some issues on FAB and I want to enhance another answer.
So, the issue will come once you set the ripple color (FAB color on pressed) programmatically through setRippleColor
. But, we still have an alternative way to set it, i.e. by calling:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
ColorStateList rippleColor = ContextCompat.getColorStateList(context, R.color.fab_ripple_color);
fab.setBackgroundTintList(rippleColor);
Your project need to has this structure:
/res/color/fab_ripple_color.xml
And the code from fab_ripple_color.xml
is:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/fab_color_pressed" />
<item android:state_focused="true" android:color="@color/fab_color_pressed" />
<item android:color="@color/fab_color_normal"/>
</selector>
Finally, alter your FAB slightly:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_action_add"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
app:fabSize="normal"
app:borderWidth="0dp"
app:elevation="6dp"
app:pressedTranslationZ="12dp"
app:rippleColor="@android:color/transparent"/> <!-- set to transparent color -->
For API level 21 and higher, set margin right and bottom to 24dp:
...
android:layout_marginRight="24dp"
android:layout_marginBottom="24dp" />
As you can see on my FAB xml code above, I set:
...
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
app:elevation="6dp"
app:pressedTranslationZ="12dp"
...
By setting these attributes, you don't need to set layout_marginTop
and layout_marginRight
again (only on pre-Lollipop). Android will place it automatically on the right corned side of the screen, which the same as normal FAB in Android Lollipop.
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
Or, you can use this in CoordinatorLayout
:
android:layout_gravity="end|bottom"
elevation
and 12dp pressedTranslationZ
, according to this guide from Google.It is because by default at the time of this writing , Ionic CLI tool is defaulted to
<preference name="android-targetSdkVersion" value="LATEST_SDK_VERSION"/>
That is the reason why it complains that you did not accept license agreement , but in reality you did not install the SDK packages for that API Level yet alone accept the license.
So what you need to do is either
Changing your SDK version
You can do it manually and even verify it by running
ionic cordova platform add android
the file can be found at your-awesome-app/config.xml
open it and add this line , since its hidden as stated above
<preference name="android-targetSdkVersion" value="24"/>
If you are not sure which API LEVEL Number you are targeting open SDK Manager and look at the API levels (Numbers) available on your machine
Installing Latest SDK Package
You can add the current SDK Packages which the CLI is showing , Which in your case it is 24
Run SDK MANAGER
as Admin
Install the SDK API Packages which you are targeting
How did I know this? I did it this morning and that's how I solved it and now am playing Sticky Bubble on Android to relax a bit.
Happy Deploying!
mvn install:install-file
-Dfile=C:\Users\xxxx\Downloads\lib\ojdbc6.jar
-DgroupId=com.oracle
-DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar
to resolve the ORACLE JAR issue with the Spring Application,
Oracle JDBC ojdbc6 Jar as a Maven Dependency
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>`
We can separate out section of which we need to convert in PDF
For example, if table is in class "pdf-table-wrap"
After this, we need to call html2canvas function combined with jsPDF
following is sample code
var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
onrendered: function(canvas) {
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var imgData = canvas.toDataURL("image/png", 1.0);
var width = canvas.width;
var height = canvas.clientHeight;
pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));
}
});
setTimeout(function() {
//jsPDF code to save file
pdf.save('sample.pdf');
}, 0);
Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/
If we take a look at the source for bytes.__repr__
, it looks as if the b''
is baked into the method.
The most obvious workaround is to manually slice off the b''
from the resulting repr()
:
>>> x = b'\x01\x02\x03\x04'
>>> print(repr(x))
b'\x01\x02\x03\x04'
>>> print(repr(x)[2:-1])
\x01\x02\x03\x04
You can make easily custom textview class :-
So what you need to do first, make Custom textview
class which extended with AppCompatTextView
.
public class CustomTextView extends AppCompatTextView {
private int mFont = FontUtils.FONTS_NORMAL;
boolean fontApplied;
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, context);
}
public CustomTextView(Context context) {
super(context);
init(null, context);
}
protected void init(AttributeSet attrs, Context cxt) {
if (!fontApplied) {
if (attrs != null) {
mFont = attrs.getAttributeIntValue(
"http://schemas.android.com/apk/res-auto", "Lato-Regular.ttf",
-1);
}
Typeface typeface = getTypeface();
int typefaceStyle = Typeface.NORMAL;
if (typeface != null) {
typefaceStyle = typeface.getStyle();
}
if (mFont > FontUtils.FONTS) {
typefaceStyle = mFont;
}
FontUtils.applyFont(this, typefaceStyle);
fontApplied = true;
}
}
}
Now , every time Custom text view call and we will get int value from attribute int fontValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","Lato-Regular.ttf",-1)
.
Or
We can also get getTypeface() from view which we set in our xml (android:textStyle="bold|normal|italic"
). So do what ever you want to do.
Now, we make FontUtils
for set any .ttf font into our view.
public class FontUtils {
public static final int FONTS = 1;
public static final int FONTS_NORMAL = 2;
public static final int FONTS_BOLD = 3;
public static final int FONTS_BOLD1 = 4;
private static Map<String, Typeface> TYPEFACE = new HashMap<String, Typeface>();
static Typeface getFonts(Context context, String name) {
Typeface typeface = TYPEFACE.get(name);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), name);
TYPEFACE.put(name, typeface);
}
return typeface;
}
public static void applyFont(TextView tv, int typefaceStyle) {
Context cxt = tv.getContext();
Typeface typeface;
if(typefaceStyle == Typeface.BOLD_ITALIC) {
typeface = FontUtils.getFonts(cxt, "FaktPro-Normal.ttf");
}else if (typefaceStyle == Typeface.BOLD || typefaceStyle == SD_FONTS_BOLD|| typefaceStyle == FONTS_BOLD1) {
typeface = FontUtils.getFonts(cxt, "FaktPro-SemiBold.ttf");
} else if (typefaceStyle == Typeface.ITALIC) {
typeface = FontUtils.getFonts(cxt, "FaktPro-Thin.ttf");
} else {
typeface = FontUtils.getFonts(cxt, "FaktPro-Normal.ttf");
}
if (typeface != null) {
tv.setTypeface(typeface);
}
}
}
Another relevant environment variable is:
So, on a 64-bit machine running in 32-bit (WOW64) mode:
- echo %programfiles% ==> C:\Program Files (x86)
- echo %programfiles(x86)% ==> C:\Program Files (x86)
- echo %ProgramW6432% ==> C:\Program Files
From Wikipedia:
The %ProgramFiles% variable points to the Program Files directory, which stores all the installed programs of Windows and others. The default on English-language systems is "C:\Program Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and %ProgramW6432%, which defaults to "C:\Program Files". The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).
Reference: http://en.wikipedia.org/wiki/Environment_variable
I would recomment Pluralsight's tool for creating self-signed-certs: http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net
Make your cert as a .pfx and import it into IIS. And add it as a trusted root cert authority.
Here is an overlay using a pseudo-element (eg: no need to add more markup to do it)
.box {_x000D_
background: 0 0 url(http://ianfarb.com/wp-content/uploads/2013/10/nicholas-hodag.jpg);_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
content: "";_x000D_
display: block;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: rgba(0, 0, 0, 0.4);_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
This function gives you all the diffs (and what stayed the same) based on the dictionary keys only. It also highlights some nice Dict comprehension, Set operations and python 3.6 type annotations :)
from typing import Dict, Any, Tuple
def get_dict_diffs(a: Dict[str, Any], b: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
added_to_b_dict: Dict[str, Any] = {k: b[k] for k in set(b) - set(a)}
removed_from_a_dict: Dict[str, Any] = {k: a[k] for k in set(a) - set(b)}
common_dict_a: Dict[str, Any] = {k: a[k] for k in set(a) & set(b)}
common_dict_b: Dict[str, Any] = {k: b[k] for k in set(a) & set(b)}
return added_to_b_dict, removed_from_a_dict, common_dict_a, common_dict_b
If you want to compare the dictionary values:
values_in_b_not_a_dict = {k : b[k] for k, _ in set(b.items()) - set(a.items())}
Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.
write.csv(Data_output, "output.csv", row.names = F, quote = F)
Do it like this
if (typeof $(this).attr("checked") == "undefined" )
// To check if checkbox is checked
if( $(this).attr("checked")=="checked")
Try remove_missing
instead with vars = the_variable
. It is very important that you set the vars
argument, otherwise remove_missing
will remove all rows that contain an NA
in any column!! Setting na.rm = TRUE
will suppress the warning message.
ggplot(data = remove_missing(MyData, na.rm = TRUE, vars = the_variable),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) +
geom_bar(stat="bin")
You are not indicating what to include in the archive.
Go one level outside your folder and try:
sudo tar -cvjSf folder.tar.bz2 folder
Or from the same folder try
sudo tar -cvjSf folder.tar.bz2 *
Cheers!
just use this
element.getAttributeNode("class").value += " antherClass";
take care about Space to avoid mix old class with new class
Global variables are almost never a good thing (maybe an exception or two out there...). In this case, it looks like you really just want to export your "name" variable. E.g.,
// module.js
var name = "foobar";
// export it
exports.name = name;
Then, in main.js...
//main.js
// get a reference to your required module
var myModule = require('./module');
// name is a member of myModule due to the export above
var name = myModule.name;
Jonas's answer is good, but I had to modify it slightly to get every piece of text on the screen to change:
set(gca,'FontSize',30,'fontWeight','bold')
set(findall(gcf,'type','text'),'FontSize',30,'fontWeight','bold')
I did a very straightforward solution by manipulating the output of the .gitignore statement with sed:
cat .gitignore | sed '/^#.*/ d' | sed '/^\s*$/ d' | sed 's/^/git rm -r /' | bash
Explanation:
Try dropping all the firewall, the one from your VM and the one from you Laptop, or add the rule in your firewall where you can ping
None of the above solutions seem to work if the width/height is less than the line resolution of quality you select. For example, the following doesn't work for me in Chrome:
<iframe width="720" height="480" src="//youtube.com/embed/hUezoHa1ZF4?autoplay=true&rel=0&vq=hd720" frameborder="0" allowfullscreen></iframe>
I want to show the high quality video, but not use up 1280 x 720 pixels on the webpage.
When I go to youtube itself, playing 720p video in a 720x480 window looks better than 480p at the same size. I want to play 720p in a 720x480 window (downsampled better quality). There is no good solution yet afaik.
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
If you are using Angular 2 (apparently it also works for Angular 4 too), you can use the following to round to two decimal places{{ exampleNumber | number : '1.2-2' }}
, as in:
<ion-input value="{{ exampleNumber | number : '1.2-2' }}"></ion-input>
BREAKDOWN
'1.2-2'
means {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
:
This worked for me, no delayed expansion necessary:
@echo off
(
echo ^<html^>
echo ^<body^>
echo Hello
echo ^</body^>
echo ^</html^>
)
pause
It writes output like this:
<html>
<body>
Hello
</body>
</html>
Press any key to continue . . .
You have to use execute immediate (dynamic sql).
DECLARE
v_owner varchar2(40);
v_table_name varchar2(40);
cursor get_tables is
select distinct table_name,user
from user_tables
where lower(user) = 'schema_name';
begin
open get_tables;
loop
fetch get_tables into v_table_name,v_owner;
EXIT WHEN get_tables%NOTFOUND;
execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'') FROM ' || v_table_name;
end loop;
CLOSE get_tables;
END;
It is simpler than I thought it would be.
To set the font size of the x-axis ticks:
x_ticks=['x tick 1','x tick 2','x tick 3']
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
To do it for the y-axis ticks:
y_ticks=['y tick 1','y tick 2','y tick 3']
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)
The arguments rotation
and fontsize
can easily control what I was after.
Reference: http://matplotlib.org/api/axes_api.html
How about the following?
0[xX][0-9a-fA-F]+
Matches expression starting with a 0, following by either a lower or uppercase x, followed by one or more characters in the ranges 0-9, or a-f, or A-F
As per https://stackoverflow.com/a/33859341/446250, having internet connection sharing enabled for my ethernet adapter ended up causing this problem for me. Disabling the sharing fixed the problem
For me it wasn't an outlet. I solved the problem by going to the error And reading what it said. (Also Noob..)
This was the error:
Just scroll up in the output and the error will be revealed.
Table1 Table2
_______ _________
1 2
2 2
3 5
4 6
SELECT Table1.Id, Table2.Id FROM Table1 LEFT OUTER JOIN Table2 ON Table1.Id=Table2.Id
Results:
1,null
2,2
2,2
3,null
4,null
For my suggestion, please read the last section: “When to use SO_LINGER with timeout 0”.
Before we come to that a little lecture about:
TIME_WAIT
FIN
, ACK
and RST
The normal TCP termination sequence looks like this (simplified):
We have two peers: A and B
close()
FIN
to BFIN_WAIT_1
stateFIN
ACK
to ACLOSE_WAIT
stateACK
FIN_WAIT_2
stateclose()
FIN
to ALAST_ACK
stateFIN
ACK
to BTIME_WAIT
stateACK
CLOSED
state – i.e. is removed from the socket tablesSo the peer that initiates the termination – i.e. calls close()
first – will end up in the TIME_WAIT
state.
To understand why the TIME_WAIT
state is our friend, please read section 2.7 in "UNIX Network Programming" third edition by Stevens et al (page 43).
However, it can be a problem with lots of sockets in TIME_WAIT
state on a server as it could eventually prevent new connections from being accepted.
To work around this problem, I have seen many suggesting to set the SO_LINGER socket option with timeout 0 before calling close()
. However, this is a bad solution as it causes the TCP connection to be terminated with an error.
Instead, design your application protocol so the connection termination is always initiated from the client side. If the client always knows when it has read all remaining data it can initiate the termination sequence. As an example, a browser knows from the Content-Length
HTTP header when it has read all data and can initiate the close. (I know that in HTTP 1.1 it will keep it open for a while for a possible reuse, and then close it.)
If the server needs to close the connection, design the application protocol so the server asks the client to call close()
.
Again, according to "UNIX Network Programming" third edition page 202-203, setting SO_LINGER
with timeout 0 prior to calling close()
will cause the normal termination sequence not to be initiated.
Instead, the peer setting this option and calling close()
will send a RST
(connection reset) which indicates an error condition and this is how it will be perceived at the other end. You will typically see errors like "Connection reset by peer".
Therefore, in the normal situation it is a really bad idea to set SO_LINGER
with timeout 0 prior to calling close()
– from now on called abortive close – in a server application.
However, certain situation warrants doing so anyway:
CLOSE_WAIT
or ending up in the TIME_WAIT
state.TIME_WAIT
(when calling close()
from the server end) as this might prevent the server from getting available ports for new client connections after being restarted.CLOSE_WAIT
trying to deliver data to a stuck terminal port, but would properly reset the stuck port if it got an RST
to discard the pending data."I would recommend this long article which I believe gives a very good answer to your question.
Perhaps setOnClickListener(null)
?
def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
One other direction--just unpack the MSI file and get the goodies that way. Saves you from the eventual uninstall . . .
I'm not 100% sure that I understand your question, so tell me if I'm wrong.
If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.
Then, you should do the following:
convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate
use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)
when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both
For example:
inline int fromJByte(jbyte pixel) {
// cast to unsigned char re-interprets values as 0-255
// cast to int will make intermediate calculations safer
return static_cast<int>(static_cast<unsigned char>(pixel));
}
inline jbyte fromInt(int pixel) {
if(pixel < 0)
pixel = 0;
if(pixel > 255)
pixel = 255;
return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}
jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);
With HTML5 specification... It is now possible to put a block-level element inside of an inline element. So now it's perfectly appropriate to put a 'div' or 'h1' inside of an 'a' element.
The marked answer seems outdated and it won't work.
Facebook now only gives unique ID related to app which isn't equal to userId and profileUrl and username will come out to be empty.
Doing me?fields=id,name,links
is also depreciated after Graph Version 2.4
The only option now is to request for user_links permission from your developer console.
and the pass it in scope when doing facebook login
scope: ['user_link'] }
or by doing an api call
By their very nature, references can only be set at the time they are created; i.e., the following two lines have very different effects:
int & A = B; // makes A an alias for B
A = C; // assigns value of C to B.
Futher, this is illegal:
int & D; // must be set to a int variable.
However, when you create a vector, there is no way to assign values to it's items at creation. You are essentially just making a whole bunch of the last example.
Matthew's supremely efficient script updated to use the dm_exec_sessions DMV, replacing the deprecated sysprocesses system table:
USE [master];
GO
DECLARE @Kill VARCHAR(8000) = '';
SELECT
@Kill = @Kill + 'kill ' + CONVERT(VARCHAR(5), session_id) + ';'
FROM
sys.dm_exec_sessions
WHERE
database_id = DB_ID('<YourDB>');
EXEC sys.sp_executesql @Kill;
Alternative using WHILE loop (if you want to process any other operations per execution):
USE [master];
GO
DECLARE @DatabaseID SMALLINT = DB_ID(N'<YourDB>');
DECLARE @SQL NVARCHAR(10);
WHILE EXISTS ( SELECT
1
FROM
sys.dm_exec_sessions
WHERE
database_id = @DatabaseID )
BEGIN;
SET @SQL = (
SELECT TOP 1
N'kill ' + CAST(session_id AS NVARCHAR(5)) + ';'
FROM
sys.dm_exec_sessions
WHERE
database_id = @DatabaseID
);
EXEC sys.sp_executesql @SQL;
END;
Search your local system's bash man page for ^INVOCATION for information on which file is going to be read at startup.
man bash
/^INVOCATION
Also in the FILES section,
~/.bash_profile
The personal initialization file, executed for login shells
~/.bashrc
The individual per-interactive-shell startup file
Add your script to the proper file. Make sure the script is in the $PATH, or use the absolute path to the script file.
Copy and paste this xml to show as a Dropdown and change your Dropdown color
<?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:background="@drawable/red">
<Spinner android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dropDownWidth="fill_parent"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"
/>
</LinearLayout>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/linearLayout1"
android:layout_alignRight="@+id/linearLayout1"
android:layout_below="@+id/linearLayout1"
android:layout_marginTop="25dp"
android:background="@drawable/red"
android:ems="10"
android:hint="enter card number" >
<requestFocus />
</EditText>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/editText1"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="33dp"
android:orientation="horizontal"
android:background="@drawable/red">
<Spinner
android:id="@+id/spinner3"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"
/>
<Spinner
android:id="@+id/spinner2"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"
/>
<EditText
android:id="@+id/editText2"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="0.18"
android:ems="10"
android:hint="enter cvv" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2"
android:layout_marginTop="26dp"
android:orientation="vertical"
android:background="@drawable/red" >
</LinearLayout>
<Spinner
android:id="@+id/spinner4"
android:layout_width="15dp"
android:layout_height="18dp"
android:layout_alignBottom="@+id/linearLayout3"
android:layout_alignLeft="@+id/linearLayout3"
android:layout_alignRight="@+id/linearLayout3"
android:layout_alignTop="@+id/linearLayout3"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/linearLayout3"
android:layout_marginTop="18dp"
android:text="Add Amount"
android:background="@drawable/buttonsty"/>
I wrote some test code to check JQueryUI drag/drop. The example shows how to drag an element from a container and drop it to another container.
Markup-
<div class="row">
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Panel 1</h1>
</div>
<div id="container1" class="panel-body box-container">
<div itemid="itm-1" class="btn btn-default box-item">Item 1</div>
<div itemid="itm-2" class="btn btn-default box-item">Item 2</div>
<div itemid="itm-3" class="btn btn-default box-item">Item 3</div>
<div itemid="itm-4" class="btn btn-default box-item">Item 4</div>
<div itemid="itm-5" class="btn btn-default box-item">Item 5</div>
</div>
</div>
</div>
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Panel 2</h1>
</div>
<div id="container2" class="panel-body box-container"></div>
</div>
</div>
</div>
JQuery codes-
$(document).ready(function() {
$('.box-item').draggable({
cursor: 'move',
helper: "clone"
});
$("#container1").droppable({
drop: function(event, ui) {
var itemid = $(event.originalEvent.toElement).attr("itemid");
$('.box-item').each(function() {
if ($(this).attr("itemid") === itemid) {
$(this).appendTo("#container1");
}
});
}
});
$("#container2").droppable({
drop: function(event, ui) {
var itemid = $(event.originalEvent.toElement).attr("itemid");
$('.box-item').each(function() {
if ($(this).attr("itemid") === itemid) {
$(this).appendTo("#container2");
}
});
}
});
});
CSS-
.box-container {
height: 200px;
}
.box-item {
width: 100%;
z-index: 1000
}
Check the plunker JQuery Drag Drop
I was getting this when streaming to ElasticSearch from a Lambda function in AWS. Smashed my head a against a wall trying to figure it out. In the end when setting the request.headers['Host']
I was adding in the https://
to the domain for ES - changing this to [es-domain-name].eu-west-1.es.amazonaws.com
(without https://) worked straight away. Below is the code I used to get it working, hopefully save anyone else smashing their head against a wall...
import path from 'path';
import AWS from 'aws-sdk';
const { region, esEndpoint } = process.env;
const endpoint = new AWS.Endpoint(esEndpoint);
const httpClient = new AWS.HttpClient();
const credentials = new AWS.EnvironmentCredentials('AWS');
/**
* Sends a request to Elasticsearch
*
* @param {string} httpMethod - The HTTP method, e.g. 'GET', 'PUT', 'DELETE', etc
* @param {string} requestPath - The HTTP path (relative to the Elasticsearch domain), e.g. '.kibana'
* @param {string} [payload] - An optional JavaScript object that will be serialized to the HTTP request body
* @returns {Promise} Promise - object with the result of the HTTP response
*/
export function sendRequest ({ httpMethod, requestPath, payload }) {
const request = new AWS.HttpRequest(endpoint, region);
request.method = httpMethod;
request.path = path.join(request.path, requestPath);
request.body = payload;
request.headers['Content-Type'] = 'application/json';
request.headers['Host'] = '[es-domain-name].eu-west-1.es.amazonaws.com';
request.headers['Content-Length'] = Buffer.byteLength(request.body);
const signer = new AWS.Signers.V4(request, 'es');
signer.addAuthorization(credentials, new Date());
return new Promise((resolve, reject) => {
httpClient.handleRequest(
request,
null,
response => {
const { statusCode, statusMessage, headers } = response;
let body = '';
response.on('data', chunk => {
body += chunk;
});
response.on('end', () => {
const data = {
statusCode,
statusMessage,
headers
};
if (body) {
data.body = JSON.parse(body);
}
resolve(data);
});
},
err => {
reject(err);
}
);
});
}
If you installed the MySQL 5 package with MacPorts:
sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql.plist
Or
sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql5-devel.plist
if you installed the mysql5-devel
package.
I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).
So I modified Stephan Muller's answer slightly:
A datalist with non-unique values:
<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
<option value="42">The answer</option>
<option value="43">The answer</option>
<option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
When the user selects an option, the browser replaces input.value
with the value
of the datalist
option instead of the innerText
.
The following code then checks for an option
with that value
, pushes that into the hidden field and replaces the input.value
with the innerText
.
document.querySelector('#answerInput').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');
if (options.length > 0) {
hiddenInput.value = input.value;
input.value = options[0].innerText;
}
});
As a consequence the user sees whatever the option's innerText
says, but the unique id from option.value
is available upon form submit.
Demo jsFiddle
With java 8 you can try this:
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class JSONUtil {
public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
String content = new String(Files.readAllBytes(Paths.get(filename)));
return new JSONObject(content);
}
public static void main(String[] args) throws IOException, JSONException {
String filename = "path/to/file/abc.json";
JSONObject jsonObject = parseJSONFile(filename);
//do anything you want with jsonObject
}
}
Andrew Whitaker's answer is true, but you can use any expression for any part.
Just remember the second (middle) expression should evaluate so it can be compared to a boolean true
or false
.
When I use a for
loop, I think of it as
for (var i = 0; i < 10; ++i) {
/* expression */
}
as being
var i = 0;
while( i < 10 ) {
/* expression */
++i;
}
I just changed the .htaccess file contents and as shown in the following links answer. And tried refreshing the page (which didn't work, and couldn't find the request to my controller) it worked.
Then just because of my doubt I undone the changes I did to my .htaccess inside my public_html folder back to original .htaccess content. So it's now as follows (which is originally it was):
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]
And now also it works.
Hint: Seems like before the Rewrite Rules haven't been clearly setup within the Server context.
My file structure is as follows:
/
|- gheapp
| |- application
| L- system
|
|- public_html
| |- .htaccess
| L- index.php
And in the index.php
I have set up the following paths to the system and the application:
$system_path = '../gheapp/system';
$application_folder = '../gheapp/application';
Note: by doing so, our application source code becomes hidden to the public at first.
Please, if you guys find anything wrong with my answer, comment and re-correct me!
Hope beginners would find this answer helpful.
Thanks!
This worked for me:
DECLARE @SQL NVARCHAR(4000)
DECLARE @tbl Table (
Id int,
Account varchar(50),
Amount int
)
-- Lots of code to Create my dynamic sql statement
insert into @tbl EXEC sp_executesql @SQL
select * from @tbl
No. Regular expressions in Python are handled by the re
module.
article = re.sub(r'(?is)</html>.+', '</html>', article)
In general:
text_after = re.sub(regex_search_term, regex_replacement, text_before)
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));
This will work well.
Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt
). You can check where you are spooling by issuing spool
command.
Instead a format such as yours, use ISO 8601 standard formats for exchanging date-time values as text.
The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
Your IST
could mean Iceland Standard Time, India Standard Time, Ireland Standard Time, or others. The java.time classes are left to merely guessing, as there is no logical solution to this ambiguity.
The modern approach uses the java.time classes.
Define a formatting pattern to match your input strings.
String input = "Sat Jun 01 12:53:10 IST 2013";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
zdt.toString(): 2013-06-01T12:53:10Z[Atlantic/Reykjavik]
If your input was not intended for Iceland, you should pre-parse the string to adjust to a proper time zone name. For example, if you are certain the input was intended for India, change IST
to Asia/Kolkata
.
String input = "Sat Jun 01 12:53:10 IST 2013".replace( "IST" , "Asia/Kolkata" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
zdt.toString(): 2013-06-01T12:53:10+05:30[Asia/Kolkata]
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
There are a variety of OCR libraries out there. However, my experience is that the major commercial implementations, ABBYY, Omnipage, and ReadIris, far outdo the open-source or other minor implementations. These commercial libraries are not primarily designed to work with Java, though of course it is possible.
Of course, if your interest is to learn the code, the open-source implementations will do the trick.
Instead of using this in your current class setClassRoomName("aClassName");
you have to use classroom.setClassRoomName("aClassName");
You have to add the class' and at a point like
yourClassNameWhereTheMethodIs.theMethodsName();
I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.
By default, a grid item cannot be smaller than the size of its content.
Grid items have an initial size of min-width: auto
and min-height: auto
.
You can override this behavior by setting grid items to min-width: 0
, min-height: 0
or overflow
with any value other than visible
.
From the spec:
6.6. Automatic Minimum Size of Grid Items
To provide a more reasonable default minimum size for grid items, this specification defines that the
auto
value ofmin-width
/min-height
also applies an automatic minimum size in the specified axis to grid items whoseoverflow
isvisible
. (The effect is analogous to the automatic minimum size imposed on flex items.)
Here's a more detailed explanation covering flex items, but it applies to grid items, as well:
This post also covers potential problems with nested containers and known rendering differences among major browsers.
To fix your layout, make these adjustments to your code:
.month-grid {
display: grid;
grid-template: repeat(6, 1fr) / repeat(7, 1fr);
background: #fff;
grid-gap: 2px;
min-height: 0; /* NEW */
min-width: 0; /* NEW; needed for Firefox */
}
.day-item {
padding: 10px;
background: #DFE7E7;
overflow: hidden; /* NEW */
min-width: 0; /* NEW; needed for Firefox */
}
1fr
vs minmax(0, 1fr)
The solution above operates at the grid item level. For a container level solution, see this post:
I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.
Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.
timing's
answer is nice thinked but no more working, so I have updated the name of the js file to 'adsense' from 'ads' and it is working back like a charm!
Here is the code, maybe this wil help someone:
<html>
<head>
<script src="/adsense.js"></script>
</head>
<body>
<script>
if( window.adblockDetecter === undefined ){
// Do anithing, adblocker detected!
alert('Adblocker Detected!');}
</script>
</body>
</html>
In the Js file put just this line: var adblockDetecter = true;
Its a late answer but I think it will help. Use this method:
protected void zoomMapInitial(LatLng finalPlace, LatLng currenLoc) {
try {
int padding = 200; // Space (in px) between bounding box edges and view edges (applied to all four sides of the bounding box)
LatLngBounds.Builder bc = new LatLngBounds.Builder();
bc.include(finalPlace);
bc.include(currenLoc);
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bc.build(), padding));
} catch (Exception e) {
e.printStackTrace();
}
}
Use this method after loading the map. Cheers!
Just another clean way:
function validateIp($var_ip){
$ip = trim($var_ip);
return (!empty($ip) &&
$ip != '::1' &&
$ip != '127.0.0.1' &&
filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
? $ip : false;
}
function getClientIp() {
$ip = @$this->validateIp($_SERVER['HTTP_CLIENT_IP']) ?:
@$this->validateIp($_SERVER['HTTP_X_FORWARDED_FOR']) ?:
@$this->validateIp($_SERVER['HTTP_X_FORWARDED']) ?:
@$this->validateIp($_SERVER['HTTP_FORWARDED_FOR']) ?:
@$this->validateIp($_SERVER['HTTP_FORWARDED']) ?:
@$this->validateIp($_SERVER['REMOTE_ADDR']) ?:
'LOCAL OR UNKNOWN ACCESS';
return $ip;
}
I'll just leave it here. Whoever has a lot of (CPU) time to spare, feel free to experiment :) Also, if you have mastered some fork-join-fu to make this thing burn all CPU cores (just threads are boring, right?), please share your code. I would greatly appreciate it.
public static void main(String[] args) {
long time = System.currentTimeMillis();
generate("stack");
generate("over");
generate("flow");
generate("rulez");
System.out.println("Took " + (System.currentTimeMillis() - time) + " ms");
}
private static void generate(String goal) {
long[] seed = generateSeed(goal, Long.MIN_VALUE, Long.MAX_VALUE);
System.out.println(seed[0]);
System.out.println(randomString(seed[0], (char) seed[1]));
}
public static long[] generateSeed(String goal, long start, long finish) {
char[] input = goal.toCharArray();
char[] pool = new char[input.length];
label:
for (long seed = start; seed < finish; seed++) {
Random random = new Random(seed);
for (int i = 0; i < input.length; i++)
pool[i] = (char) random.nextInt(27);
if (random.nextInt(27) == 0) {
int base = input[0] - pool[0];
for (int i = 1; i < input.length; i++) {
if (input[i] - pool[i] != base)
continue label;
}
return new long[]{seed, base};
}
}
throw new NoSuchElementException("Sorry :/");
}
public static String randomString(long i, char base) {
System.out.println("Using base: '" + base + "'");
Random ran = new Random(i);
StringBuilder sb = new StringBuilder();
for (int n = 0; ; n++) {
int k = ran.nextInt(27);
if (k == 0)
break;
sb.append((char) (base + k));
}
return sb.toString();
}
Output:
-9223372036808280701
Using base: 'Z'
stack
-9223372036853943469
Using base: 'b'
over
-9223372036852834412
Using base: 'e'
flow
-9223372036838149518
Using base: 'd'
rulez
Took 7087 ms
The JDK provides
Collections.unmodifiableXXX
methods, but in our opinion, these can be unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.
There's a --no-cache
option:
docker build --no-cache -t u12_core -f u12_core .
In older versions of Docker you needed to pass --no-cache=true
, but this is no longer the case.
This is a simple program to capture an image from using a default camera. Also, It can Detect a human face.
import cv2
import sys
import logging as log
import datetime as dt
from time import sleep
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('s'):
check, frame = video_capture.read()
cv2.imshow("Capturing", frame)
cv2.imwrite(filename='saved_img.jpg', img=frame)
video_capture.release()
img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
img_new = cv2.imshow("Captured Image", img_new)
cv2.waitKey(1650)
print("Image Saved")
print("Program End")
cv2.destroyAllWindows()
break
elif cv2.waitKey(1) & 0xFF == ord('q'):
print("Turning off camera.")
video_capture.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
# Display the resulting frame
cv2.imshow('Video', frame)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
output
Also, You can check out my GitHub code
As per the django documentation 2.2 you can use:
To get all fields: Model._meta.get_fields()
To get an individual field: Model._meta.get_field('field name')
ex. Session._meta.get_field('expire_date')
let's do try and checkout For Swift 3...
UIView.transition(with: mysuperview, duration: 0.75, options:UIViewAnimationOptions.transitionFlipFromRight , animations: {
myview.removeFromSuperview()
}, completion: nil)
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
With Bootstrap 4, there is a css class specifically for this. The below will center row content:
<div class="row justify-content-center">
...inner divs and content...
</div>
See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.
If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ"));
That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.
Usually to use the library you need to install the dev version.
Try
sudo apt-get install libusb-1.0-0-dev
I'll answer my own question for the first time. I found an example straight from the source. Please forgive the poor indentation. I wasn't sure how to indent properly when copying and pasting. The code comes straight from Express multipart/form-data
example on GitHub.
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');
/**
* Module dependencies.
*/
var express = require('../../lib/express')
, form = require('connect-form');
var app = express.createServer(
// connect-form (http://github.com/visionmedia/connect-form)
// middleware uses the formidable middleware to parse urlencoded
// and multipart form data
form({ keepExtensions: true })
);
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// connect-form adds the req.form object
// we can (optionally) define onComplete, passing
// the exception (if any) fields parsed, and files parsed
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
console.log('\nuploaded %s to %s'
, files.image.filename
, files.image.path);
res.redirect('back');
}
});
// We can add listeners for several form
// events such as "progress"
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
app.listen(3000);
console.log('Express app started on port 3000');
I would do it like this:
int totalMinutes = (int)(end - start).TotalMinutes;
Use: INT(11)
.
MySQL indexes will be able to parse through an int list fastest.
Use: BINARY(x)
, or BLOB(x)
.
You can store security tokens, etc., as hex directly in BINARY(x) or BLOB(x). To retrieve from binary
-type, use SELECT HEX(field)...
or SELECT ... WHERE field = UNHEX("ABCD....")
.
Use: DATETIME
, DATE
, or TIME
.
Always use DATETIME
if you need to store both date and time (instead of a pair of fields), as a DATETIME
indexing is more amenable to date-comparisons in MySQL.
Use: BIT(1)
(MySQL 8-only.) Otherwise, use BOOLEAN(1)
.
BOOLEAN
is actually just an alias of TINYINT(1)
, which actually stores 0 to 255 (not exactly a true/false, is it?).
Use: INT(11)
.
VARCHAR or other types of fields won't work with the SUM()
, etc., functions.
Use: TEXT.
Max limit is 65,535.
Use: MEDIUMTEXT.
Max limit is 16,777,215.
Use: LONGTEXT.
Max limit is 4,294,967,295.
Use : VARCHAR(255)
.
UTF-8 characters can take up three characters per visible character, and some cultures do not distinguish firstname and lastname. Additionally, cultures may have disagreements about which name is first and which name is last. You should name these fields Person.GivenName
and Person.FamilyName
.
Use : VARCHAR(256)
.
The definition of an e-mail path is set in RFC821 in 1982. The maximum limit of an e-mail was set by RFC2821 in 2001, and these limits were kept unchanged by RFC5321 in 2008. (See the section: 4.5.3.1. Size Limits and Minimums.) RFC3696, published 2004, mistakenly cites the email address limit as 320
characters, but this was an "info-only" RFC that explicitly "defines no standards" according to its intro, so disregard it.
Use: VARCHAR(255)
.
You never know when the phone number will be in the form of "1800...", or "1-800", or "1-(800)", or if it will end with "ext. 42", or "ask for susan".
Use: VARCHAR(10)
.
You'll get data like 12345
or 12345-6789
. Use validation to cleanse this input.
Use: VARCHAR(2000)
.
Official standards support URL's much longer than this, but few modern browsers support URL's over 2,000 characters. See this SO answer: What is the maximum length of a URL in different browsers?
Use: DECIMAL(11,2)
.
It goes up to 11.
Yes it is true.
If you create two instance of your class
Test t1 = new Test();
Test t2 = new Test();
Then t1.foo and t2.foo both synchronize on the same static object and hence block each other.
This if clause easily checks if location services are available in my opinion:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
//All location services are disabled
}
Aircoded (but tested on this fiddle)
(function($) {
function startTrigger(e) {
var $elem = $(this);
$elem.data('mouseheld_timeout', setTimeout(function() {
$elem.trigger('mouseheld');
}, e.data));
}
function stopTrigger() {
var $elem = $(this);
clearTimeout($elem.data('mouseheld_timeout'));
}
var mouseheld = $.event.special.mouseheld = {
setup: function(data) {
// the first binding of a mouseheld event on an element will trigger this
// lets bind our event handlers
var $this = $(this);
$this.bind('mousedown', +data || mouseheld.time, startTrigger);
$this.bind('mouseleave mouseup', stopTrigger);
},
teardown: function() {
var $this = $(this);
$this.unbind('mousedown', startTrigger);
$this.unbind('mouseleave mouseup', stopTrigger);
},
time: 750 // default to 750ms
};
})(jQuery);
// usage
$("div").bind('mouseheld', function(e) {
console.log('Held', e);
})
Packet
A packet is the unit of data that is routed between an origin and a destination on the Internet or any other packet-switched network. When any file (e-mail message, HTML file, Graphics Interchange Format file, Uniform Resource Locator request, and so forth) is sent from one place to another on the Internet, the Transmission Control Protocol (TCP) layer of TCP/IP divides the file into "chunks" of an efficient size for routing. Each of these packets is separately numbered and includes the Internet address of the destination. The individual packets for a given file may travel different routes through the Internet. When they have all arrived, they are reassembled into the original file (by the TCP layer at the receiving end).
Frame
1) In telecommunications, a frame is data that is transmitted between network points as a unit complete with addressing and necessary protocol control information. A frame is usually transmitted serial bit by bit and contains a header field and a trailer field that "frame" the data. (Some control frames contain no data.)
2) In time-division multiplexing (TDM), a frame is a complete cycle of events within the time division period.
3) In film and video recording and playback, a frame is a single image in a sequence of images that are recorded and played back.
4) In computer video display technology, a frame is the image that is sent to the display image rendering devices. It is continuously updated or refreshed from a frame buffer, a highly accessible part of video RAM.
5) In artificial intelligence (AI) applications, a frame is a set of data with information about a particular object, process, or image. An example is the iris-print visual recognition system used to identify users of certain bank automated teller machines. This system compares the frame of data for a potential user with the frames in its database of authorized users.
I know that its bit old Q but if u get here by searching a solution so i got a nice one via jquery
jQuery('a[target^="_new"]').click(function() {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
});
it will open all the <a target="_new">
in a new window
EDIT:
1st, I did some little changes in the original code now it open the new window perfectly followed the user screen ratio (for landscape desktops)
but, I would like to recommend you to use the following code that open the link in new tab if you in mobile (thanks to zvona answer in other question):
jQuery('a[target^="_new"]').click(function() {
return openWindow(this.href);
}
function openWindow(url) {
if (window.innerWidth <= 640) {
// if width is smaller then 640px, create a temporary a elm that will open the link in new tab
var a = document.createElement('a');
a.setAttribute("href", url);
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
}
else {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
return false;
}
The jQuery UI sortable plugin provides drag-and-drop reordering. A save button can extract the IDs of each item to create a comma-delimited string of those IDs, added to a hidden textbox. The textbox is returned to the server using an async postback.
This fiddle example reorders table elements, but does not save them to a database.
The sortable plugin takes one line of code to turn any list into a sortable list. If you care to use them, it also provides CSS and images to provide a visual impact to sortable list (see the example that I linked to). Developers, however, must provide code to retrieve items in their new order. I embed unique IDs of each item in the list as an HTML attribute and then retrieve those IDs via jQuery.
For example:
// ----- code executed when the document loads
$(function() {
wireReorderList();
});
function wireReorderList() {
$("#reorderExampleItems").sortable();
$("#reorderExampleItems").disableSelection();
}
function saveOrderClick() {
// ----- Retrieve the li items inside our sortable list
var items = $("#reorderExampleItems li");
var linkIDs = [items.size()];
var index = 0;
// ----- Iterate through each li, extracting the ID embedded as an attribute
items.each(
function(intIndex) {
linkIDs[index] = $(this).attr("ExampleItemID");
index++;
});
$get("<%=txtExampleItemsOrder.ClientID %>").value = linkIDs.join(",");
}
There is no static keyword in kotlin. kotlin docs recommends to use package-level functions if u want to follow DRY. Create a file with .kt extension and put your method in it.
package p
fun m(){
//fun body
}
after compilation m will have a signature of public static final void
and
import p.m
?
As of April 2018, Chrome's autoplay policies changed:
"Chrome's autoplay policies are simple:
Autoplay with sound is allowed if:
Also
Chrome's developer site has more information, including some programming examples, which can be found here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
The debugger should automatically attach to the browser with Visual Studio 2012. You can use the debugger
keyword to halt at a certain point in the application or use the breakpoints
directly inside VS.
You can also detatch the default debugger in Visual Studio and use the Developer Tools which come pre loaded with Internet Explorer or FireBug etc.
To do this goto Visual Studio
-> Debug
-> Detatch All
and then click Start debugging in Internet Explorer
. You can then set breakpoints at this level.
This is the new suggested method.
WebRequest.GetSystemWebProxy();
You should be able to attach an event handler to the onchange event of the input and have that call a function to set the text in your span.
<script type="text/javascript">
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
});
</script>
You may want to add IDs to your input and span so you can select based on those to be specific to the elements you are concerned with and not other file inputs or spans in the DOM.
brew install python3
create alias in your shell profile
alias pip3="python3 -m pip"
in my .zshrc
? ~ pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)
Since you already have Android Studio installed, and require the environment variable ANDROID_HOME
to be set, the easy way to do this is to add %ANDROID_HOME%\platform-tools
to your path.
You need something like this:
foreach(DataColumn c in dr.Table.Columns)
{
MessageBox.Show(c.ColumnName);
}
Currently, Macports has many more packages (~18.6 K) than there are Homebrew formulae (~3.1K), owing to its maturity. Homebrew is slowly catching up though.
Macport packages tend to be maintained by a single person.
Macports can keep multiple versions of packages around, and you can enable or disable them to test things out. Sometimes this list can get corrupted and you have to manually edit it to get things back in order, although this is not too hard.
Both package managers will ask to be regularly updated. This can take some time.
Note: you can have both package managers on your system! It is not one or the other. Brew might complain but Macports won't.
Also, if you are dealing with python or ruby packages, use a virtual environment wherever possible.
foreach over a statement is just a syntax sugar for the regular one-way fetch() loop. If you want to loop over your data more than once, select it as a regular array first
$sql = "SELECT * FROM users";
$stm = $dbh->query($sql);
// here you go:
$users = $stm->fetchAll();
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Also quit that try..catch
thing. Don't use it, but set the proper error reporting for PHP and PDO
@Query("select b.equipSealRegisterId from EquipSealRegister b where b.sealName like %?1% and b.deleteFlag = '0'" )
List<String>findBySeal(String sealname);
I have tried this code and it works.
In short, size_t
is never negative, and it maximizes performance because it's typedef'd to be the unsigned integer type that's big enough -- but not too big -- to represent the size of the largest possible object on the target platform.
Sizes should never be negative, and indeed size_t
is an unsigned type. Also, because size_t
is unsigned, you can store numbers that are roughly twice as big as in the corresponding signed type, because we can use the sign bit to represent magnitude, like all the other bits in the unsigned integer. When we gain one more bit, we are multiplying the range of numbers we can represents by a factor of about two.
So, you ask, why not just use an unsigned int
? It may not be able to hold big enough numbers. In an implementation where unsigned int
is 32 bits, the biggest number it can represent is 4294967295
. Some processors, such as the IP16L32, can copy objects larger than 4294967295
bytes.
So, you ask, why not use an unsigned long int
? It exacts a performance toll on some platforms. Standard C requires that a long
occupy at least 32 bits. An IP16L32 platform implements each 32-bit long as a pair of 16-bit words. Almost all 32-bit operators on these platforms require two instructions, if not more, because they work with the 32 bits in two 16-bit chunks. For example, moving a 32-bit long usually requires two machine instructions -- one to move each 16-bit chunk.
Using size_t
avoids this performance toll. According to this fantastic article, "Type size_t
is a typedef that's an alias for some unsigned integer type, typically unsigned int
or unsigned long
, but possibly even unsigned long long
. Each Standard C implementation is supposed to choose the unsigned integer that's big enough--but no bigger than needed--to represent the size of the largest possible object on the target platform."
As a continuation on Matas' answer on benchmarking.
TL/DR: Exists() and Any() are equally fast.
First off: Benchmarking using Stopwatch is not precise (see series0ne's answer on a different, but similiar, topic), but it is far more precise than DateTime.
The way to get really precise readings is by using Performance Profiling. But one way to get a sense of how the two methods' performance measure up to each other is by executing both methods loads of times and then comparing the fastest execution time of each. That way, it really doesn't matter that JITing and other noise gives us bad readings (and it does), because both executions are "equally misguiding" in a sense.
static void Main(string[] args)
{
Console.WriteLine("Generating list...");
List<string> list = GenerateTestList(1000000);
var s = string.Empty;
Stopwatch sw;
Stopwatch sw2;
List<long> existsTimes = new List<long>();
List<long> anyTimes = new List<long>();
Console.WriteLine("Executing...");
for (int j = 0; j < 1000; j++)
{
sw = Stopwatch.StartNew();
if (!list.Exists(o => o == "0123456789012"))
{
sw.Stop();
existsTimes.Add(sw.ElapsedTicks);
}
}
for (int j = 0; j < 1000; j++)
{
sw2 = Stopwatch.StartNew();
if (!list.Exists(o => o == "0123456789012"))
{
sw2.Stop();
anyTimes.Add(sw2.ElapsedTicks);
}
}
long existsFastest = existsTimes.Min();
long anyFastest = anyTimes.Min();
Console.WriteLine(string.Format("Fastest Exists() execution: {0} ticks\nFastest Any() execution: {1} ticks", existsFastest.ToString(), anyFastest.ToString()));
Console.WriteLine("Benchmark finished. Press any key.");
Console.ReadKey();
}
public static List<string> GenerateTestList(int count)
{
var list = new List<string>();
for (int i = 0; i < count; i++)
{
Random r = new Random();
int it = r.Next(0, 100);
list.Add(new string('s', it));
}
return list;
}
After executing the above code 4 times (which in turn do 1 000 Exists()
and Any()
on a list with 1 000 000 elements), it's not hard to see that the methods are pretty much equally fast.
Fastest Exists() execution: 57881 ticks
Fastest Any() execution: 58272 ticks
Fastest Exists() execution: 58133 ticks
Fastest Any() execution: 58063 ticks
Fastest Exists() execution: 58482 ticks
Fastest Any() execution: 58982 ticks
Fastest Exists() execution: 57121 ticks
Fastest Any() execution: 57317 ticks
There is a slight difference, but it's too small a difference to not be explained by background noise. My guess would be that if one would do 10 000 or 100 000 Exists()
and Any()
instead, that slight difference would disappear more or less.
IMPORTANT this answer is valid only for PHP 5, in PHP 7 use built-in cryptographic functions.
Here is simple but secure enough implementation:
Code and examples are here: https://stackoverflow.com/a/19445173/1387163
Modify your $PATH, Add this in your bashrc or bash_profile:
export PATH=/usr/local/bin:/usr/local/sbin:~/bin:$PATH
more click here: Issue #89791
I faced this issue a lot when using position: absolute;
, I faced this issue by using position: relative
in the child element. don't need to change position: absolute
to relative
, just need to add in the child element look into the beneath two examples:
let toggle = document.getElementById('toggle')
toggle.addEventListener("click", () => {
toggle.classList.toggle('change');
})
_x000D_
.container {
width: 60px;
height: 22px;
background: #333;
border-radius: 20px;
position: relative;
cursor: pointer;
}
.change .slide {
transform: translateX(33px);
}
.slide {
transition: 0.5s;
width: 20px;
height: 20px;
background: #fff;
border-radius: 20px;
margin: 2px 2px;
z-index: 100;
}
.dot {
width: 10px;
height: 16px;
background: red;
position: absolute;
top: 4px;
right: 5px;
z-index: 1;
}
_x000D_
<div class="container" id="toggle">
<div class="slide"></div>
<div class="dot"></div>
</div>
_x000D_
let toggle = document.getElementById('toggle')
toggle.addEventListener("click", () => {
toggle.classList.toggle('change');
})
_x000D_
.container {
width: 60px;
height: 22px;
background: #333;
border-radius: 20px;
position: relative;
cursor: pointer;
}
.change .slide {
transform: translateX(33px);
}
.slide {
transition: 0.5s;
width: 20px;
height: 20px;
background: #fff;
border-radius: 20px;
margin: 2px 2px;
z-index: 100;
// Just add position relative;
position: relative;
}
.dot {
width: 10px;
height: 16px;
background: red;
position: absolute;
top: 4px;
right: 5px;
z-index: 1;
}
_x000D_
<div class="container" id="toggle">
<div class="slide"></div>
<div class="dot"></div>
</div>
_x000D_
I had this issue when running ng test
, so to fix it, I added to my xyz.component.spec.ts
file:
import { MatTableModule } from '@angular/material';
And added it to imports
section in TestBed.configureTestingModule({})
:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ReactiveFormsModule, HttpClientModule, RouterTestingModule, MatTableModule ],
declarations: [ BookComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));
Sometimes help to add ?raw=true
at the end of a file path. For example:
wb = xlrd.open_workbook("Z:\\Data\\Locates\\3.8 locates.xls?raw=true")
For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post (TL;DR for most folks) which led me to this concise example.
The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.
That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:
var table = $('#example').DataTable();
table.rows.add( $(
'<tr>'+
' <td>Tiger Nixon</td>'+
' <td>System Architect</td>'+
' <td>Edinburgh</td>'+
' <td>61</td>'+
' <td>2011/04/25</td>'+
' <td>$3,120</td>'+
'</tr>'
) ).draw();
The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.
Here is a function that converts a 1-D vector to a 2-D one-hot array.
#!/usr/bin/env python
import numpy as np
def convertToOneHot(vector, num_classes=None):
"""
Converts an input 1-D vector of integers into an output
2-D array of one-hot vectors, where an i'th input value
of j will set a '1' in the i'th row, j'th column of the
output array.
Example:
v = np.array((1, 0, 4))
one_hot_v = convertToOneHot(v)
print one_hot_v
[[0 1 0 0 0]
[1 0 0 0 0]
[0 0 0 0 1]]
"""
assert isinstance(vector, np.ndarray)
assert len(vector) > 0
if num_classes is None:
num_classes = np.max(vector)+1
else:
assert num_classes > 0
assert num_classes >= np.max(vector)
result = np.zeros(shape=(len(vector), num_classes))
result[np.arange(len(vector)), vector] = 1
return result.astype(int)
Below is some example usage:
>>> a = np.array([1, 0, 3])
>>> convertToOneHot(a)
array([[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 1]])
>>> convertToOneHot(a, num_classes=10)
array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]])
I had a similar problem and found that if you remove the size definition, it works for some reason.
Remove:
<size
android:width="60dp"
android:height="40dp" />
from the shape.
Let me know if this works!
The number of column parameters in your insert query is 9, but you've only provided 8 values.
INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
The query should omit the "id" parameter, because it is auto-generated (or should be anyway):
INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
I recently tried to use the above answers to access the docstring of a function from the context of that function but as the above questions were only returning the name string it did not work.
Fortunately I found a simple solution. If like me, you want to refer to the function rather than simply get the string representing the name you can apply eval() to the string of the function name.
import sys
def foo():
"""foo docstring"""
print(eval(sys._getframe().f_code.co_name).__doc__)
Try setTitle by itself, like this:
setTitle("Hello StackOverflow");
Cascade will work when you delete something on table Courses
. Any record on table BookCourses
that has reference to table Courses
will be deleted automatically.
But when you try to delete on table BookCourses
only the table itself is affected and not on the Courses
follow-up question: why do you have CourseID
on table Category?
Maybe you should restructure your schema into this,
CREATE TABLE Categories
(
Code CHAR(4) NOT NULL PRIMARY KEY,
CategoryName VARCHAR(63) NOT NULL UNIQUE
);
CREATE TABLE Courses
(
CourseID INT NOT NULL PRIMARY KEY,
BookID INT NOT NULL,
CatCode CHAR(4) NOT NULL,
CourseNum CHAR(3) NOT NULL,
CourseSec CHAR(1) NOT NULL,
);
ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;
Here's a simple latex-based example.
---
header-includes:
- \usepackage[most]{tcolorbox}
- \definecolor{light-yellow}{rgb}{1, 0.95, 0.7}
- \newtcolorbox{myquote}{colback=light-yellow,grow to right by=-10mm,grow to left by=-10mm, boxrule=0pt,boxsep=0pt,breakable}
- \newcommand{\todo}[1]{\begin{myquote} \textbf{TODO:} \emph{#1} \end{myquote}}
---
blah blah
\todo{something}
blah
Unfortunately because this is latex, you can no-longer include markdown inside the TODO box (which is not a huge problem, usually), and it won't work when converting to formats other than PDF (e.g. html).
You could programmatically add more -name
clauses, separated by -or
:
find Documents \( -name "*.py" -or -name "*.html" \)
Or, go for a simple loop instead:
for F in Documents/*.{py,html}; do ...something with each '$F'... ; done
Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):
select *
from calls c join users u
on c.assigned_to = u.user_id
or c.requestor_id = u.user_id
where u.dept = 4
You should take care with readLines(...)
and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:
processFile = function(filepath) {
con = file(filepath, "r")
while ( TRUE ) {
line = readLines(con, n = 1)
if ( length(line) == 0 ) {
break
}
print(line)
}
close(con)
}
Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.
var byteCharacters = atob(response.data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new Blob([byteArray], { type: 'application/pdf;base64' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
You return a base64 string from the API or another source. You can also download it.
all you need to do is just add $mail->IsHTML(true); to the code it works fine..
If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".
So at the top of your program
import pdb
Then in the code where you want to see what is happening
pdb.set_trace()
and you get dropped into a prompt
This snippet works in IE7 at least
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
You should run:
composer dump-autoload
and if does not work you should:
re-install composer
dict1 = {}
dict1['dict2'] = {}
print dict1
>>> {'dict2': {},}
this is commonly known as nesting iterators into other iterators I think
There is no need to include a bulky library such as Moment.js to fix such a simple issue.
The issue you are facing is not with formatting, but with parsing.
As John Shammas mentions in another answer, the Date
constructor (and Date.parse
) are picky about the input. Your 2016-01-04 10:34:23
may work in one JavaScript implementation, but not necessarily in the other.
According to the specification of ECMAScript 5.1, Date.parse
supports (a simplification of) ISO 8601. That's good news, because your date is already very ISO 8601-like.
All you have to do is change the input format just a little. Swap the space for a T
: 2016-01-04T10:34:23
; and optionally add a time zone (2016-01-04T10:34:23+01:00
), otherwise UTC is assumed.
Although you need a pair of parentheses to print in Python 3, you no longer need a space after print
, because it's a function. So that's only a single extra character.
If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print
and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print
shortcut in Python 3.
Python 2:
>>> p = print
File "<stdin>", line 1
p = print
^
SyntaxError: invalid syntax
Python 3:
>>> p = print
>>> p('hello')
hello
It'll make your code less readable, but you'll save those few characters every time you print something.
You just copy the cv2.pyd file to the C:\Users\USERNAME\Anaconda2\Lib
directory.
You get the cv2.pyd file at this link (https://sourceforge.net/projects/opencvlibrary/files/).
The cv2.pyd is located at C:\Users\USERNAME\Desktop\opencv\build\python\2.7\x64
.
try running after changing file name from '-' to `_'
for eg:
.\my_app\my_fle.bat
instead of
.\\my-app\my-fle.bat
Or
cd my_app
.\my_file.bat
This can be done. For example with Firefox
CSS
#hlinks {
-moz-binding: url(stackexchange.xml#hlinks);
}
stackexchange.xml
<bindings xmlns="http://www.mozilla.org/xbl"
xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="hlinks">
<content>
<children/>
<html:a href="/privileges">privileges</html:a>
<html:span class="lsep"> | </html:span>
<html:a href="/users/logout">log out</html:a>
</content>
</binding>
</bindings>
Both of these two top-rated answers are wrong. Check out the MDN description on the concurrency model and the event loop, and it should become clear what's going on (that MDN resource is a real gem). And simply using setTimeout
can be adding unexpected problems in your code in addition to "solving" this little problem.
What's actually going on here is not that "the browser might not be quite ready yet because concurrency," or something based on "each line is an event that gets added to the back of the queue".
The jsfiddle provided by DVK indeed illustrates a problem, but his explanation for it isn't correct.
What's happening in his code is that he's first attaching an event handler to the click
event on the #do
button.
Then, when you actually click the button, a message
is created referencing the event handler function, which gets added to the message queue
. When the event loop
reaches this message, it creates a frame
on the stack, with the function call to the click event handler in the jsfiddle.
And this is where it gets interesting. We're so used to thinking of Javascript as being asynchronous that we're prone to overlook this tiny fact: Any frame has to be executed, in full, before the next frame can be executed. No concurrency, people.
What does this mean? It means that whenever a function is invoked from the message queue, it blocks the queue until the stack it generates has been emptied. Or, in more general terms, it blocks until the function has returned. And it blocks everything, including DOM rendering operations, scrolling, and whatnot. If you want confirmation, just try to increase the duration of the long running operation in the fiddle (e.g. run the outer loop 10 more times), and you'll notice that while it runs, you cannot scroll the page. If it runs long enough, your browser will ask you if you want to kill the process, because it's making the page unresponsive. The frame is being executed, and the event loop and message queue are stuck until it finishes.
So why this side-effect of the text not updating? Because while you have changed the value of the element in the DOM — you can console.log()
its value immediately after changing it and see that it has been changed (which shows why DVK's explanation isn't correct) — the browser is waiting for the stack to deplete (the on
handler function to return) and thus the message to finish, so that it can eventually get around to executing the message that has been added by the runtime as a reaction to our mutation operation, and in order to reflect that mutation in the UI.
This is because we are actually waiting for code to finish running. We haven't said "someone fetch this and then call this function with the results, thanks, and now I'm done so imma return, do whatever now," like we usually do with our event-based asynchronous Javascript. We enter a click event handler function, we update a DOM element, we call another function, the other function works for a long time and then returns, we then update the same DOM element, and then we return from the initial function, effectively emptying the stack. And then the browser can get to the next message in the queue, which might very well be a message generated by us by triggering some internal "on-DOM-mutation" type event.
The browser UI cannot (or chooses not to) update the UI until the currently executing frame has completed (the function has returned). Personally, I think this is rather by design than restriction.
Why does the setTimeout
thing work then? It does so, because it effectively removes the call to the long-running function from its own frame, scheduling it to be executed later in the window
context, so that it itself can return immediately and allow the message queue to process other messages. And the idea is that the UI "on update" message that has been triggered by us in Javascript when changing the text in the DOM is now ahead of the message queued for the long-running function, so that the UI update happens before we block for a long time.
Note that a) The long-running function still blocks everything when it runs, and b) you're not guaranteed that the UI update is actually ahead of it in the message queue. On my June 2018 Chrome browser, a value of 0
does not "fix" the problem the fiddle demonstrates — 10 does. I'm actually a bit stifled by this, because it seems logical to me that the UI update message should be queued up before it, since its trigger is executed before scheduling the long-running function to be run "later". But perhaps there're some optimisations in the V8 engine that may interfere, or maybe my understanding is just lacking.
Okay, so what's the problem with using setTimeout
, and what's a better solution for this particular case?
First off, the problem with using setTimeout
on any event handler like this, to try to alleviate another problem, is prone to mess with other code. Here's a real-life example from my work:
A colleague, in a mis-informed understanding on the event loop, tried to "thread" Javascript by having some template rendering code use setTimeout 0
for its rendering. He's no longer here to ask, but I can presume that perhaps he inserted timers to gauge the rendering speed (which would be the return immediacy of functions) and found that using this approach would make for blisteringly fast responses from that function.
First problem is obvious; you cannot thread javascript, so you win nothing here while you add obfuscation. Secondly, you have now effectively detached the rendering of a template from the stack of possible event listeners that might expect that very template to have been rendered, while it may very well not have been. The actual behaviour of that function was now non-deterministic, as was — unknowingly so — any function that would run it, or depend on it. You can make educated guesses, but you cannot properly code for its behaviour.
The "fix" when writing a new event handler that depended on its logic was to also use setTimeout 0
. But, that's not a fix, it is hard to understand, and it is no fun to debug errors that are caused by code like this. Sometimes there's no problem ever, other times it concistently fails, and then again, sometimes it works and breaks sporadically, depending on the current performance of the platform and whatever else happens to going on at the time. This is why I personally would advise against using this hack (it is a hack, and we should all know that it is), unless you really know what you're doing and what the consequences are.
But what can we do instead? Well, as the referenced MDN article suggests, either split the work into multiple messages (if you can) so that other messages that are queued up may be interleaved with your work and executed while it runs, or use a web worker, which can run in tandem with your page and return results when done with its calculations.
Oh, and if you're thinking, "Well, couldn't I just put a callback in the long-running function to make it asynchronous?," then no. The callback doesn't make it asynchronous, it'll still have to run the long-running code before explicitly calling your callback.
Response.Redirect()
should be used when:
Server.Transfer()
should be used when:
The VPATH option might come in handy, which tells make what directories to look in for source code. You'd still need a -I option for each include path, though. An example:
CXXFLAGS=-Ipart1/inc -Ipart2/inc -Ipart3/inc
VPATH=part1/src:part2/src:part3/src
OutputExecutable: part1api.o part2api.o part3api.o
This will automatically find the matching partXapi.cpp files in any of the VPATH specified directories and compile them. However, this is more useful when your src directory is broken into subdirectories. For what you describe, as others have said, you are probably better off with a makefile for each part, especially if each part can stand alone.
Use this one, it is trusted solution and works well for all browsers:
protected void clearInput(WebElement webElement) {
// isIE() - just checks is it IE or not - use your own implementation
if (isIE() && "file".equals(webElement.getAttribute("type"))) {
// workaround
// if IE and input's type is file - do not try to clear it.
// If you send:
// - empty string - it will find file by empty path
// - backspace char - it will process like a non-visible char
// In both cases it will throw a bug.
//
// Just replace it with new value when it is need to.
} else {
// if you have no StringUtils in project, check value still empty yet
while (!StringUtils.isEmpty(webElement.getAttribute("value"))) {
// "\u0008" - is backspace char
webElement.sendKeys("\u0008");
}
}
}
If input has type="file" - do not clear it for IE. It will try to find file by empty path and will throw a bug.
More details you could find on my blog