The primary key class must define equals and hashCode methods
The error you are getting is in line 3. i.e. it is not in
CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)
but earlier:
CREATE TABLE tags
(
(question_id, tag_id) NOT NULL,
Correct table definition is like pilcrow showed.
And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:
CREATE TABLE tags (
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id),
UNIQUE (tag1, tag2, tag3)
);
or, if you want to have the constraint named according to your wish:
CREATE TABLE tags (
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id),
CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);
Composite primary keys are what you want where you want to create a many to many relationship with a fact table. For example, you might have a holiday rental package that includes a number of properties in it. On the other hand, the property could also be available as a part of a number of rental packages, either on its own or with other properties. In this scenario, you establish the relationship between the property and the rental package with a property/package fact table. The association between a property and a package will be unique, you will only ever join using property_id with the property table and/or package_id with the package table. Each relationship is unique and an auto_increment key is redundant as it won't feature in any other table. Hence defining the composite key is the answer.
I do it like this:
CREATE UNIQUE INDEX index_name ON TableName (Column1, Column2, Column3);
My convention for a unique index_name
is TableName_Column1_Column2_Column3_uindex
.
The fastest way to check if a string contains another string is using indexOf
:
if (code.indexOf('ST1') !== -1) {
// string code has "ST1" in it
} else {
// string code does not have "ST1" in it
}
I resolved this issue by updating the project: right click on the Maven project, select Maven -> Update Project -> select checkbox Force Updates of Snapshots/Releases.
Make the function take one parameter: an array. Pass in the actual parameters as values in the array.
Edit: the link in Pekka's comment just about sums it up.
Oldie but goldie...
Since user is asking for jQuery, I'm going to keep it simple:
var html = $('#container').clone();
console.log(html);
SELECT *
FROM table_name
WHERE table_name.the_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
You can use Open Street Map : you will find dozens of different layers and map types, and this is absolutely free. You can download all the map tiles you want. And of course, as anyone can enhance the map, it displays more information than Google's maps. If you need help, you can ask the community which is also very active.
That is correct. Super is used to call the parent constructor. So suppose you have a code block like so
class A{
int n;
public A(int x){
n = x;
}
}
class B extends A{
int m;
public B(int x, int y){
super(x);
m = y;
}
}
Then you can assign a value to the member variable n.
First of all don't use 'list' as variable name.
If you have simple dictionaries with unique keys then you can do the following(note that new dictionary object with all items from sub-dictionaries will be created):
res = {}
for line in listOfDicts:
res.update(line)
res['d']
>>> 4
Otherwise:
getValues = lambda key,inputData: [subVal[key] for subVal in inputData if key in subVal]
getValues('d', listOfDicts)
>>> [4]
Or very base:
def get_value(listOfDicts, key):
for subVal in listOfDicts:
if key in subVal:
return subVal[key]
Try this one on for size.
private static void addSoftwareLibrary(File file) throws Exception {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
}
This edits the system class loader to include the given library jar. It is pretty ugly, but it works.
A rather common solution to the two click problem is putting
e.stopPropagation()
at the end of your function (assuming you use function(e)
that is). This prevents the event from bubbling up which could lead to a second execution of the function.
Another possibility would be to use pidof
it usually comes with most distributions. It will return you the PID of a given process by using it's name.
pidof process_name
This way you could store that information in a variable and execute kill -9
on it.
#!/bin/bash
pid=`pidof process_name`
kill -9 $pid
Solution of VS2010 is supported by VS2012. Solution of VS2012 isn't supported by VS2010 --> one-way upgrade only. VS2012 doesn't support setup projects. Find here more about VS2010/VS2012 compatibility: http://msdn.microsoft.com/en-us/library/hh266747(v=vs.110).aspx
To answer the first part of your question:
LPCSTR
is a pointer to a const string (LP means Long Pointer)
LPCTSTR
is a pointer to a const TCHAR
string, (TCHAR
being either a wide char or char depending on whether UNICODE is defined in your project)
LPTSTR
is a pointer to a (non-const) TCHAR
string
In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.
This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)
VB sample:
@Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})
Sample Css:
.someClass
{
color: Green !important;
}
In my case, I found that I need the !important attribute to over ride the site.css a:link css class
You can use "dd/MM/yyyy"
format for using it in DateTime.ParseExact
.
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Here is a DEMO
.
For more informations, check out Custom Date and Time Format Strings
You're better off making two selects
and showing one while hiding the other.
It's easier, and adding options
to selects
with your method will not work in IE8 (if you care).
simply change <div>
to <tbody>
<table id="authenticationSetting" style="display: none">
<tbody id="authenticationOuterIdentityBlock" style="display: none;">
<tr>
<td class="orionSummaryHeader">
<orion:message key="policy.wifi.enterprise.authentication.outeridentitity" />:</td>
<td class="orionSummaryColumn">
<orion:textbox id="authenticationOuterIdentity" size="30" />
</td>
</tr>
</tbody>
</table>
You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..
string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call
but still, it would not be found by the getElementById
because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.
You would need to use append
or appendTo
or after
etc.. to put it in the dom first..
Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..
To my knowledge this is inherent to most widgets and the amount of "padding" differs among phone manufacturers. This padding is really white space between the image border and the image in the 9 patch image file.
For example on my Droid X, spinner widgets get extra white space than buttons, which makes it look awkward when you have a spinner inline with a button, yet on my wife's phone the same application doesn't have the same problem and looks great!
The only suggestion I would have is to create your own 9 patch files and use them in your application.
Ahhh the pains that are Android.
Edited: Clarify padding vs white space.
I have achieved this by using one nice example i have found here. I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.
From the jQuery API: with the setting of dataType
, If none is specified, jQuery will try to infer it with $.parseJSON()
based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType
to json
to convert it automatically.
What is being returned is an anonymous type so create a new class with 2 fields
class BasicProjectInfo {
string name;
string id;
}
and return new BasicProjectInfo(pro.ProjectName, pro.ProjectId);
. You method in this case will return a List<BasicProjectInfo>
Sample form using PHP for direct payments.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="[email protected]">
<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '">
<input type="hidden" name="amount_' . $x . '" value="' . $price . '">
<input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '">
<input type="hidden" name="custom" value="' . $product_id_array . '">
<input type="hidden" name="notify_url" value="https://www.yoursite.com/my_ipn.php">
<input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="cbt" value="Return to The Store">
<input type="hidden" name="cancel_return" value="https://www.yoursite.com/paypal_cancel.php">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="currency_code" value="USD">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - its fast, free and secure!">
</form>
kindly go through the fields notify_url, return, cancel_return
sample code for handling ipn (my_ipn.php) which is requested by paypal after payment has been made.
For more information on creating a IPN, please refer to this link.
<?php
// Check to see there are posted variables coming into the script
if ($_SERVER['REQUEST_METHOD'] != "POST")
die("No Post Variables");
// Initialize the $req variable and add CMD key value pair
$req = 'cmd=_notify-validate';
// Read the post from PayPal
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// Now Post all of that back to PayPal's server using curl, and validate everything with PayPal
// We will use CURL instead of PHP for this for a more universally operable script (fsockopen has issues on some environments)
//$url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
$url = "https://www.paypal.com/cgi-bin/webscr";
$curl_result = $curl_err = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($req)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$curl_result = @curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);
$req = str_replace("&", "\n", $req); // Make it a nice list in case we want to email it to ourselves for reporting
// Check that the result verifies
if (strpos($curl_result, "VERIFIED") !== false) {
$req .= "\n\nPaypal Verified OK";
} else {
$req .= "\n\nData NOT verified from Paypal!";
mail("[email protected]", "IPN interaction not verified", "$req", "From: [email protected]");
exit();
}
/* CHECK THESE 4 THINGS BEFORE PROCESSING THE TRANSACTION, HANDLE THEM AS YOU WISH
1. Make sure that business email returned is your business email
2. Make sure that the transaction?s payment status is ?completed?
3. Make sure there are no duplicate txn_id
4. Make sure the payment amount matches what you charge for items. (Defeat Price-Jacking) */
// Check Number 1 ------------------------------------------------------------------------------------------------------------
$receiver_email = $_POST['receiver_email'];
if ($receiver_email != "[email protected]") {
//handle the wrong business url
exit(); // exit script
}
// Check number 2 ------------------------------------------------------------------------------------------------------------
if ($_POST['payment_status'] != "Completed") {
// Handle how you think you should if a payment is not complete yet, a few scenarios can cause a transaction to be incomplete
}
// Check number 3 ------------------------------------------------------------------------------------------------------------
$this_txn = $_POST['txn_id'];
//check for duplicate txn_ids in the database
// Check number 4 ------------------------------------------------------------------------------------------------------------
$product_id_string = $_POST['custom'];
$product_id_string = rtrim($product_id_string, ","); // remove last comma
// Explode the string, make it an array, then query all the prices out, add them up, and make sure they match the payment_gross amount
// END ALL SECURITY CHECKS NOW IN THE DATABASE IT GOES ------------------------------------
////////////////////////////////////////////////////
// Homework - Examples of assigning local variables from the POST variables
$txn_id = $_POST['txn_id'];
$payer_email = $_POST['payer_email'];
$custom = $_POST['custom'];
// Place the transaction into the database
// Mail yourself the details
mail("[email protected]", "NORMAL IPN RESULT YAY MONEY!", $req, "From: [email protected]");
?>
The below image will help you in understanding the paypal process.
For further reading refer to the following links;
hope this helps you..:)
In typescript it is possible to do an instanceof
check in an if statement and you will have access to the same variable with the Typed
properties.
So let's say MarkerSymbolInfo
has a property on it called marker
. You can do the following:
if (symbolInfo instanceof MarkerSymbol) {
// access .marker here
const marker = symbolInfo.marker
}
It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.
Check out these two resources for more information:
There are also the following options:
docker container ls
docker container ls -a
# --all, -a
# Show all containers (default shows just running)
since: 1.13.0 (2017-01-18):
Restructure CLI commands by adding
docker image
anddocker container
commands for more consistency #26025
and as stated here: Introducing Docker 1.13, users are encouraged to adopt the new syntax:
CLI restructured
In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with. For example
list
andstart
of containers are now subcommands ofdocker container
andhistory
is a subcommand ofdocker image
.These changes let us clean up the Docker CLI syntax, improve help text and make Docker simpler to use. The old command syntax is still supported, but we encourage everybody to adopt the new syntax.
When building big tables speed is a concern so Jamie Dixon's second function is best, but it doesn't completely work as is...
It fails to take all of the letters to lowercase, and it only capitalizes the first letter of the string, not the first letter of each word in the string... the below option fixes both issues:
public string UppercaseFirstEach(string s)
{
char[] a = s.ToLower().ToCharArray();
for (int i = 0; i < a.Count(); i++ )
{
a[i] = i == 0 || a[i-1] == ' ' ? char.ToUpper(a[i]) : a[i];
}
return new string(a);
}
Although at this point, whether this is still the fastest option is uncertain, the Regex
solution provided by George Mauer might be faster... someone who cares enough should test it.
An Euler path is a path that uses every edge of a graph exactly once.and it must have exactly two odd vertices.the path starts and ends at different vertex. A Hamiltonian cycle is a cycle that contains every vertex of the graph hence you may not use all the edges of the graph.
Use <location>
configuration tag, and <allow users="?"/>
to allow anonymous only or <allow users="*"/>
for all:
<configuration>
<location path="Path/To/Public/Folder">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
df[df.duplicated(['ID'], keep=False)]
it'll return all duplicated rows back to you.
According to documentation:
keep : {‘first’, ‘last’, False}, default ‘first’
- first : Mark duplicates as True except for the first occurrence.
- last : Mark duplicates as True except for the last occurrence.
- False : Mark all duplicates as True.
BigDecimal pi = new BigDecimal(3.14);
BigDecimal pi4 = new BigDecimal(12.56);
System.out.printf("%.2f",pi);
// prints 3.14
System.out.printf("%.0f",pi4);
// prints 13
Which would you rather write and maintain?
ASP.NET MVC
public class TweetsController : Controller {
// GET: /Tweets/
[HttpGet]
public ActionResult Index() {
return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
}
}
ASP.NET Web API
public class TweetsController : ApiController {
// GET: /Api/Tweets/
public List<Tweet> Get() {
return Twitter.GetTweets();
}
}
This works for me in my onClickListener
:
yourView.postDelayed(new Runnable() {
@Override
public void run() {
yourView.invalidate();
System.out.println("Height yourView: " + yourView.getHeight());
System.out.println("Width yourView: " + yourView.getWidth());
}
}, 1);
You can try this script, that converts all of your databases and tables to utf8.
len(repr(float(x)/3))
However I must say that this isn't as reliable as you think.
Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:
>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001
The explanation on why this happens is in this chapter of the python tutorial.
A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal
:
>>> print len(str(decimal.Decimal('0.1')))
3
Guessing from your directory name, you are trying to access the repository on the local filesystem. You still need to use URL syntax to access it:
svn export file:///e:/repositories/process/test.txt c:\test.txt
If there are no typos in the question, you got the conditions wrong:
You said this:
IF cells (i,"A") contains the text 'Miami'
...but your code says:
If Cells(i, "A") <> "Miami"
--> <>
means that the value of the cell is not equal to "Miami", so you're not checking what you think you are checking.
I guess you want this instead:
If Cells(i, "A") like "*Miami*"
EDIT:
Sorry, but I can't really help you more. As I already said in a comment, I'm no Excel VBA expert.
Normally I would open Excel now and try your code myself, but I don't even have Excel on any of my machines at home (I use OpenOffice).
Just one general thing: can you identify the row that does not work?
Maybe this helps someone else to answer the question.
Does it ever execute (or at least try to execute) the Cells(i, "C").Value = "BA"
line?
Or is the If Cells(i, "A") like "*Miami*"
stuff already False
?
If yes, try checking just one cell and see if that works.
I don't think Ansible provides this feature, which it should. Here's something that you can do:
hosts: "{{ variable_host | default('web') }}"
and you can pass variable_host
from either command-line or from a vars file, e.g.:
ansible-playbook server.yml --extra-vars "variable_host=newtarget(s)"
a = int(float(a)) if int(float(a)) == float(a) else float(a)
There are many way to install radis-cli
. It comes with redis-tools
and redis-server
. Installing any of them will install redis-cli
too. But it will also install other tools too. As you have redis-server
installed somewhere and only interested to install redis-cli
. To install install only redis-cli
without other unnecessary tools follow below command
cd /tmp
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
cp src/redis-cli /usr/local/bin/
chmod 755 /usr/local/bin/redis-cli
Adding to kennytm's answer. When you do a shallow copy parent.copy() a new dictionary is created with same keys,but the values are not copied they are referenced.If you add a new value to parent_copy it won't effect parent because parent_copy is a new dictionary not reference.
parent = {1: [1,2,3]}
parent_copy = parent.copy()
parent_reference = parent
print id(parent),id(parent_copy),id(parent_reference)
#140690938288400 140690938290536 140690938288400
print id(parent[1]),id(parent_copy[1]),id(parent_reference[1])
#140690938137128 140690938137128 140690938137128
parent_copy[1].append(4)
parent_copy[2] = ['new']
print parent, parent_copy, parent_reference
#{1: [1, 2, 3, 4]} {1: [1, 2, 3, 4], 2: ['new']} {1: [1, 2, 3, 4]}
The hash(id) value of parent[1], parent_copy[1] are identical which implies [1,2,3] of parent[1] and parent_copy[1] stored at id 140690938288400.
But hash of parent and parent_copy are different which implies They are different dictionaries and parent_copy is a new dictionary having values reference to values of parent
You can use whereIn
which accepts an array as second paramter.
DB:table('table')
->whereIn('column', [value, value, value])
->get()
You can chain where multiple times.
DB:table('table')->where('column', 'operator', 'value')
->where('column', 'operator', 'value')
->where('column', 'operator', 'value')
->get();
This will use AND
operator. if you need OR
you can use orWhere
method.
For advanced where
statements
DB::table('table')
->where('column', 'operator', 'value')
->orWhere(function($query)
{
$query->where('column', 'operator', 'value')
->where('column', 'operator', 'value');
})
->get();
First, try to Force reload or Clear cache and Empty chase and hard reload. You can do it by pressing F12 and then by right-clicking on it.
2nd Solution: Check your HTML base tag. You can learn more about it from here.
Once java-8 is out (March 2014) you'll be able to use streams:
If you have a List<Integer>
int sum = list.stream().mapToInt(Integer::intValue).sum();
If it's an int[]
int sum = IntStream.of(a).sum();
In order to render the buttons properly on Safari and other browsers, you'll need to give a specific style for the buttons in addition to setting webkit-appearance to none, e.g.:
border-radius: 0;
-webkit-appearance: none;
background-image: linear-gradient(to bottom, #e4e4e4, #f7f7f7);
border: 1px solid #afafaf
It depends on the server configuration or the relevant directives session.gc_maxlifetime in php.ini
.
Typically the default is 24 minutes (1440 seconds), but your webhost may have altered the default to something else.
You can use the .forEach() method of JavaScript for looping through JSON.
var datesBooking = [_x000D_
{"date": "04\/24\/2018"},_x000D_
{"date": "04\/25\/2018"}_x000D_
];_x000D_
_x000D_
datesBooking.forEach(function(data, index) {_x000D_
console.log(data);_x000D_
});
_x000D_
One can use regular expressions, too:
var thingToTest = "B";_x000D_
if (/A|B/.test(thingToTest)) alert("Do something!")
_x000D_
Here's an example of regular expressions in general:
var myString = "This is my search subject"_x000D_
if (/my/.test(myString)) alert("Do something here!")
_x000D_
This will look for "my" within the variable "myString". You can substitute a string directly in place of the "myString" variable.
As an added bonus you can add the case insensitive "i" and the global "g" to the search as well.
var myString = "This is my search subject"_x000D_
if (/my/ig.test(myString)) alert("Do something here");
_x000D_
Simply said and without revealing the kitchen secrets:
a set in general, is a collection that contains no duplicate elements, and whose elements are in no particular order. So, A HashSet<T>
is similar to a generic List<T>
, but is optimized for fast lookups (via hashtables, as the name implies) at the cost of losing order.
As what has already mentioned by others, the save()
itself contains both create and update operation.
I just want to add supplement about what behind the save()
method.
Firstly, let's see the extend/implement hierarchy of the CrudRepository<T,ID>
,
Ok, let's check the save()
implementation at SimpleJpaRepository<T, ID>
,
@Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
As you can see, it will check whether the ID is existed or not firstly, if the entity is already there, only update will happen by merge(entity)
method and if else, a new record is inserted by persist(entity)
method.
Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.
.iframe-embed {
position: absolute;
top: 0;
left: 0;
bottom: 0;
height: 100%;
width: 100%;
border: 0;
}
.iframe-embed-wrapper {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.iframe-embed-responsive-16by9 {
padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
<iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>
Another way (a new way) to use named tuple is using NamedTuple from typing package: Type hints in namedtuple
Let's use the example of the top answer in this post to see how to use it.
(1) Before using the named tuple, the code is like this:
pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)
from math import sqrt
line_length = sqrt((pt1[0] - pt2[0])**2 + (pt1[1] - pt2[1])**2)
print(line_length)
(2) Now we use the named tuple
from typing import NamedTuple
inherit the NamedTuple class and define the variable name in the new class. test is the name of the class.
class test(NamedTuple):
x: float
y: float
create instances from the class and assign values to them
pt1 = test(1.0, 5.0) # x is 1.0, and y is 5.0. The order matters
pt2 = test(2.5, 1.5)
use the variables from the instances to calculate
line_length = sqrt((pt1.x - pt2.x)**2 + (pt1.y - pt2.y)**2)
print(line_length)
Try something like this:
int main()
{
printf("%x %x %x %x %x %x %x %x\n",
0xC0, 0xC0, 0x61, 0x62, 0x63, 0x31, 0x32, 0x33);
}
Which produces this:
$ ./foo
c0 c0 61 62 63 31 32 33
Both of the above two answers work for me with a similar problem.
However, the body {-webkit-transform} approach causes all elements on the page to effectively be rendered in 3D. This isn't the worst thing, but it slightly changes the rendering of text and other CSS-styled elements.
It may be an effect you want. It may be useful if you're doing a lot of transform on your page. Otherwise, -webkit-backface-visibility:hidden on the element your transforming is the least invasive option.
If you are looking to cobble together a quick utility with minimal effort, bash is good. For a wrapper round an application, bash is invaluable.
Anything that may have you coming back over and over to add improvements is probably (though not always) better suited to a language like Python as Bash code comprising over a 1000 lines gets very painful to maintain. Bash code is also irritating to debug when it gets long.......
Part of the problem with these kind of questions is, from my experience, that shell scripts are usually all custom tasks. There have been very few shell scripting tasks that I have come across where there is already a solution freely available.
temperature = input("What's the current temperature in your city? (please use the format ??C or ???F) >>> ")
### warning... the result from input will <str> on Python 3.x only
### in the case of Python 2.x, the result from input is the variable type <int>
### for the <str> type as the result for Python 2.x it's neccessary to use the another: raw_input()
temp_int = int(temperature[:-1]) # 25 <int> (as example)
temp_str = temperature[-1:] # "C" <str> (as example)
if temp_str.lower() == 'c':
print("Your temperature in Fahrenheit is: {}".format( (9/5 * temp_int) + 32 ) )
elif temp_str.lower() == 'f':
print("Your temperature in Celsius is: {}".format( ((5/9) * (temp_int - 32)) ) )
The traceback
module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:
import traceback
try:
1/0
except Exception:
traceback.print_exc()
Output:
Traceback (most recent call last):
File "C:\scripts\divide_by_zero.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
use this query in your local DB.
select * from schema_version delete from schema_version where checksum Column = -1729781252;
Note: -1729781252 is the "Resolved locally" value.
Build and start the server.
I think I know what you are asking for. Here is what you can do.
first get the height of the person say h meters.
if you can calculate the height of the camera from ground (using height if the person i.e. h) and get angles A and B using gyroscope or something from android then you can calculate the height of the object using the above formula.
Isn't this what you were looking for???
let me know if you need any explanation.
If we want to add custom HTTP headers to a POST request, we must pass them through a dictionary to the headers
parameter.
Here is an example with a non-empty body and headers:
import requests
import json
url = 'https://somedomain.com'
body = {'name': 'Maryja'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(body), headers=headers)
First of all, with regards to FormatType.JSON: JSON is not a member of FormatType, it's a possible value of the type. FormatType isn't even a composite type — it's a scalar.
Second, the only way to do this is to create a mapping table. The more common way to do this in Objective-C is to create a series of constants referring to your "symbols", so you'd have NSString *FormatTypeJSON = @"JSON"
and so on.
You can read plist in SWIFT Language in this way:
let path = NSBundle.mainBundle().pathForResource("PriceList", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path)
Read Single Dictionary value:
let test: AnyObject = dict.objectForKey("index1")
If you want to get full multi-dimensional dictionary in plist:
let value: AnyObject = dict.objectForKey("index2").objectForKey("date")
Here is the plist:
<plist version="1.0">
<dict>
<key>index2</key>
<dict>
<key>date</key>
<string>20140610</string>
<key>amount</key>
<string>110</string>
</dict>
<key>index1</key>
<dict>
<key>amount</key>
<string>125</string>
<key>date</key>
<string>20140212</string>
</dict>
</dict>
</plist>
import operator
reduce(operator.mul, list, 1)
Use the getResourceAsStream()
method on the ServletContext object, e.g.
servletContext.getResourceAsStream("/WEB-INF/myfile");
How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?
EDITED: If you're inside a Servlet object, then call getServletContext()
. If you're in JSP, use the predefined variable application
.
The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?
Require all granted
is only in 2.4, but Allow all ...
stops working in 2.4, and we want to be able to rollout a config that works in both.
The only solution I found, which I am not sure is the proper one, is to use:
# backwards compatibility with apache 2.2
Order allow,deny
Allow from all
# forward compatibility with apache 2.4
Require all granted
Satisfy Any
This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...
See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.
fileinput
is quite straightforward as mentioned on previous answers:
import fileinput
def replace_in_file(file_path, search_text, new_text):
with fileinput.input(file_path, inplace=True) as f:
for line in f:
new_line = line.replace(search_text, new_text)
print(new_line, end='')
Explanation:
fileinput
can accept multiple files, but I prefer to close each single file as soon as it is being processed. So placed single file_path
in with
statement.print
statement does not print anything when inplace=True
, because STDOUT
is being forwarded to the original file.end=''
in print
statement is to eliminate intermediate blank new lines.Can be used as follows:
file_path = '/path/to/my/file'
replace_in_file(file_path, 'old-text', 'new-text')
This is my general way:
View namebar = view.findViewById(R.id.namebar);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
parent.removeView(namebar);
}
Why not do string suppression with triple quotes:
>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes
you can use something like this.It worked out for me
doc = parse('C:\\eve.xml')
my_node_list = doc.getElementsByTagName("name")
my_n_node = my_node_list[0]
my_child = my_n_node.firstChild
my_text = my_child.data
print my_text
$query = mysql_query("SELECT username FROM Users WHERE username='$username' ")
Use prepared statements, do not use mysql as it is deprecated.
// check if name is taken already
$stmt = $link->prepare("SELECT username FROM users WHERE username = :username");
$stmt->execute([
'username' => $username
]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (isset($user) && !empty($user)){
// Username already taken
}
Update 2016:
Unfortunately most of the above solutions are out of date and no longer maintained.
There are 3 additional options I can suggest that are still actively developed:
A .Net component that can be used to integrate the Chrome engine into your .Net Application. Based on CefGlue but a little faster on updates to the latest Chrome version. Also there is a commercial support option available which might come in handy for some. Of course the component itself is open source.
Another .Net component which can be used to integrate the Firefox engine into your .Net application. This is based on Geckofx but unlike the current version of Geckofx this will work with a normal release build of Firefox. To use Geckofx you will need to build Firefox yourself. Again commercial support is available but the component itself is fully open source.
Need all the different browsers in your .Net Application? Which the BrowseEmAll Core API you can integrate Chrome, Firefox, Webkit and Internet Explorer into your application. This is a commercial product though so be warned.
(Full disclosure: I work for this company so take everything I say with a grain of salt)
I like Joel's answer, but I've modified it slightly as I'm not a fan of eating exceptions.
/// <summary>
/// Converts a string to the specified nullable type.
/// </summary>
/// <typeparam name="T">The type to convert to</typeparam>
/// <param name="s">The string to convert</param>
/// <returns>The nullable output</returns>
public static T? ToNullable<T>(this string s) where T : struct
{
if (string.IsNullOrWhiteSpace(s))
return null;
TypeConverter conv = TypeDescriptor.GetConverter(typeof (T));
return (T) conv.ConvertFrom(s);
}
/// <summary>
/// Attempts to convert a string to the specified nullable primative.
/// </summary>
/// <typeparam name="T">The primitive type to convert to</typeparam>
/// <param name="data">The string to convert</param>
/// <param name="output">The nullable output</param>
/// <returns>
/// True if conversion is successfull, false otherwise. Null and whitespace will
/// be converted to null and return true.
/// </returns>
public static bool TryParseNullable<T>(this string data, out T? output) where T : struct
{
try
{
output = data.ToNullable<T>();
return true;
}
catch
{
output = null;
return false;
}
}
Using little functions and things really doesn't appeal to me; I prefer to just use slices:
data = [...]
chunk_size = 10000 # or whatever
chunks = [data[i:i+chunk_size] for i in xrange(0,len(data),chunk_size)]
for chunk in chunks:
...
Create Common Method to Convert String to Date format
public static void main(String[] args) throws Exception {
long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}
private static long ConvertStringToDate(String dateString, String format) {
try {
return new SimpleDateFormat(format).parse(dateString).getTime();
} catch (ParseException e) {}
return 0;
}
The marked answer didn't work for me, I had to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
EDIT:
Or just try removing the this
:
SharedPreferences prefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
Connection in APPConfig
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com" providerName="System.Data.SqlClient" />
</connectionStrings>
In Class.Cs
public string ConnectionString
{
get
{
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
}
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
Here's a function that can include an optional offset for those fixed headers. No external libraries needed.
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
You can grab the height of an element using JQuery and scroll to it.
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
Update March 2018
Scroll to this answer without using JQuery
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
The "selected" answer didn't work for me. I'm using rails 3.1 with CouchRest::Model (based on Active Model). The _changed?
methods don't return true for changed attributes in the after_update
hook, only in the before_update
hook. I was able to get it to work using the (new?) around_update
hook:
class SomeModel < ActiveRecord::Base
around_update :send_notification_after_change
def send_notification_after_change
should_send_it = self.published_changed? && self.published == true
yield
Notification.send(...) if should_send_it
end
end
According to the Go spec, the order of iteration over a map is undefined, and may vary between runs of the program. In practice, not only is it undefined, it's actually intentionally randomized. This is because it used to be predictable, and the Go language developers didn't want people relying on unspecified behavior, so they intentionally randomized it so that relying on this behavior was impossible.
What you'll have to do, then, is pull the keys into a slice, sort them, and then range over the slice like this:
var m map[keyType]valueType
keys := sliceOfKeys(m) // you'll have to implement this
for _, k := range keys {
v := m[k]
// k is the key and v is the value; do your computation here
}
in most cases, got no authentication method error when using the wrong username for logging in. But I do find something else if you still struggle with connection issue and you have tried all the options above.
I created couple Linux VM and try to reproduce such connection issue, one thing I found is, when AWS asked you name your key pair, DO NOT user blank space (" ") and dot (".") in key pair name, even AWS actually allow you to do so.
ex. when I named the key pair as "AWS.FREE.LINUX", connection always be refused. When I named as "AWS_FREE_LINUX", everything works fine.
Hope this will help a little bit.
this is simple solution for your question
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
map.animateCamera(yourLocation);
I think in this case they are the same, but here is an example where order matters:
const int* cantChangeTheData;
int* const cantChangeTheAddress;
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
as this question is the first result at search engines
There are a problem with the selected -and right by the way- solution, is that if you want to add style that will apply to images like ( borders for example ) .
for example :
img {_x000D_
color:#fff;_x000D_
border: 1px solid black;_x000D_
padding: 5px;_x000D_
background-color: #ccc;_x000D_
}
_x000D_
<img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /> <hr />_x000D_
<img src="https://cdn4.iconfinder.com/data/icons/miu-square-flat-social/60/stackoverflow-square-social-media-128.png" alt="BLAH BLAH BLAH" />
_x000D_
as you can see, all of images will apply the same style
there is another approach to easily work around such an issue, using onerror
and injecting some special class to deal with the interrupted images :
.invalidImageSrc {_x000D_
color:#fff;_x000D_
border: 1px solid black;_x000D_
padding: 5px;_x000D_
background-color: #ccc;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
_x000D_
<img onerror="$(this).addClass('invalidImageSrc')" src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /> <hr />_x000D_
<img onerror="$(this).addClass('invalidImageSrc')" src="https://cdn4.iconfinder.com/data/icons/miu-square-flat-social/60/stackoverflow-square-social-media-128.png" alt="BLAH BLAH BLAH" />
_x000D_
You can also create a request instance with default options:
require('request').defaults({ rejectUnauthorized: false })
It's also possible to avoid specifying the properties altogether.
#box {
transition: 0.4s;
position: absolute;
border: 1px solid darkred;
bottom: 20px; left: 20px;
width: 200px; height: 200px;
opacity: 0;
}
#box.on {
opacity: 1;
height: 300px;
width: 500px;
}
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
You can add the directories for your build process like:
...
<resources>
<resource>
<directory>src/bootstrap</directory>
</resource>
</resources>
...
The src/main/java is the default path which is not needed to be mentioned in the pom.xml
There is a solution actually, by applying the "anonymous class" trick and the ideas from the Super Type Tokens:
public final class Voodoo {
public static void chill(final List<?> aListWithSomeType) {
// Here I'd like to get the Class-Object 'SpiderMan'
System.out.println(aListWithSomeType.getClass().getGenericSuperclass());
System.out.println(((ParameterizedType) aListWithSomeType
.getClass()
.getGenericSuperclass()).getActualTypeArguments()[0]);
}
public static void main(String... args) {
chill(new ArrayList<SpiderMan>() {});
}
}
class SpiderMan {
}
The trick lies in the creation of an anonymous class, new ArrayList<SpiderMan>() {}
, in the place of the original (simple) new ArrayList<SpiderMan>()
. The use of an anoymous class (if possible) ensures that the compiler retains information about the type argument SpiderMan
given to the type parameter List<?>
. Voilà !
What you want is an implementation of the observer pattern. You can do it yourself completely, or use java classes like java.util.Observer
and java.util.Observable
Just install http-server globally
npm install -g http-server
where ever you need to run a html file run the command http-server
For ex: your html file is in /home/project/index.html
you can do /home/project/$ http-server
That will give you a link to accessyour webpages:
http-server
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://192.168.0.106:8080
In Java, there are two types of exceptions: checked exceptions and un-checked exceptions. A checked exception must be handled explicitly by the code, whereas, an un-checked exception does not need to be explicitly handled.
For checked exceptions, you either have to put a try/catch block around the code that could potentially throw the exception, or add a "throws" clause to the method, to indicate that the method might throw this type of exception (which must be handled in the calling class or above).
Any exception that derives from "Exception" is a checked exception, whereas a class that derives from RuntimeException is un-checked. RuntimeExceptions do not need to be explicitly handled by the calling code.
What ultimately worked for me was the following steps:
I got this error because I had a dependency on another module that was not loaded.
angular.module("app", ["kendo.directives"]).controller("MyCtrl", function(){}...
so even though I had all the Angular modules, I didn't have the kendo one.
Here's an example - we recently developed a simulation model to measure the remote transmission response time of a yet-to-be-developed system. An emulation analysis would not have given us the answer in time to upgrade the bandwidth capacity so simulation was our approach. Because we were mostly interested in determining bandwidth needs, we cared primarily about transaction size and volume, not the processing of the system. The simulation model was on a stand-alone piece of software that was designed to model discrete-event processes. To summarize in response to your question, emulation is a type of simulation. But, in this case, simulation was NOT an emulation because it didn't fully represent the new system, only the size and volume of transactions.
Filenames can include spaces and even control characters. Spaces are (default) delimiters for shell expansion in bash and as a result of that x=$(find . -name "*.txt")
from the question is not recommended at all. If find gets a filename with spaces e.g. "the file.txt"
you will get 2 separated strings for processing, if you process x
in a loop. You can improve this by changing delimiter (bash IFS
Variable) e.g. to \r\n
, but filenames can include control characters - so this is not a (completely) safe method.
From my point of view, there are 2 recommended (and safe) patterns for processing files:
1. Use for loop & filename expansion:
for file in ./*.txt; do
[[ ! -e $file ]] && continue # continue, if file does not exist
# single filename is in $file
echo "$file"
# your code here
done
2. Use find-read-while & process substitution
while IFS= read -r -d '' file; do
# single filename is in $file
echo "$file"
# your code here
done < <(find . -name "*.txt" -print0)
Remarks
on Pattern 1:
nullglob
can be used to avoid this extra line.failglob
shell option is set, and no matches are found, an error message is printed and the command is not executed." (from Bash Manual above)globstar
: "If set, the pattern ‘**’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘/’, only directories and subdirectories match." see Bash Manual, Shopt Builtinextglob
, nocaseglob
, dotglob
& shell variable GLOBIGNORE
on Pattern 2:
filenames can contain blanks, tabs, spaces, newlines, ... to process filenames in a safe way, find
with -print0
is used: filename is printed with all control characters & terminated with NUL. see also Gnu Findutils Manpage, Unsafe File Name Handling, safe File Name Handling, unusual characters in filenames. See David A. Wheeler below for detailed discussion of this topic.
There are some possible patterns to process find results in a while loop. Others (kevin, David W.) have shown how to do this using pipes:
files_found=1 find . -name "*.txt" -print0 | while IFS= read -r -d '' file; do # single filename in $file echo "$file" files_found=0 # not working example # your code here done [[ $files_found -eq 0 ]] && echo "files found" || echo "no files found"
When you try this piece of code, you will see, that it does not work: files_found
is always "true" & the code will always echo "no files found". Reason is: each command of a pipeline is executed in a separate subshell, so the changed variable inside the loop (separate subshell) does not change the variable in the main shell script. This is why I recommend using process substitution as the "better", more useful, more general pattern.
See I set variables in a loop that's in a pipeline. Why do they disappear... (from Greg's Bash FAQ) for a detailed discussion on this topic.
Additional References & Sources:
As an example, mocha would normally be a devDependency, since testing isn't necessary in production, while express would be a dependency.
Use this layout. If you want to animate the main view shrinking you'll need to add animation to the height of the hidden bar, buy it may be good enough to use the translate animation on the bar, and have the main view height jump instead of animate.
<LinearLayout 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:orientation="vertical" >
<RelativeLayout
android:id="@+id/main_screen"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="@string/hello_world" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/hello_world" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="slideUpDown"
android:text="Slide up / down" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/hidden_panel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#fcc"
android:visibility="visible" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
</RelativeLayout>
</LinearLayout>
Using GNU sed
:
sed -i '$ d' foo.txt
The -i
option does not exist in GNU sed
versions older than 3.95, so you have to use it as a filter with a temporary file:
cp foo.txt foo.txt.tmp
sed '$ d' foo.txt.tmp > foo.txt
rm -f foo.txt.tmp
Of course, in that case you could also use head -n -1
instead of sed
.
MacOS:
On Mac OS X (as of 10.7.4), the equivalent of the sed -i
command above is
sed -i '' -e '$ d' foo.txt
Try this:-
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
getch()
is used to get a character from console but does not echo to the screen.
It is caused by a lack of precision with doubles / decimals (i.e. - the function will not always give the result you expect).
See the following link: MSDN on Math.Round
Here is the relevant quote:
Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter.This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.
There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV
) file with the XChart library. Disclaimer: I'm the lead developer of the project.
In this example, two text files exist in ./CSV/CSVChartRows/
. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1
contains x
, y
, and error bar
data, whereas series2
contains just x
and y
, data.
1,12,1.4
2,34,1.12
3,56,1.21
4,47,1.5
1,56
2,34
3,12
4,26
public class CSVChartRows {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);
// Show it
new SwingWrapper(chart).displayChart();
}
}
yourLabel.intrinsicContentSize.width
for Objective-C / Swift
I struggled a bit with the Interface Builder of XCode 7 to set the Presentation Style as @VenuGopalTewari suggested. In this version, there seems to be no Over Current Context
or Over Full Screen
presentation mode for the segue. Thus, to make it work, I set the mode to Default
:
Additionally I set the presentation mode of the modally presented view controller to Over Full Screen
:
Razor is a view engine for ASP.NET MVC, and also a template engine. Razor code and ASP.NET inline code (code mixed with markup) both get compiled first and get turned into a temporary assembly before being executed. Thus, just like C# and VB.NET both compile to IL which makes them interchangable, Razor and Inline code are both interchangable.
Therefore, it's more a matter of style and interest. I'm more comfortable with razor, rather than ASP.NET inline code, that is, I prefer Razor (cshtml) pages to .aspx pages.
Imagine that you want to get a Human
class, and render it. In cshtml files you write:
<div>Name is @Model.Name</div>
While in aspx files you write:
<div>Name is <%= Human.Name %></div>
As you can see, @
sign of razor makes mixing code and markup much easier.
You can loop over the properties of your object as follows:
for(var prop in ad) {
if (ad.hasOwnProperty(prop)) {
// handle prop as required
}
}
It is important to use the hasOwnProperty()
method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.
From the comments: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment
Verry Easy, change order of element:
Origin
<div style="">
My Text
<button type="button" style="float: right; margin:5px;">
My Button
</button>
</div>
Change to:
<div style="">
<button type="button" style="float: right; margin:5px;">
My Button
</button>
My Text
</div>
Because linux
is a built-in macro defined when the compiler is running on, or compiling for (if it is a cross-compiler), Linux.
There are a lot of such predefined macros. With GCC, you can use:
cp /dev/null emptyfile.c
gcc -E -dM emptyfile.c
to get a list of macros. (I've not managed to persuade GCC to accept /dev/null
directly, but
the empty file seems to work OK.) With GCC 4.8.1 running on Mac OS X 10.8.5, I got the output:
#define __DBL_MIN_EXP__ (-1021)
#define __UINT_LEAST16_MAX__ 65535
#define __ATOMIC_ACQUIRE 2
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __UINT_LEAST8_TYPE__ unsigned char
#define __INTMAX_C(c) c ## L
#define __CHAR_BIT__ 8
#define __UINT8_MAX__ 255
#define __WINT_MAX__ 2147483647
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __SIZE_MAX__ 18446744073709551615UL
#define __WCHAR_MAX__ 2147483647
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __FLT_EVAL_METHOD__ 0
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __x86_64 1
#define __UINT_FAST64_MAX__ 18446744073709551615ULL
#define __SIG_ATOMIC_TYPE__ int
#define __DBL_MIN_10_EXP__ (-307)
#define __FINITE_MATH_ONLY__ 0
#define __GNUC_PATCHLEVEL__ 1
#define __UINT_FAST8_MAX__ 255
#define __DEC64_MAX_EXP__ 385
#define __INT8_C(c) c
#define __UINT_LEAST64_MAX__ 18446744073709551615ULL
#define __SHRT_MAX__ 32767
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __UINT_LEAST8_MAX__ 255
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __APPLE_CC__ 1
#define __UINTMAX_TYPE__ long unsigned int
#define __DEC32_EPSILON__ 1E-6DF
#define __UINT32_MAX__ 4294967295U
#define __LDBL_MAX_EXP__ 16384
#define __WINT_MIN__ (-__WINT_MAX__ - 1)
#define __SCHAR_MAX__ 127
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __INT64_C(c) c ## LL
#define __DBL_DIG__ 15
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __SIZEOF_INT__ 4
#define __SIZEOF_POINTER__ 8
#define __USER_LABEL_PREFIX__ _
#define __STDC_HOSTED__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __DEC32_MAX__ 9.999999E96DF
#define __strong
#define __INT32_MAX__ 2147483647
#define __SIZEOF_LONG__ 8
#define __APPLE__ 1
#define __UINT16_C(c) c
#define __DECIMAL_DIG__ 21
#define __LDBL_HAS_QUIET_NAN__ 1
#define __DYNAMIC__ 1
#define __GNUC__ 4
#define __MMX__ 1
#define __FLT_HAS_DENORM__ 1
#define __SIZEOF_LONG_DOUBLE__ 16
#define __BIGGEST_ALIGNMENT__ 16
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __INT_FAST32_MAX__ 2147483647
#define __DBL_HAS_INFINITY__ 1
#define __DEC32_MIN_EXP__ (-94)
#define __INT_FAST16_TYPE__ short int
#define __LDBL_HAS_DENORM__ 1
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __INT_LEAST32_MAX__ 2147483647
#define __DEC32_MIN__ 1E-95DF
#define __weak
#define __DBL_MAX_EXP__ 1024
#define __DEC128_EPSILON__ 1E-33DL
#define __SSE2_MATH__ 1
#define __ATOMIC_HLE_RELEASE 131072
#define __PTRDIFF_MAX__ 9223372036854775807L
#define __amd64 1
#define __tune_core2__ 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __LONG_LONG_MAX__ 9223372036854775807LL
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WINT_T__ 4
#define __GXX_ABI_VERSION 1002
#define __FLT_MIN_EXP__ (-125)
#define __INT_FAST64_TYPE__ long long int
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __LP64__ 1
#define __DEC128_MIN__ 1E-6143DL
#define __REGISTER_PREFIX__
#define __UINT16_MAX__ 65535
#define __DBL_HAS_DENORM__ 1
#define __UINT8_TYPE__ unsigned char
#define __NO_INLINE__ 1
#define __FLT_MANT_DIG__ 24
#define __VERSION__ "4.8.1"
#define __UINT64_C(c) c ## ULL
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __INT32_C(c) c
#define __DEC64_EPSILON__ 1E-15DD
#define __ORDER_PDP_ENDIAN__ 3412
#define __DEC128_MIN_EXP__ (-6142)
#define __INT_FAST32_TYPE__ int
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __INT16_MAX__ 32767
#define __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ 1080
#define __SIZE_TYPE__ long unsigned int
#define __UINT64_MAX__ 18446744073709551615ULL
#define __INT8_TYPE__ signed char
#define __FLT_RADIX__ 2
#define __INT_LEAST16_TYPE__ short int
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __UINTMAX_C(c) c ## UL
#define __SSE_MATH__ 1
#define __k8 1
#define __SIG_ATOMIC_MAX__ 2147483647
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __SIZEOF_PTRDIFF_T__ 8
#define __x86_64__ 1
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __INT_FAST16_MAX__ 32767
#define __UINT_FAST32_MAX__ 4294967295U
#define __UINT_LEAST64_TYPE__ long long unsigned int
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MAX_10_EXP__ 38
#define __LONG_MAX__ 9223372036854775807L
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __FLT_HAS_INFINITY__ 1
#define __UINT_FAST16_TYPE__ short unsigned int
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __CHAR16_TYPE__ short unsigned int
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __INT_LEAST16_MAX__ 32767
#define __DEC64_MANT_DIG__ 16
#define __INT64_MAX__ 9223372036854775807LL
#define __UINT_LEAST32_MAX__ 4294967295U
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __INT_LEAST64_TYPE__ long long int
#define __INT16_TYPE__ short int
#define __INT_LEAST8_TYPE__ signed char
#define __DEC32_MAX_EXP__ 97
#define __INT_FAST8_MAX__ 127
#define __INTPTR_MAX__ 9223372036854775807L
#define __LITTLE_ENDIAN__ 1
#define __SSE2__ 1
#define __LDBL_MANT_DIG__ 64
#define __CONSTANT_CFSTRINGS__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __code_model_small__ 1
#define __k8__ 1
#define __INTPTR_TYPE__ long int
#define __UINT16_TYPE__ short unsigned int
#define __WCHAR_TYPE__ int
#define __SIZEOF_FLOAT__ 4
#define __pic__ 2
#define __UINTPTR_MAX__ 18446744073709551615UL
#define __DEC64_MIN_EXP__ (-382)
#define __INT_FAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __FLT_DIG__ 6
#define __UINT_FAST64_TYPE__ long long unsigned int
#define __INT_MAX__ 2147483647
#define __MACH__ 1
#define __amd64__ 1
#define __INT64_TYPE__ long long int
#define __FLT_MAX_EXP__ 128
#define __ORDER_BIG_ENDIAN__ 4321
#define __DBL_MANT_DIG__ 53
#define __INT_LEAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __DEC64_MIN__ 1E-383DD
#define __WINT_TYPE__ int
#define __UINT_LEAST32_TYPE__ unsigned int
#define __SIZEOF_SHORT__ 2
#define __SSE__ 1
#define __LDBL_MIN_EXP__ (-16381)
#define __INT_LEAST8_MAX__ 127
#define __SIZEOF_INT128__ 16
#define __LDBL_MAX_10_EXP__ 4932
#define __ATOMIC_RELAXED 0
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define _LP64 1
#define __UINT8_C(c) c
#define __INT_LEAST32_TYPE__ int
#define __SIZEOF_WCHAR_T__ 4
#define __UINT64_TYPE__ long long unsigned int
#define __INT_FAST8_TYPE__ signed char
#define __DBL_DECIMAL_DIG__ 17
#define __FXSR__ 1
#define __DEC_EVAL_METHOD__ 2
#define __UINT32_C(c) c ## U
#define __INTMAX_MAX__ 9223372036854775807L
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __INT8_MAX__ 127
#define __PIC__ 2
#define __UINT_FAST32_TYPE__ unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __INT32_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __FLT_MIN_10_EXP__ (-37)
#define __INTMAX_TYPE__ long int
#define __DEC128_MAX_EXP__ 6145
#define __ATOMIC_CONSUME 1
#define __GNUC_MINOR__ 8
#define __UINTMAX_MAX__ 18446744073709551615UL
#define __DEC32_MANT_DIG__ 7
#define __DBL_MAX_10_EXP__ 308
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __INT16_C(c) c
#define __STDC__ 1
#define __PTRDIFF_TYPE__ long int
#define __ATOMIC_SEQ_CST 5
#define __UINT32_TYPE__ unsigned int
#define __UINTPTR_TYPE__ long unsigned int
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DEC128_MANT_DIG__ 34
#define __LDBL_MIN_10_EXP__ (-4931)
#define __SIZEOF_LONG_LONG__ 8
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __LDBL_DIG__ 18
#define __FLT_DECIMAL_DIG__ 9
#define __UINT_FAST16_MAX__ 65535
#define __GNUC_GNU_INLINE__ 1
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __SSE3__ 1
#define __UINT_FAST8_TYPE__ unsigned char
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_RELEASE 3
That's 236 macros from an empty file. When I added #include <stdio.h>
to the file, the number of macros defined went up to 505. These includes all sorts of platform-identifying macros.
This is because, in C#, single quotes (''
) denote (or encapsulate) a single character, whereas double quotes (""
) are used for a string of characters. For example:
var myChar = '=';
var myString = "==";
I needed clean and lightweight solution (so no jQuery and alike), which will look exactly like plain HTML, would also continue working when only plain HTML is preset (so javascript will only enhance it), and which will allow searching by starting letters (including national UTF-8 letters) if possible where it does not add extra weight. It also must work fast on very slow browsers (think rPi - so preferably no javascript executing after page load).
In firefox it uses CSS identing and thus allow searching by letters, and in other browsers it will use
prepending (but there it does not support quick search by letters). Anyway, I'm quite happy with results.
You can try it in action here
It goes like this:
CSS:
.i0 { }
.i1 { margin-left: 1em; }
.i2 { margin-left: 2em; }
.i3 { margin-left: 3em; }
.i4 { margin-left: 4em; }
.i5 { margin-left: 5em; }
HTML (class "i1", "i2" etc denote identation level):
<form action="/filter/" method="get">
<select name="gdje" id="gdje">
<option value=1 class="i0">Svugdje</option>
<option value=177 class="i1">Bosna i Hercegovina</option>
<option value=190 class="i2">Babin Do</option>
<option value=258 class="i2">Banja Luka</option>
<option value=181 class="i2">Tuzla</option>
<option value=307 class="i1">Crna Gora</option>
<option value=308 class="i2">Podgorica</option>
<option value=2 SELECTED class="i1">Hrvatska</option>
<option value=5 class="i2">Bjelovarsko-bilogorska županija</option>
<option value=147 class="i3">Bjelovar</option>
<option value=79 class="i3">Daruvar</option>
<option value=94 class="i3">Garešnica</option>
<option value=329 class="i3">Grubišno Polje</option>
<option value=368 class="i3">Cazma</option>
<option value=6 class="i2">Brodsko-posavska županija</option>
<option value=342 class="i3">Gornji Bogicevci</option>
<option value=158 class="i3">Klakar</option>
<option value=140 class="i3">Nova Gradiška</option>
</select>
</form>
<script>
<!--
window.onload = loadFilter;
// -->
</script>
JavaScript:
function loadFilter() {
'use strict';
// indents all options depending on "i" CSS class
function add_nbsp() {
var opt = document.getElementsByTagName("option");
for (var i = 0; i < opt.length; i++) {
if (opt[i].className[0] === 'i') {
opt[i].innerHTML = Array(3*opt[i].className[1]+1).join(" ") + opt[i].innerHTML; // this means " " x (3*$indent)
}
}
}
// detects browser
navigator.sayswho= (function() {
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
M= M[2]? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
return M.join(' ');
})();
// quick detection if browser is firefox
function isFirefox() {
var ua= navigator.userAgent,
M= ua.match(/firefox\//i);
return M;
}
// indented select options support for non-firefox browsers
if (!isFirefox()) {
add_nbsp();
}
}
If there is not ISNULL()
method, you can use this expression instead:
CASE WHEN fieldname IS NULL THEN 0 ELSE fieldname END
This works the same as ISNULL(fieldname, 0)
.
You turn off pack_propagate
by setting pack_propagate(0)
Turning off pack_propagate
here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally
To turn off resizing the root window, you can set root.resizable(0, 0)
, where resizing is allowed in the x
and y
directions respectively.
To set a maxsize to window, as noted in the other answer you can set the maxsize
attribute or minsize
although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.
Whenever you set grid
or pack
on a widget it will return None
. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid
or pack
on it. You should instead set the variable to be the widget Widget(master, ....)
and then call pack
or grid
on the widget instead.
import tkinter as tk
def startgame():
pass
mw = tk.Tk()
#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()
mw.mainloop()
The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).
In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character
So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).
And you can mix “combining above” and “combining below” marks.
The sample text in the question starts with:
H
ͭ
̓
̓
̇
Here's a more recent and in depth analysis of Appcelerator and PhoneGap: http://savagelook.com/blog/portfolio/a-deeper-look-at-appcelerator-and-phonegap
And here's even more detail on how they differ programmatically: http://savagelook.com/blog/portfolio/phonegap-is-web-based-appcelerator-is-pure-javascript
<script type="text/javascript">
jQuery(function () {
var container = jQuery("\#content");
jQuery(container)
.kendoGrid({
selectable: "single row",
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
dataType: "json",
},
},
batch: true,
}),
editable: "popup",
columns: [
{ field: "Id", title: "Id", width: 250, hidden: true },
{ field: "Data", title: "Message Body", width: 100 },
{ field: "mobile", title: "Mobile Number", width: 100 },
]
});
});
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
def transpose_finite_iterable(iterable):
return zip(*iterable) # `itertools.izip` for Python 2 users
works fine for finite iterable (e.g. sequences like list
/tuple
/str
) of (potentially infinite) iterables which can be illustrated like
| |a_00| |a_10| ... |a_n0| |
| |a_01| |a_11| ... |a_n1| |
| |... | |... | ... |... | |
| |a_0i| |a_1i| ... |a_ni| |
| |... | |... | ... |... | |
where
n in N
,a_ij
corresponds to j
-th element of i
-th iterable,and after applying transpose_finite_iterable
we get
| |a_00| |a_01| ... |a_0i| ... |
| |a_10| |a_11| ... |a_1i| ... |
| |... | |... | ... |... | ... |
| |a_n0| |a_n1| ... |a_ni| ... |
Python example of such case where a_ij == j
, n == 2
>>> from itertools import count
>>> iterable = [count(), count()]
>>> result = transpose_finite_iterable(iterable)
>>> next(result)
(0, 0)
>>> next(result)
(1, 1)
But we can't use transpose_finite_iterable
again to return to structure of original iterable
because result
is an infinite iterable of finite iterables (tuple
s in our case):
>>> transpose_finite_iterable(result)
... hangs ...
Traceback (most recent call last):
File "...", line 1, in ...
File "...", line 2, in transpose_finite_iterable
MemoryError
So how can we deal with this case?
deque
After we take a look at docs of itertools.tee
function, there is Python recipe that with some modification can help in our case
def transpose_finite_iterables(iterable):
iterator = iter(iterable)
try:
first_elements = next(iterator)
except StopIteration:
return ()
queues = [deque([element])
for element in first_elements]
def coordinate(queue):
while True:
if not queue:
try:
elements = next(iterator)
except StopIteration:
return
for sub_queue, element in zip(queues, elements):
sub_queue.append(element)
yield queue.popleft()
return tuple(map(coordinate, queues))
let's check
>>> from itertools import count
>>> iterable = [count(), count()]
>>> result = transpose_finite_iterables(transpose_finite_iterable(iterable))
>>> result
(<generator object transpose_finite_iterables.<locals>.coordinate at ...>, <generator object transpose_finite_iterables.<locals>.coordinate at ...>)
>>> next(result[0])
0
>>> next(result[0])
1
Now we can define general function for working with iterables of iterables ones of which are finite and another ones are potentially infinite using functools.singledispatch
decorator like
from collections import (abc,
deque)
from functools import singledispatch
@singledispatch
def transpose(object_):
"""
Transposes given object.
"""
raise TypeError('Unsupported object type: {type}.'
.format(type=type))
@transpose.register(abc.Iterable)
def transpose_finite_iterables(object_):
"""
Transposes given iterable of finite iterables.
"""
iterator = iter(object_)
try:
first_elements = next(iterator)
except StopIteration:
return ()
queues = [deque([element])
for element in first_elements]
def coordinate(queue):
while True:
if not queue:
try:
elements = next(iterator)
except StopIteration:
return
for sub_queue, element in zip(queues, elements):
sub_queue.append(element)
yield queue.popleft()
return tuple(map(coordinate, queues))
def transpose_finite_iterable(object_):
"""
Transposes given finite iterable of iterables.
"""
yield from zip(*object_)
try:
transpose.register(abc.Collection, transpose_finite_iterable)
except AttributeError:
# Python3.5-
transpose.register(abc.Mapping, transpose_finite_iterable)
transpose.register(abc.Sequence, transpose_finite_iterable)
transpose.register(abc.Set, transpose_finite_iterable)
which can be considered as its own inverse (mathematicians call this kind of functions "involutions") in class of binary operators over finite non-empty iterables.
As a bonus of singledispatch
ing we can handle numpy
arrays like
import numpy as np
...
transpose.register(np.ndarray, np.transpose)
and then use it like
>>> array = np.arange(4).reshape((2,2))
>>> array
array([[0, 1],
[2, 3]])
>>> transpose(array)
array([[0, 2],
[1, 3]])
Since transpose
returns iterators and if someone wants to have a tuple
of list
s like in OP -- this can be made additionally with map
built-in function like
>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple(map(list, transpose(original)))
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])
I've added generalized solution to lz
package from 0.5.0
version which can be used like
>>> from lz.transposition import transpose
>>> list(map(tuple, transpose(zip(range(10), range(10, 20)))))
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19)]
There is no solution (at least obvious) for handling potentially infinite iterable of potentially infinite iterables, but this case is less common though.
I also had an issue on a site I was working on last week. I implemented a like box and tested the like box. Then I went ahead to add an image to my header (the ob:image meta). Still the correct image did not show up on my facebook notification.
I tried everything, and came to the conclusion that every single implementation of a like button is cached. So let's say you clock the Like button on url A, then you specify an image in the header and you test it by clicking the Luke button again on url A. You won't see the image as the page is cached. The image will show up when you click on the Like button on page B.
To reset the cache, you have to use the lint debugger tool that's mentioned above, and validate all the Urls for those that are cached... That's the only thing that worked for me.
If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...
Just add this somewhere in your code:
$(document).ready(
$('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
e.preventDefault();
}),
$('[data-toggle="collapse"]').on('click', function(e) {
e.preventDefault();
$($(this).data('target')).toggleClass('in');
})
);
I found a solution using AutoLayout in StoryBoard.
1) Set no of lines to 0 and text alignment to Left.
2) Set height constraint.
3) The height Constraint should be in Relation - Less Than or Equal
4)
override func viewWillLayoutSubviews() {
sampleLabel.sizeToFit()
}
I got the result as follows :
Sometimes it is just easier to try something simple like this.
validateNumber(control: FormControl): { [s: string]: boolean } {
//revised to reflect null as an acceptable value
if (control.value === null) return null;
// check to see if the control value is no a number
if (isNaN(control.value)) {
return { 'NaN': true };
}
return null;
}
Hope this helps.
updated as per comment, You need to to call the validator like this
number: new FormControl('',[this.validateNumber.bind(this)])
The bind(this) is necessary if you are putting the validator in the component which is how I do it.
You can run command like this
php artisan migrate --path=/database/migrations/2020_04_10_130703_create_test_table.php
If you can, use boost shared_ptr and standard C++ auto_ptr. Those convey ownership semantics.
When you return an auto_ptr, you are telling the caller that you are giving them ownership of the memory.
When you return a shared_ptr, you are telling the caller that you have a reference to it and they take part of the ownership, but it isn't solely their responsibility.
These semantics also apply to parameters. If the caller passes you an auto_ptr, they are giving you ownership.
In my Spring Boot app I resolved a similar type of issue like this:
@Autowired
private EntityManager entityManager;
public User findByEmail(String email) {
User user = null;
Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.email=:email");
query.setParameter("email", email);
try {
user = (User) query.getSingleResult();
} catch (Exception e) {
// Handle exception
}
return user;
}
The "table-column" display type means it acts like the <col>
tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.
See the W3C standard for more information about the CSS table model.
* And a few other properties like borders, backgrounds.
public class prime{
public static void main(String ar[])
{
int count;
int no=0;
for(int i=0;i<1000;i++){
count=0;
for(int j=1;j<=i;j++){
if(i%j==0){
count++;
}
}
if(count==2){
no++;
if(no==Integer.parseInt(ar[0])){
System.out.println(no+"\t"+i+"\t") ;
}
}
}
}
}
All of the answers are good but not complete. Use this.
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:background="@drawable/text_area_background"
android:gravity="start|top"
android:hint="@string/write_your_comments"
android:imeOptions="actionDone"
android:importantForAutofill="no"
android:inputType="textMultiLine"
android:padding="12dp" />
I am sharing my code. form1.cs:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BorderExp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
}
private void ExitClick(object sender, EventArgs e)
{
Application.Exit();
}
private void MaxClick(object sender, EventArgs e)
{
if (WindowState ==FormWindowState.Normal)
{
this.WindowState = FormWindowState.Maximized;
}
else
{
this.WindowState = FormWindowState.Normal;
}
}
private void MinClick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
}
}
Now, the designer:-
namespace BorderExp
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.BackColor = System.Drawing.SystemColors.ButtonFace;
this.button1.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.button1.FlatAppearance.BorderSize = 0;
this.button1.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Location = new System.Drawing.Point(376, 1);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(27, 26);
this.button1.TabIndex = 0;
this.button1.Text = "X";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.ExitClick);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button2.BackColor = System.Drawing.SystemColors.ButtonFace;
this.button2.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.button2.FlatAppearance.BorderSize = 0;
this.button2.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.Location = new System.Drawing.Point(343, 1);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(27, 26);
this.button2.TabIndex = 1;
this.button2.Text = "[]";
this.button2.UseVisualStyleBackColor = false;
this.button2.Click += new System.EventHandler(this.MaxClick);
//
// button3
//
this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button3.BackColor = System.Drawing.SystemColors.ButtonFace;
this.button3.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.button3.FlatAppearance.BorderSize = 0;
this.button3.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button3.Location = new System.Drawing.Point(310, 1);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(27, 26);
this.button3.TabIndex = 2;
this.button3.Text = "___";
this.button3.UseVisualStyleBackColor = false;
this.button3.Click += new System.EventHandler(this.MinClick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.ClientSize = new System.Drawing.Size(403, 320);
this.ControlBox = false;
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
}
}
the screenshot:- NoBorderForm
SQL Server was not configured to allow mixed authentication.
Here are steps to fix:
Select the SQL Server and Windows Authentication mode radio button, and click OK.
Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).
This is also incredibly helpful for IBM Connections users, my wizards were not able to connect until I fxed this setting.
Generally, we save the model and weights in the same file by calling the save()
function.
For saving,
model.compile(optimizer='adam',
loss = 'categorical_crossentropy',
metrics = ["accuracy"])
model.fit(X_train, Y_train,
batch_size = 32,
epochs= 10,
verbose = 2,
validation_data=(X_test, Y_test))
#here I have use filename as "my_model", you can choose whatever you want to.
model.save("my_model.h5") #using h5 extension
print("model saved!!!")
For Loading the model,
from keras.models import load_model
model = load_model('my_model.h5')
model.summary()
In this case, we can simply save and load the model without re-compiling our model again. Note - This is the preferred way for saving and loading your Keras model.
It is hard to tell for sure, but here are two "close" things that can help.
$ ps aux
will give you Virtual Size (VSZ)
You can also get detailed statistics from the /proc file-system by going to /proc/$pid/status
.
The most important is the VmSize, which should be close to what ps aux
gives.
/proc/19420$ cat status Name: firefox State: S (sleeping) Tgid: 19420 Pid: 19420 PPid: 1 TracerPid: 0 Uid: 1000 1000 1000 1000 Gid: 1000 1000 1000 1000 FDSize: 256 Groups: 4 6 20 24 25 29 30 44 46 107 109 115 124 1000 VmPeak: 222956 kB VmSize: 212520 kB VmLck: 0 kB VmHWM: 127912 kB VmRSS: 118768 kB VmData: 170180 kB VmStk: 228 kB VmExe: 28 kB VmLib: 35424 kB VmPTE: 184 kB Threads: 8 SigQ: 0/16382 SigPnd: 0000000000000000 ShdPnd: 0000000000000000 SigBlk: 0000000000000000 SigIgn: 0000000020001000 SigCgt: 000000018000442f CapInh: 0000000000000000 CapPrm: 0000000000000000 CapEff: 0000000000000000 Cpus_allowed: 03 Mems_allowed: 1 voluntary_ctxt_switches: 63422 nonvoluntary_ctxt_switches: 7171
There is part of the spec that sure sounds like this... right in the "flex layout algorithm" and "main sizing" sections:
Otherwise, starting from the first uncollected item, collect consecutive items one by one until the first time that the next collected item would not fit into the flex container’s inner main size, or until a forced break is encountered. If the very first uncollected item wouldn’t fit, collect just it into the line. A break is forced wherever the CSS2.1 page-break-before/page-break-after [CSS21] or the CSS3 break-before/break-after [CSS3-BREAK] properties specify a fragmentation break.
From http://www.w3.org/TR/css-flexbox-1/#main-sizing
It sure sounds like (aside from the fact that page-breaks ought to be for printing), when laying out a potentially multi-line flex layout (which I take from another portion of the spec is one without flex-wrap: nowrap
) a page-break-after: always
or break-after: always
should cause a break, or wrap to the next line.
.flex-container {
display: flex;
flex-flow: row wrap;
}
.child {
flex-grow: 1;
}
.child.break-here {
page-break-after: always;
break-after: always;
}
However, I have tried this and it hasn't been implemented that way in...
It does work the way it sounds (to me, at least) like in:
Sample at http://codepen.io/morewry/pen/JoVmVj.
I didn't find any other requests in the bug tracker, so I reported it at https://code.google.com/p/chromium/issues/detail?id=473481.
But the topic took to the mailing list and, regardless of how it sounds, that's not what apparently they meant to imply, except I guess for pagination. So there's no way to wrap before or after a particular box in flex layout without nesting successive flex layouts inside flex children or fiddling with specific widths (e.g. flex-basis: 100%
).
This is deeply annoying, of course, since working with the Firefox implementation confirms my suspicion that the functionality is incredibly useful. Aside from the improved vertical alignment, the lack obviates a good deal of the utility of flex layout in numerous scenarios. Having to add additional wrapping tags with nested flex layouts to control the point at which a row wraps increases the complexity of both the HTML and CSS and, sadly, frequently renders order
useless. Similarly, forcing the width of an item to 100%
reduces the "responsive" potential of the flex layout or requires a lot of highly specific queries or count selectors (e.g. the techniques that may accomplish the general result you need that are mentioned in the other answers).
At least floats had clear
. Something may get added at some point or another for this, one hopes.
Here is short Scala solution:
def bfs(nodes: List[Node]): List[Node] = {
if (nodes.nonEmpty) {
nodes ++ bfs(nodes.flatMap(_.children))
} else {
List.empty
}
}
Idea of using return value as accumulator is well suited. Can be implemented in other languages in similar way, just make sure that your recursive function process list of nodes.
Test code listing (using @marco test tree):
import org.scalatest.FlatSpec
import scala.collection.mutable
class Node(val value: Int) {
private val _children: mutable.ArrayBuffer[Node] = mutable.ArrayBuffer.empty
def add(child: Node): Unit = _children += child
def children = _children.toList
override def toString: String = s"$value"
}
class BfsTestScala extends FlatSpec {
// 1
// / | \
// 2 3 4
// / | | \
// 5 6 7 8
// / | | \
// 9 10 11 12
def tree(): Node = {
val root = new Node(1)
root.add(new Node(2))
root.add(new Node(3))
root.add(new Node(4))
root.children(0).add(new Node(5))
root.children(0).add(new Node(6))
root.children(2).add(new Node(7))
root.children(2).add(new Node(8))
root.children(0).children(0).add(new Node(9))
root.children(0).children(0).add(new Node(10))
root.children(2).children(0).add(new Node(11))
root.children(2).children(0).add(new Node(12))
root
}
def bfs(nodes: List[Node]): List[Node] = {
if (nodes.nonEmpty) {
nodes ++ bfs(nodes.flatMap(_.children))
} else {
List.empty
}
}
"BFS" should "work" in {
println(bfs(List(tree())))
}
}
Output:
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
def anotherFunction(word):
for letter in word:
print("_", end=" ")
def oneFunction(lists):
category = random.choice(list(lists.keys()))
word = random.choice(lists[category])
return anotherFunction(word)
Here's another way of attaching the event based on W3C DOM Level 2 Events Specification:
transport_select.addEventListener(
'change',
function() { toggleSelect(this.id); },
false
);
You JSON is not a valid string as P. Galbraith has told you above.
and here is the solution for it.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Use this code it will work for you.
Use the valgrind option --track-origins=yes
to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.
Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:
It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.
From the Valgrind FAQ:
As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.
You can use the following code;
var example: String = "Hello World \r\n This is a new line"
Here is an answer from a bit of an abstract, graph theoretic angle:
Let's simplify the problem by only looking at (directed) dependency graphs between stateful objects.
An extremely simple answer can be illustrated by considering two limiting cases of dependency graphs:
The 1st limiting case: a cluster graphs .
A cluster graph is the most perfect realisation of a high cohesion and low coupling (given a set of cluster sizes) dependency graph.
The dependence between clusters is maximal (fully connected), and inter cluster dependence is minimal (zero).
This is an abstract illustration of the answer in one of the limiting cases.
The 2nd limiting case is a fully connected graph, where everything depends on everything.
Reality is somewhere in between, the closer to the cluster graph the better, in my humble understanding.
From another point of view: when looking at a directed dependency graph, ideally it should be acyclic, if not then cycles form the smallest clusters/components.
One step up/down the hierarchy corresponds to "one instance" of loose coupling, tight cohesion in a software but it is possible to view this loose coupling/tight cohesion principle as a repeating phenomena at different depths of an acyclic directed graph (or on one of its spanning tree's).
Such decomposition of a system into a hierarchy helps to beat exponential complexity (say each cluster has 10 elements). Then at 6 layers it's already 1 million objects:
10 clusters form 1 supercluster, 10 superclusters form 1 hypercluster and so on ... without the concept of tight cohesion, loose coupling, such a hierarchical architecture would not be possible.
So this might be the real importance of the story and not just the high cohesion low coupling within two layers only. The real importance becomes clear when considering higher level abstractions and their interactions.
First of all jar
creates a jar, and does not run it. Try java -jar
instead.
Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2
) and as file (com/mycomp/myproj/dir2/MainClass2.class
)?
Edit:
It seems as if java -jar
requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ...
instead. -cp
sets the jar on the classpath and enables java to look up the main class there.
On Centos7, It is important to note that while you remove jenkins using following command: sudo yum remove jenkins
it will not remove your users and other information. For that you will have to do following: sudo rm -r /var/lib/jenkins
First, let's note that git push
"wants" two more arguments and will make them up automatically if you don't supply them. The basic command is therefore git push remote refspec
.
The remote
part is usually trivial as it's almost always just the word origin
. The trickier part is the refspec
. Most commonly, people write a branch name here: git push origin master
, for instance. This uses your local branch to push to a branch of the same name1 on the remote, creating it if necessary. But it doesn't have to be just a branch name.
In particular, a refspec
has two colon-separated parts. For git push
, the part on the left identifies what to push,2 and the part on the right identifies the name to give to the remote. The part on the left in this case would be branch_name
and the part on the right would be branch_name_test
. For instance:
git push origin foo:foo_test
As you are doing the push, you can tell your git push
to set your branch's upstream name at the same time, by adding -u
to the git push
options. Setting the upstream name makes your git save the foo_test
(or whatever) name, so that a future git push
with no arguments, while you're on the foo
branch, can try to push to foo_test
on the remote (git also saves the remote, origin
in this case, so that you don't have to enter that either).
You need only pass -u
once: it basically just runs git branch --set-upstream-to
for you. (If you pass -u
again later, it re-runs the upstream-setting, changing it as directed; or you can run git branch --set-upstream-to
yourself.)
However, if your git is 2.0 or newer, and you have not set any special configuration, you will run into the same kind of thing that had me enter footnote 1 above: push.default
will be set to simple
, which will refuse to push because the upstream's name differs from your own local name. If you set push.default
to upstream
, git will stop complaining—but the simplest solution is just to rename your local branch first, so that the local and remote names match. (What settings to set, and/or whether to rename your branch, are up to you.)
1More precisely, git consults your remote.remote.push
setting to derive the upstream half of the refspec. If you haven't set anything here, the default is to use the same name.
2This doesn't have to be a branch name. For instance, you can supply HEAD
, or a commit hash, here. If you use something other than a branch name, you may have to spell out the full refs/heads/branch
on the right, though (it depends on what names are already on the remote).
for VS code and later versions Ctrl + P to open and then writing Whitespace, you can select the View: Toggle Render Whitespace
Found this useful - ensures the compiled Assembly references everything you currently have referenced, since there's a good chance you wanted the C# you're compiling to use some classes etc in the code that's emitting this:
(string code
is the dynamic C# being compiled)
var refs = AppDomain.CurrentDomain.GetAssemblies();
var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
compileParams.GenerateInMemory = true;
compileParams.GenerateExecutable = false;
var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
var asm = compilerResult.CompiledAssembly;
In my case I was emitting a class, whose name was stored in a string, className
, which had a single public static method named Get()
, that returned with type StoryDataIds
. Here's what calling that method looks like:
var tempType = asm.GetType(className);
var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);
Warning: Compilation can be surprisingly, extremely slow. A small, relatively simple 10-line chunk of code compiles at normal priority in 2-10 seconds on our relatively fast server. You should never tie calls to CompileAssemblyFromSource()
to anything with normal performance expectations, like a web request. Instead, proactively compile code you need on a low-priority thread and have a way of dealing with code that requires that code to be ready, until it's had a chance to finish compiling. For example you could use it in a batch job process.
Reloading the configuration file (my.cnf
) cannot be done without restarting the mysqld
server.
FLUSH LOGS
only rotates a few log files.
SET @@...=...
sets it for anyone not yet logged in, but it will go away after the next restart. But that gives a clue... Do the SET
, and change my.cnf
; that way you are covered. Caveat: Not all settings can be performed via SET
.
New with MySQL 8.0...
SET PERSIST ...
will set the global setting and save it past restarts. Nearly all settings can be adjusted this way.
I developed a software tool that opens (most) Pickle files directly in your browser (nothing is transferred so it's 100% private):
Setting thoses two properties were enough to make it work for me, and doesn't expose to security issues :
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
Collections.sort
allows you to pass an instance of a Comparator
which defines the sorting logic. So instead of sorting the list in natural order and then reversing it, one can simply pass Collections.reverseOrder()
to sort
in order to sort the list in reverse order:
// import java.util.Collections;
Collections.sort(testList, Collections.reverseOrder());
As mentioned by @Marco13, apart from being more idiomatic (and possibly more efficient), using the reverse order comparator makes sure that the sort is stable (meaning that the order of elements will not be changed when they are equal according to the comparator, whereas reversing will change the order)
I'm updating this answer since is very useful. Just add readonly to the input.
So the form will be:
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<input type="textbox" name="Percentage" value="100" readonly/>
</form>
I'm not sure how to do it with curl, but libwww-perl installs the GET alias.
$ GET -S -d -e http://google.com
GET http://google.com --> 301 Moved Permanently
GET http://www.google.com/ --> 302 Found
GET http://www.google.ca/ --> 200 OK
Cache-Control: private, max-age=0
Connection: close
Date: Sat, 19 Jun 2010 04:11:01 GMT
Server: gws
Content-Type: text/html; charset=ISO-8859-1
Expires: -1
Client-Date: Sat, 19 Jun 2010 04:11:01 GMT
Client-Peer: 74.125.155.105:80
Client-Response-Num: 1
Set-Cookie: PREF=ID=a1925ca9f8af11b9:TM=1276920661:LM=1276920661:S=ULFrHqOiFDDzDVFB; expires=Mon, 18-Jun-2012 04:11:01 GMT; path=/; domain=.google.ca
Title: Google
X-XSS-Protection: 1; mode=block
C# 7.0 now has binary literals, which is awesome.
[Flags]
enum Days
{
None = 0,
Sunday = 0b0000001,
Monday = 0b0000010, // 2
Tuesday = 0b0000100, // 4
Wednesday = 0b0001000, // 8
Thursday = 0b0010000, // 16
Friday = 0b0100000, // etc.
Saturday = 0b1000000,
Weekend = Saturday | Sunday,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}
Since the topic seems to have turned to declaring bit-based flag values in enums, I thought it would be worth pointing out a handy trick for this sort of thing. The left-shift operator (<<
) will allow you to push a bit to a specific binary position. Combine that with the ability to declare enum values in terms of other values in the same class, and you have a very easy-to-read declarative syntax for bit flag enums.
[Flags]
enum Days
{
None = 0,
Sunday = 1,
Monday = 1 << 1, // 2
Tuesday = 1 << 2, // 4
Wednesday = 1 << 3, // 8
Thursday = 1 << 4, // 16
Friday = 1 << 5, // etc.
Saturday = 1 << 6,
Weekend = Saturday | Sunday,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}
If, for example, x = 5 and is stored as string, you can also just:
x = x + 0
and the new x would be stored as a numeric value.
I believe that XDocument
makes a lot more object creation calls. I suspect that for when you're handling a lot of XML documents, XMLDocument
will be faster.
One place this happens is in managing scan data. Many scan tools output their data in XML (for obvious reasons). If you have to process a lot of these scan files, I think you'll have better performance with XMLDocument
.
Just in case anyone got to a desperate point where nothing works... It happened to us that the content assist somehow shrunk so no suggestion was shown, just the "Press Ctrl+Space for non-Java..." could be seen. So, it was just a matter of dragging the corner of the content assist to enlarge the pop-up.
I know, embarrassing. Hope it helps.
Note: this was an Ubuntu server with Xfce4 using Eclipse Oxygen.
Maybe you are looking for Vector
. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList
instead.
Method One (Small Sites Only):
Serve encrypted / encoded data.
I Scape the web using python (urllib, requests, beautifulSoup etc...) and found many websites that serve encrypted / encoded data that is not decrypt-able in any programming language simply because the encryption method does not exist.
I achieved this in a PHP website by encrypting and minimizing the output (WARNING: this is not a good idea for large sites) the response was always jumbled content.
Example of minimizing output in PHP (How to minify php page html output?):
<?php
function sanitize_output($buffer) {
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s' // shorten multiple whitespace sequences
);
$replace = array('>', '<', '\\1');
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
ob_start("sanitize_output");
?>
Method Two:
If you can't stop them screw them over serve fake / useless data as a response.
Method Three:
block common scraping user agents, you'll see this in major / large websites as it is impossible to scrape them with "python3.4" as you User-Agent.
Method Four:
Make sure all the user headers are valid, I sometimes provide as many headers as possible to make my scraper seem like an authentic user, some of them are not even true or valid like en-FU :).
Here is a list of some of the headers I commonly provide.
headers = {
"Requested-URI": "/example",
"Request-Method": "GET",
"Remote-IP-Address": "656.787.909.121",
"Remote-IP-Port": "69696",
"Protocol-version": "HTTP/1.1",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip,deflate",
"Accept-Language": "en-FU,en;q=0.8",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Dnt": "1",
"Host": "http://example.com",
"Referer": "http://example.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"
}
If you are using maven project then you just need to add the jstl-1.2 jar in your dependency. If you are simply adding the jar to your project then it's possible that jar file is not added in your project project artifact. You simply need to add the jar file in WEB-INF/lib file.
This is how your project should look when jstl is not added to the artifact. Just hit the fix button and intellij will add the jar file in the above mentioned path. Run the project and bang.
If you just want simple parallelism, you can do this:
var bag = new ConcurrentBag<object>();
var tasks = myCollection.Select(async item =>
{
// some pre stuff
var response = await GetData(item);
bag.Add(response);
// some post stuff
});
await Task.WhenAll(tasks);
var count = bag.Count;
If you need something more complex, check out Stephen Toub's ForEachAsync
post.
In Info Plist file Add a row for following property
Property Name : View controller-based status bar appearance
Value : NO
Addon for Ubuntu (Ubuntu 10.04 LTS (Lucid Lynx)):
The repository moved, but a
pip install -e git+http://github.com/scipy/scipy/#egg=scipy
failed for me... With the following steps, it finally worked out (as root in a virtual environment, where python3
is a link to Python 3.2.2):
install the Ubuntu dependencies (see elaichi), clone NumPy and SciPy:
git clone git://github.com/scipy/scipy.git scipy
git clone git://github.com/numpy/numpy.git numpy
Build NumPy (within the numpy
folder):
python3 setup.py build --fcompiler=gnu95
Install SciPy (within the scipy
folder):
python3 setup.py install
ncftp -u <user> -p <pass> <server>
ncftp> mget directory
Still using empty strings you can use:
document.getElementById("name").value = '';
document.getElementById("review").value = '';
The path is different if you're talking ASP.NET.
I couldn't find any of the 'SpecialFolder' values that pointed to /App_Data for ASP.NET.
Instead you need to do this:
HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data")
(Note: You don't need the 'Current' property in an MVC Controller)
If theres another more 'abstract' way to get to App_Data
would love to hear how.
Keytool comes with your Java library. So you have to execute the Keytool command from your /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/bin directory. Or you can add JAVA_HOME to your environmental variables (Windows) or ~/.bash_profile (Linux)
I have faced similar problem, using the same post and and this link I have resolved my issue.
var http = new XMLHttpRequest();
var url = "MY_URL.Com/login.aspx";
var params = 'eid=' +userEmailId+'&pwd='+userPwd
http.open("POST", url, true);
// Send the proper header information along with the request
//http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
//http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"
// Call a function when the state
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
This link has completed information.
the shortest code is :
JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));
stringPictureURL is PATH of image .
There is actually a way to test methods from a private member with Mockito. Let's say you have a class like this:
public class A {
private SomeOtherClass someOtherClass;
A() {
someOtherClass = new SomeOtherClass();
}
public void method(boolean b){
if (b == true)
someOtherClass.method1();
else
someOtherClass.method2();
}
}
public class SomeOtherClass {
public void method1() {}
public void method2() {}
}
If you want to test a.method
will invoke a method from SomeOtherClass
, you can write something like below.
@Test
public void testPrivateMemberMethodCalled() {
A a = new A();
SomeOtherClass someOtherClass = Mockito.spy(new SomeOtherClass());
ReflectionTestUtils.setField( a, "someOtherClass", someOtherClass);
a.method( true );
Mockito.verify( someOtherClass, Mockito.times( 1 ) ).method1();
}
ReflectionTestUtils.setField();
will stub the private member with something you can spy on.
You could try the classic MySQL world database.
The world.sql file is available for download here:
http://dev.mysql.com/doc/index-other.html
Just scroll down to Example Databases and you will find it.
Opaque will cause less system strain since 'transparent' will still attempt to apply alpha. The reason you see transparent used instead is because most web authors don't pay attention to detail (ie, just copy-pasted some embed code they found).
BTW, you are correct about it being undocumented. The best I've ever seen is a blog by a guy who claims to have talked to a Macromedia developer about it. Unfortunaetly I can't find the link.
EDIT: I think it was this one: http://www.communitymx.com/content/article.cfm?cid=e5141
Maybe this can help: Advanced Python Scheduler
Here's a small piece of code from their documentation:
from apscheduler.schedulers.blocking import BlockingScheduler
def some_job():
print "Decorated job"
scheduler = BlockingScheduler()
scheduler.add_job(some_job, 'interval', hours=1)
scheduler.start()
When you start using switch statements within your views, that usually indicate that you can further re-factor your code. Business logic is not meant for views, I would rather suggest you to do the switch statement within your controller and then pass the switch statements outcome to the view.
For me the following solution worked:
1] Going to BIOS setting and enabling Virtualization.
font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")
Use this code to get Registration ID using GCM
String regId = "", msg = "";
public void getRegisterationID() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(Login.this);
}
regId = gcm.register(YOUR_SENDER_ID);
Log.d("in async task", regId);
// try
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
and don't forget to write permissions in manifest...
I hope it helps!
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
I fixed it by removing float:left
, and adding display:inline-block
instead. Haven't used it for images, but should work fine, there, too.
The GNU libc will print out information to /dev/tty
regarding some fatal conditions before it calls abort()
(which then triggers SIGABRT
), but if you are running your program as a service or otherwise not in a real terminal window, these message can get lost, because there is no tty to display the messages.
See my post on redirecting libc to write to stderr instead of /dev/tty:
Downloading java dependencies is possible, if you actually really need to download them into a folder.
Example:
apply plugin: 'java'
dependencies {
runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2'
runtime group: 'org.apache.zookeeper', name: 'zookeeper', version: '3.4.6'
}
repositories { mavenCentral() }
task getDeps(type: Copy) {
from sourceSets.main.runtimeClasspath
into 'runtime/'
}
Download the dependencies (and their dependencies) into the folder runtime
when you execute gradle getDeps
.
Go to Window -> Preferences and type tab as the search text (which will display a dialog like below):
Go to the highlighted sections to change the tab policy. For the Editor settings it is mostly Indent using spaces (also shown above).
For Formatter settings you need to edit the active profile and update Tab policy (available under `Indentation -> General settings:
This an example from my project for rating using radio
buttons and its label
s
<div class="rating">
<%= form.radio_button :star, '1' %>
<%= form.label :star, '?', value: '1' %>
<%= form.radio_button :star, '2' %>
<%= form.label :star, '?', value: '2' %>
<%= form.radio_button :star, '3' %>
<%= form.label :star, '?', value: '3' %>
<%= form.radio_button :star, '4' %>
<%= form.label :star, '?', value: '4' %>
<%= form.radio_button :star, '5' %>
<%= form.label :star, '?', value: '5' %>
</div>
You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :
List<Book> list = new List<Book>();
return list.AsEnumerable();
This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).
OVERVIEW
I have written a simple semantic hack for this using @AshutoshMehra
response. You code looks really readable this way!
MACRO
#include <time.h>
#ifndef SYSOUT_F
#define SYSOUT_F(f, ...) _RPT1( 0, f, __VA_ARGS__ ) // For Visual studio
#endif
#ifndef speedtest__
#define speedtest__(data) for (long blockTime = NULL; (blockTime == NULL ? (blockTime = clock()) != NULL : false); SYSOUT_F(data "%.9fs", (double) (clock() - blockTime) / CLOCKS_PER_SEC))
#endif
USAGE
speedtest__("Block Speed: ")
{
// The code goes here
}
OUTPUT
Block Speed: 0.127000000s
You don't really need to have parenthesis. You can sort directly:
SELECT *, 1 AS RN FROM TABLE_A
UNION ALL
SELECT *, 2 AS RN FROM TABLE_B
ORDER BY RN, COLUMN_1
You can also reset page number counter:
\setcounter{page}{1}
However, with this technique you get wrong page numbers in Acrobat in the top left page numbers field:
\maketitle: 1
\tableofcontents: 2
\setcounter{page}{1}
\section{Introduction}: 1
...
Lot of very detailed answers here but I don't think you are answering the right questions. As I understand the question, there are two concerns:
You can use most of the scoring functions in scikit-learn with both multiclass problem as with single class problems. Ex.:
from sklearn.metrics import precision_recall_fscore_support as score
predicted = [1,2,3,4,5,1,2,1,1,4,5]
y_test = [1,2,3,4,5,1,2,1,1,4,1]
precision, recall, fscore, support = score(y_test, predicted)
print('precision: {}'.format(precision))
print('recall: {}'.format(recall))
print('fscore: {}'.format(fscore))
print('support: {}'.format(support))
This way you end up with tangible and interpretable numbers for each of the classes.
| Label | Precision | Recall | FScore | Support |
|-------|-----------|--------|--------|---------|
| 1 | 94% | 83% | 0.88 | 204 |
| 2 | 71% | 50% | 0.54 | 127 |
| ... | ... | ... | ... | ... |
| 4 | 80% | 98% | 0.89 | 838 |
| 5 | 93% | 81% | 0.91 | 1190 |
Then...
... you can tell if the unbalanced data is even a problem. If the scoring for the less represented classes (class 1 and 2) are lower than for the classes with more training samples (class 4 and 5) then you know that the unbalanced data is in fact a problem, and you can act accordingly, as described in some of the other answers in this thread. However, if the same class distribution is present in the data you want to predict on, your unbalanced training data is a good representative of the data, and hence, the unbalance is a good thing.
import { HttpClientModule } from '@angular/common/http';
The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below
http.get('friends.json').subscribe(result => this.result =result);
create a bash script with the following:
#!/bin/bash
exec ./manage.py runserver 0.0.0.0:<your_port>
save it as runserver in the same dir as manage.py
chmod +x runserver
and run it as
./runserver
It's impossible. document.cookie
contains information in string like this:
key1=value1;key2=value2;...
So there isn't any information about dates.
You can store these dates in separate cookie variable:
auth_user=Riateche;auth_expire=01/01/2012
But user can change this variable.
Slightly shorter version, without unnecessary second variable:
$csv = <<<'ENDLIST'
"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
ENDLIST;
$arr = explode("\n", $csv);
foreach ($arr as &$line) {
$line = str_getcsv($line);
}
So normally you would create a backing variable in the class and toggle it on click and tie a class binding to the variable. Something like:
@Component(
selector:'foo',
template:`<a (click)="onClick()"
[class.selected]="wasClicked">Link</a>
`)
export class MyComponent {
wasClicked = false;
onClick() {
this.wasClicked= !this.wasClicked;
}
}
In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:
On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.
After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.
To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:
JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);
And if you have an image:
JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);
But, I believe you want to make the label such that there are only 2 words on 1 line.
In that case try this:
String urText="<html>You can<br>use basic HTML<br>in Swing<br> components,"
+"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);
There is an easier way so you don't have to unload the project. Just install this tool called EditProj in Visual Studio:
https://marketplace.visualstudio.com/items?itemName=EdMunoz.EditProj
Then right click edit you will have a new menu item Edit Project File :)
i also think that link list is more better than arrays. because we do traversing in link list but not in arrays
Alex's answer needs some care (e.g. locking or a transaction) in multi-client environments.
Assuming the AUTO ID
field is the first one in the table (a usual case), we can make use of implicit
transactions.
CREATE TEMPORARY TABLE tmp SELECT * from invoices WHERE ...; ALTER TABLE tmp drop ID; # drop autoincrement field # UPDATE tmp SET ...; # just needed to change other unique keys INSERT INTO invoices SELECT 0,tmp.* FROM tmp; DROP TABLE tmp;
From the MySQL docs:
Using AUTO_INCREMENT: You can also explicitly assign NULL or 0 to the column to generate sequence numbers.
Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.
This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html
(It also includes the drag/drop interface but that's easily ignored.)
Basically what it comes down to is this:
<input id="files" type="file" />
<script>
document.getElementById('files').addEventListener('change', function(e) {
var file = this.files[0];
var xhr = new XMLHttpRequest();
(xhr.upload || xhr).addEventListener('progress', function(e) {
var done = e.position || e.loaded
var total = e.totalSize || e.total;
console.log('xhr progress: ' + Math.round(done/total*100) + '%');
});
xhr.addEventListener('load', function(e) {
console.log('xhr upload complete', e, this.responseText);
});
xhr.open('post', '/URL-HERE', true);
xhr.send(file);
});
</script>
(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)
So basically what it comes down to is this =)
xhr.send(file);
Where file
is typeof Blob
: http://www.w3.org/TR/FileAPI/
Another (better IMO) way is to use FormData
. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.
var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);
FormData
makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).
All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.
This is how I handled the request (1 image per request) in PHP:
if ( isset($_FILES['file']) ) {
$filename = basename($_FILES['file']['name']);
$error = true;
// Only upload if on my home win dev machine
if ( isset($_SERVER['WINDIR']) ) {
$path = 'uploads/'.$filename;
$error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
}
$rsp = array(
'error' => $error, // Used in JS
'filename' => $filename,
'filepath' => '/tests/uploads/' . $filename, // Web accessible
);
echo json_encode($rsp);
exit;
}
To do POST you'll need to have a form.
<form action="employee.action" method="post">
<input type="submit" value="Employee1" />
</form>
There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.
Some tricks: Make a link use POST instead of GET and How do you post data with a link
Edit: to load response on a frame you can target your form to your frame:
<form action="employee.action" method="post" target="myFrame">