It is an old article, but i want to warn people who will find it. Be careful with disabled attribute with got element by name. Strange but it seems not too work.
this do not work:
<script language="JavaScript">
function onChangeFullpageCheckbox() {
$('name=img_size').attr("disabled",$("#fullpage").attr("checked"));
</script>
this work:
<script language="JavaScript">
function onChangeFullpageCheckbox() {
$('#img_size').attr("disabled",$("#fullpage").attr("checked"));
</script>
Yes, i know that i better should use prop and not attr, but at least now prop will not work because of old version of jquery, and now i cant update it, dont ask why... html difference is only added id: ...
<select name="img_size" class="dropDown" id="img_size">
<option value="200">200px
</option><option value="300">300px
</option><option value="400">400px
</option><option value="500">500px
</option><option value="600" selected="">600px
</option><option value="800">800px
</option><option value="900">900px
</option><option value="1024">1024px
</option></select>
<input type="checkbox" name="fullpage" id="fullpage" onChange="onChangeFullpageCheckbox()" />
...
I have not found any mistakes in the script, and in the version with name, there was no errors in console. But ofcourse it can be my mistake in code
Seen on: Chrome 26 on Win 7 Pro
Sorry for bad grammar.
In the web a stateful protocol is based on having a temporary token that is exchanged between a browser and a server (via cookie header or URI rewriting) on every request. That token is usually created on the server end, and it is a piece of opaque data that has a certain time-to-live, and it has the sole purpose of identifying a specific web user agent. That is, the token is temporary, and becomes a STATE that the web server has to maintain on behalf of a client user agent during the duration of that conversation. Therefore, the communication using a token in this way is STATEFUL. And if the conversation between client and server is STATEFUL it is not RESTful.
The username/password (sent on the Authorization header) is usually persisted on the database with the intent of identifying a user. Sometimes the user could mean another application; however, the username/password is NEVER intended to identify a specific web client user agent. The conversation between a web agent and server based on using the username/password in the Authorization header (following the HTTP Basic Authorization) is STATELESS because the web server front-end is not creating or maintaining any STATE information whatsoever on behalf of a specific web client user agent. And based on my understanding of REST, the protocol states clearly that the conversation between clients and server should be STATELESS. Therefore, if we want to have a true RESTful service we should use username/password (Refer to RFC mentioned in my previous post) in the Authorization header for every single call, NOT a sension kind of token (e.g. Session tokens created in web servers, OAuth tokens created in authorization servers, and so on).
I understand that several called REST providers are using tokens like OAuth1 or OAuth2 accept-tokens to be be passed as "Authorization: Bearer " in HTTP headers. However, it appears to me that using those tokens for RESTful services would violate the true STATELESS meaning that REST embraces; because those tokens are temporary piece of data created/maintained on the server side to identify a specific web client user agent for the valid duration of a that web client/server conversation. Therefore, any service that is using those OAuth1/2 tokens should not be called REST if we want to stick to the TRUE meaning of a STATELESS protocol.
Rubens
Its undefined
because, console.log(response)
runs before doCall(urlToCall);
is finished. You have to pass in a callback function aswell, that runs when your request is done.
First, your function. Pass it a callback:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return callback(finalData);
});
}
Now:
var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
// Here you have access to your variable
console.log(response);
})
@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.
I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.
Understanding that the Angular documents call checking the $$phase
an anti-pattern, I tried to get $timeout
and _.defer
to work.
The timeout and deferred methods create a flash of unparsed {{myVar}}
content in the dom like a FOUT. For me this was not acceptable. It leaves me without much to be told dogmatically that something is a hack, and not have a suitable alternative.
The only thing that works every time is:
if(scope.$$phase !== '$digest'){ scope.$digest() }
.
I don't understand the danger of this method, or why it's described as a hack by people in the comments and the angular team. The command seems precise and easy to read:
"Do the digest unless one is already happening"
In CoffeeScript it's even prettier:
scope.$digest() unless scope.$$phase is '$digest'
What's the issue with this? Is there an alternative that won't create a FOUT? $safeApply looks fine but uses the $$phase
inspection method, too.
If you also want to give a suggested name to the file (instead of the default 'download') you can use the following in Chrome, Firefox and some IE versions:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
And the following example shows it's use:
downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");
In version 7.8, you can accomplish this without any plugins - Edit -> Line Operations -> Remove Consecutive Duplicate Lines. You will have to sort the file to place duplicate lines in consecutive order before this works, but it does work like a charm.
Sorting options are available under Edit -> Line Operations -> Sort By ...
Use the DecimalFormat class to format the double
I like the reasoning by an article from "cplusplus.com:"
Pass by value when the function does not want to modify the parameter and the value is easy to copy (ints, doubles, char, bool, etc... simple types. std::string, std::vector, and all other STL containers are NOT simple types.)
Pass by const pointer when the value is expensive to copy AND the function does not want to modify the value pointed to AND NULL is a valid, expected value that the function handles.
Pass by non-const pointer when the value is expensive to copy AND the function wants to modify the value pointed to AND NULL is a valid, expected value that the function handles.
Pass by const reference when the value is expensive to copy AND the function does not want to modify the value referred to AND NULL would not be a valid value if a pointer was used instead.
Pass by non-cont reference when the value is expensive to copy AND the function wants to modify the value referred to AND NULL would not be a valid value if a pointer was used instead.
When writing template functions, there isn't a clear-cut answer because there are a few tradeoffs to consider that are beyond the scope of this discussion, but suffice it to say that most template functions take their parameters by value or (const) reference, however because iterator syntax is similar to that of pointers (asterisk to "dereference"), any template function that expects iterators as arguments will also by default accept pointers as well (and not check for NULL since the NULL iterator concept has a different syntax).
What I take from this is that the major difference between choosing to use a pointer or reference parameter is if NULL is an acceptable value. That's it.
Whether the value is input, output, modifiable etc. should be in the documentation / comments about the function, after all.
Let's illustrate what's happening here:
Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
... def __init__(self, x=[]):
... x.append(1)
...
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)
You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults
.
As other posters have pointed out, you probably want to use None
as a sentinel value and give each instance it's own list.
Solution:
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
Model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}
Default working of EditText
:
On first click it focuses and on second click it handles onClickListener
so you need to disable focus. Then on first click the onClickListener
will handle.
To do that you need to add this android:focusableInTouchMode="false"
attribute to your EditText
. That's it!
Something like this:
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:inputType="text" />
Just copy and paste this Objective-C code.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self addRightBarButtonItem];
}
- (void) addRightBarButtonItem {
UIButton *btnAddContact = [UIButton buttonWithType:UIButtonTypeContactAdd];
[btnAddContact addTarget:self action:@selector(addCustomerPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btnAddContact];
self.navigationItem.rightBarButtonItem = barButton;
}
#pragma mark - UIButton
- (IBAction)addCustomerPressed:(id)sender {
// Your right button pressed event
}
One way would be:
import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(list(d.values()))
EDIT: The question was changed a couple years after the original post, and now asks for a pair, rather than a single item. The final line should now be:
country, capital = random.choice(list(d.items()))
In Visual Basic, do this to select a row in a DataGridView
; the selected row will appear with a highlighted color but note that the cursor position will not change:
Grid.Rows(0).Selected = True
Do this change the position of the cursor:
Grid.CurrentCell = Grid.Rows(0).Cells(0)
Combining the lines above will position the cursor and select a row. This is the standard procedure for focusing and selecting a row in a DataGridView
:
Grid.CurrentCell = Grid.Rows(0).Cells(0)
Grid.Rows(0).Selected = True
note! there is a difference between e.clientX
& e.clientY
and e.pageX
and e.pageY
try them both out and make sure you are using the proper one. clientX
and clientY
change based on scrolling position
In the answer from @mariubog (https://stackoverflow.com/a/27882337/1279002) I was using password grant types too as in the example but needed to set the client authentication scheme to form. Scopes were not supported by the endpoint for password and there was no need to set the grant type as the ResourceOwnerPasswordResourceDetails object sets this itself in the constructor.
...
public ResourceOwnerPasswordResourceDetails() {
setGrantType("password");
}
...
The key thing for me was the client_id and client_secret were not being added to the form object to post in the body if resource.setClientAuthenticationScheme(AuthenticationScheme.form);
was not set.
See the switch in:
org.springframework.security.oauth2.client.token.auth.DefaultClientAuthenticationHandler.authenticateTokenRequest()
Finally, when connecting to Salesforce endpoint the password token needed to be appended to the password.
@EnableOAuth2Client
@Configuration
class MyConfig {
@Value("${security.oauth2.client.access-token-uri}")
private String tokenUrl;
@Value("${security.oauth2.client.client-id}")
private String clientId;
@Value("${security.oauth2.client.client-secret}")
private String clientSecret;
@Value("${security.oauth2.client.password-token}")
private String passwordToken;
@Value("${security.user.name}")
private String username;
@Value("${security.user.password}")
private String password;
@Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setAccessTokenUri(tokenUrl);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setClientAuthenticationScheme(AuthenticationScheme.form);
resource.setUsername(username);
resource.setPassword(password + passwordToken);
return resource;
}
@Bean
public OAuth2RestOperations restTemplate() {
return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
}
}
@Service
@SuppressWarnings("unchecked")
class MyService {
@Autowired
private OAuth2RestOperations restTemplate;
public MyService() {
restTemplate.getAccessToken();
}
}
use the scan method e.g.
curl -XGET 'localhost:9200/_search?search_type=scan&scroll=10m&size=50' -d '
{
"query" : {
"match_all" : {}
}
}
see here
I found a website that apperars to explain the need for FirstOrDefault
http://thepursuitofalife.com/the-linq-firstordefault-method-and-null-resultsets/
If there are no results to a query, and you want to to call First() or Single() to get a single row... You will get an “Sequence contains no elements” exception.
Disclaimer: I have never used LINQ, so my apologies if this is way off the mark.
The basic one, ask tasklist to filter its output and only show the indicated process id information
tasklist /fi "pid eq 4444"
To only get the process name, the line must be splitted
for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a
In this case, the list of processes is retrieved without headers (/nh
) in csv format (/fo:csv
). The commas are used as token delimiters and the first token in the line is the image name
note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command
for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a
This will generate the task list and filter it searching for the process id in the second column of the csv output.
edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.
tasklist /fi "idp eq 4444"
This is good sample for you :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollID"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1" >
<LinearLayout
android:id="@+id/test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="true"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:weightSum="1" >
<EditText
android:id="@+id/txtInpuConversation"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:hint="@string/edt_Conversation" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnSend"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="@string/btn_Conversation" />
</LinearLayout>
</LinearLayout>
You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df_pandas = pd.DataFrame(df.head(3), columns=df.columns)
In [4]: df_pandas
Out[4]:
name age
0 Alice 1
1 Jim 2
2 Sandra 3
If your template.html
file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.
However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.
Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML
prop.
var __html = require('./template.html');
var template = { __html: __html };
React.module.exports = React.createClass({
render: function() {
return(
<div dangerouslySetInnerHTML={template} />
);
}
});
This goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.
The JSX syntax makes it trivially easy to express structured data, like HTML, especially when you use stateless function components.
If your template.html
file looked something like this
<div class='foo'>
<h1>Hello</h1>
<p>Some paragraph text</p>
<button>Click</button>
</div>
Then you could convert it instead to a JSX file that looked like this.
module.exports = function(props) {
return (
<div className='foo'>
<h1>Hello</h1>
<p>Some paragraph text</p>
<button>Click</button>
</div>
);
};
Then you can require and use it without needing stringify.
var Template = require('./template');
module.exports = React.createClass({
render: function() {
var bar = 'baz';
return(
<Template foo={bar}/>
);
}
});
It maintains all of the structure of the original file, but leverages the flexibility of React's props model and allows for compile time syntax checking, unlike a regular HTML file.
'always|withText' will work if there is sufficient room, otherwise it will only place icon. You can test it on your phone with rotation.
<item android:id="@id/menu_item"
android:title="text"
android:icon="@drawable/drawable_resource_name"
android:showAsAction="always|withText" />
View this web: http://www.w3resource.com/sql/subqueries/multiplee-row-column-subqueries.php
Use example
select ord_num, agent_code, ord_date, ord_amount
from orders
where(agent_code, ord_amount) IN
(SELECT agent_code, MIN(ord_amount)
FROM orders
GROUP BY agent_code);
WebDriver driver = new FirefoxDriver();
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
This method removes the extra call ( String.ValueOf() ) to convert unicode to string.
I have two methods, using this méthod to get the key with the max value:
public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map){
Entry<String, Integer> maxEntry = null;
Integer max = Collections.max(map.values());
for(Entry<String, Integer> entry : map.entrySet()) {
Integer value = entry.getValue();
if(null != value && max == value) {
maxEntry = entry;
}
}
return maxEntry;
}
As an example gettin the Entry with the max value using the method:
Map.Entry<String, Integer> maxEntry = getMaxEntry(map);
Using Java 8 we can get an object containing the max value:
Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();
System.out.println("maxEntry = " + maxEntry);
I know this is old but by far the easier solution is to just use
var temp = new Date("2010-08-17T12:09:36");
You are looking for the jQuery extend method. This will allow you to add other members to your already created JS object.
Another "solution": skip all this frustration and use a UIScrollView instead to get a result that looks and feels identical to UITableView.
That was the painful "solution" for me, after having put in literally 20+ very frustrating hours total trying to build something like what smileyborg suggested and failing over many months and three versions of App Store releases.
My take is that if you really need iOS 7 support (for us, it's essential) then the technology is just too brittle and you'll pull your hair out trying. And that UITableView is complete overkill generally unless you're using some of the advanced row editing features and/or really need to support 1000+ "rows" (in our app, it's realistically never more than 20 rows).
The added bonus is that the code gets insanely simple versus all the delegate crap and back and forth that comes with UITableView. It's just one single loop of code in viewOnLoad that looks elegant and is easy to manage.
Here's some tips on how to do it:
Using either Storyboard or a nib file, create a ViewController and associated root view.
Drag over a UIScrollView onto your root view.
Add constraints top, bottom, left and right constraints to the top-level view so the UIScrollView fills the entire root view.
Add a UIView inside the UIScrollView and call it "container". Add top, bottom, left and right constraints to the UIScrollView (its parent). KEY TRICK: Also add a "Equal widths" constraints to link the UIScrollView and UIView.
NOTE: You will get an error "scroll view has ambiguous scrollable content height" and that your container UIView should have a height of 0 pixels. Neither error seems to matter when the app is running.
Create nib files and controllers for each of your "cells". Use UIView not UITableViewCell.
In your root ViewController, you essentially add all the "rows" to the container UIView and programmatically add constraints linking their left and right edges to the container view, their top edges to either the container view top (for the first item) or the previous cell. Then link the final cell to the container bottom.
For us, each "row" is in a nib file. So the code looks something like this:
class YourRootViewController {
@IBOutlet var container: UIView! //container mentioned in step 4
override func viewDidLoad() {
super.viewDidLoad()
var lastView: UIView?
for data in yourDataSource {
var cell = YourCellController(nibName: "YourCellNibName", bundle: nil)
UITools.addViewToTop(container, child: cell.view, sibling: lastView)
lastView = cell.view
//Insert code here to populate your cell
}
if(lastView != nil) {
container.addConstraint(NSLayoutConstraint(
item: lastView!,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: container,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0))
}
///Add a refresh control, if you want - it seems to work fine in our app:
var refreshControl = UIRefreshControl()
container.addSubview(refreshControl!)
}
}
And here's the code for UITools.addViewToTop:
class UITools {
///Add child to container, full width of the container and directly under sibling (or container if sibling nil):
class func addViewToTop(container: UIView, child: UIView, sibling: UIView? = nil)
{
child.setTranslatesAutoresizingMaskIntoConstraints(false)
container.addSubview(child)
//Set left and right constraints so fills full horz width:
container.addConstraint(NSLayoutConstraint(
item: child,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: container,
attribute: NSLayoutAttribute.Left,
multiplier: 1,
constant: 0))
container.addConstraint(NSLayoutConstraint(
item: child,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: container,
attribute: NSLayoutAttribute.Right,
multiplier: 1,
constant: 0))
//Set vertical position from last item (or for first, from the superview):
container.addConstraint(NSLayoutConstraint(
item: child,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: sibling == nil ? container : sibling,
attribute: sibling == nil ? NSLayoutAttribute.Top : NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0))
}
}
The only "gotcha" I've found with this approach so far is that UITableView has a nice feature of "floating" section headers at the top of the view as you scroll. The above solution won't do that unless you add more programming but for our particular case this feature wasn't 100% essential and nobody noticed when it went away.
If you want dividers between your cells, just add a 1 pixel high UIView at the bottom of your custom "cell" that looks like a divider.
Be sure to turn on "bounces" and "bounce vertically" for the refresh control to work and so it seems more like a tableview.
TableView shows some empty rows and dividers under your content, if it doesn't fill the full screen where as this solution doesn't. But personally, I prefer if those empty rows weren't there anyway - with variable cell height it always looked "buggy" to me anyway to have the empty rows in there.
Here's hoping some other programmer reads my post BEFORE wasting 20+ hours trying to figure it out with Table View in their own app. :)
If you absolutely have to have the field disabled and pass the data you could use a javascript to input the same data into a hidden field (or just set the hidden field too). This would allow you to have it disabled but still post the data even though you'd be posting to another page.
First of all check error log in the path that your webserver indicates. Then maybe the browser is showing friendly error messages, so disable it.
https://superuser.com/questions/202244/show-http-error-details-in-google-chrome
This is a solution but in form of my story with this problem:
I was almost dead trying all the solution given above(for 3 days ) and nothing worked for me.
I lost all hope.
I contacted my security team regarding this because i was behind a proxy and they told that they had recently updated their security policy.
I scolded them badly for not informing the Developers.
Later they issued a new "cacerts" file which contains all the certificates.
I removed the cacerts file which is present inside %JAVA_HOME%/jre/lib/security and it solved my problem.
So if you are facing this issue it might be from your network team also like this.
Play around this piece of code. Focus on the concept, edit where necessary so that it can
<html>
<head>
<title> Delegate edit form</title>
</head>
<body>
Delegate update form </p>
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link href='http://fonts.googleapis.com/css?family=Droid+Serif|Ubuntu' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="js/flexslider/flexslider.css" />
<link rel="stylesheet" href="css/basic-style.css">
<script src="js/libs/modernizr-2.6.2.min.js"></script>
</head>
<body id="home">
<header class="wrapper clearfix">
<nav id="topnav" role="navigation">
<div class="menu-toggle">Menu</div>
<ul class="srt-menu" id="menu-main-navigation">
<li><a href="Swift_Landing.html">Home page</a></li>
</header>
</section>
<style>
form label {
display: inline-block;
width: 100px;
font-weight: bold;
}
</style>
</ul>
<?php
session_start();
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";
$Username=$_SESSION['myssession'];
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$sql = "SELECT * FROM usermaster WHERE User_name='$Username'";
$result = mysql_query ($sql) or die (mysql_error ());
while ($row = mysql_fetch_array ($result)){
?>
<form action="Delegate_update.php" method="post">
Name
<input type="text" name="Namex" value="<?php echo $row ['Name']; ?> " size=10>
Username
<input type="text" name="Username" value="<?php echo $row ['User_name']; ?> " size=10>
Password
<input type="text" name="Password" value="<?php echo $row ['User_password']; ?>" size=17>
<input type="submit" name="submit" value="Update">
</form>
<?php
}
?>
</p>
</body>
</html>
Use the Oracle 10g dialect. Also Hibernate 3.3.2+ is required for recent JDBC drivers (the internal class structure changed - symptoms will be whining about an abstract class).
Dialect of Oracle 11g is same as Oracle 10g (org.hibernate.dialect.Oracle10gDialect). Source: http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/session-configuration.html#configuration-optional-dialects
If you simply want to see the column names this one line should provide it without changing any settings:
describe database.tablename;
However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:
use database;
describe tablename;
That worked for me in python3:
import urllib.request
htmlfile = urllib.request.urlopen("http://google.com")
htmltext = htmlfile.read()
print(htmltext)
res.setHeader('Access-Control-Allow-Headers', '*');
Another modification:
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.
Also, if the server fails to respond, it won't keep trying.
I've used a similar method in the past using .ajax to handle even more complex behaviour:
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'response.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
}
This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.
This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.
There are great solutions out there, but ultimately every script will fail if you're not in the right directory. So code like this:
if [ -d "$LINK_OR_DIR" ]; then
if [ -L "$LINK_OR_DIR" ]; then
# It is a symlink!
# Symbolic link specific commands go here
rm "$LINK_OR_DIR"
else
# It's a directory!
# Directory command goes here
rmdir "$LINK_OR_DIR"
fi
fi
will execute successfully only if at the moment of execution you're in a directory that has a subdirectory that you happen to check for.
I understand the initial question like this: to verify if a directory exists irrespective of the user's position in the file system. So using the command 'find' might do the trick:
dir=" "
echo "Input directory name to search for:"
read dir
find $HOME -name $dir -type d
This solution is good because it allows the use of wildcards, a useful feature when searching for files/directories. The only problem is that, if the searched directory doesn't exist, the 'find' command will print nothing to standard output (not an elegant solution for my taste) and will have nonetheless a zero exit. Maybe someone could improve on this.
THE C WAY
You can use gets
function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets
is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream
itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
If you have jQuery UI this little function allows basic tabbing
handlePseudoTab(direction) {
if (!document.hasFocus() || !document.activeElement) {
return;
}
const focusList = $(":focusable", $yourHTMLElement);
const i = focusList.index(document.activeElement);
if (i < 0) {
focusList[0].focus(); // nothing is focussed so go to list item 0
} else if (direction === 'next' && i + 1 < focusList.length) {
focusList[i + 1].focus(); // advance one
} else if (direction === 'prev' && i - 1 > -1) {
focusList[i - 1].focus(); // go back one
}
}
In the .gitconfig file you can add the below given value to make the self signed cert acceptable
sslCAInfo = /home/XXXX/abc.crt
Remove the starting semicolon ( ; )
Like:
;extension=php_intl.dll
to extension=php_intl.dll
This helped me.
Just discovered that if the source table for a subform is updated using adodb, it takes a while until the requery can find the updated information.
In my case, I was adding some records with 'dbconn.execute "sql" ' and wondered why the requery command in vba doesn't seem to work. When I was debugging, the requery worked. Added a 2-3 second wait in the code before requery just to test made a difference.
But changing to 'currentdb.execute "sql" ' fixed the problem immediately.
In PHP there is a pretty good function utf8_encode() to solve this issue.
echo utf8_encode("Résumé");
//will output Résumé instead of R?sum?
Remove semicolon and you can see that link: http://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_HowTo.html
If you really want to dive into it and even need to distinguish between -0
and 0
, here's a way to do it.
function negative(number) {
return !Object.is(Math.abs(number), +number);
}
console.log(negative(-1)); // true
console.log(negative(1)); // false
console.log(negative(0)); // false
console.log(negative(-0)); // true
git fetch
git checkout HEAD path/to/your/dir/or/file
Where "path/...
" in (3) starts at the directory just below the repo root containing your ".../file
"
NOTE that instead of "HEAD", the hash code of a specific commit may be used, and then you will get the revision (file) or revisions (dir) specific to that commit.
I tested dkarp's solution with gmail and it was filtered to spam. Use the Reply-To header instead (or in addition, although gmail apparently doesn't need it). Here's how linkedin does it:
Sender: [email protected]
From: John Doe via LinkedIn <[email protected]>
Reply-To: John Doe <[email protected]>
To: My Name <[email protected]>
Once I switched to this format, gmail is no longer filtering my messages as spam.
Alternatively:
Save current changes to a temp stash:
$ git stash
Create a new branch based on this stash, and switch to the new branch:
$ git stash branch <new-branch> stash@{0}
Tip: use tab key to reduce typing the stash name.
Just encase someone else ran into the issues I did I was using Response.End() an async trigger button
<asp:AsyncPostBackTrigger ControlID="btn_login" />
in an update panel. I switched to regular post back not the best but it worked.
<asp:PostBackTrigger ControlID="btn_login" />.
Since I was only redirecting on the page this was a viable solution.
.section {
display: flex;
}
.element-left {
width: 94%;
}
.element-right {
flex-grow: 1;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
or
.section {
display: flex;
flex-wrap: wrap;
}
.element-left {
flex: 2;
}
.element-right {
width: 100px;
}
_x000D_
<div class="section">
<div id="dB" class="element-left" }>
<a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
</div>
<div id="gB" class="element-right">
<a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
</div>
</div>
_x000D_
It can be done using a single line:
perl -pi.back -e 's/oldString/newString/g;' inputFileName
Pay attention that oldString
is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+?
(The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \
, so \[
.
Try this Example
class InvalidInputError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
inp = int(input("Enter a number between 1 to 10:"))
try:
if type(inp) != int or inp not in list(range(1,11)):
raise InvalidInputError
except InvalidInputError:
print("Invalid input entered")
I've tried a select statement now with a PreparedStatement
, but it turned out that it was not faster than the Jdbc template. Maybe, as mezmo suggested, it automatically creates prepared statements.
Anyway, the reason for my sql SELECT
s being so slow was another one. In the WHERE
clause I always used the operator LIKE
, when all I wanted to do was finding an exact match. As I've found out LIKE
searches for a pattern and therefore is pretty slow.
I'm using the operator =
now and it's much faster.
In my case I was seeing referrals when I was accessing AD via SSO with an account in a trusted domain. The problem went away when I connected with explicit credentials in the local domain.
i.e. I replaced
DirectoryEntry de = new DirectoryEntry("blah.com");
with
DirectoryEntry de = new DirectoryEntry("blah.com", "[email protected]", "supersecret");
and the problem went away.
Let's create the dataframe in question
df_test = spark.createDataFrame(
[
(1, 5),
(2, 9),
(3, 3),
(4, 1),
],
['mvv', 'count']
)
df_test.show()
Which gives
+---+-----+
|mvv|count|
+---+-----+
| 1| 5|
| 2| 9|
| 3| 3|
| 4| 1|
+---+-----+
and then apply rdd.flatMap(f).collect() to get the list
test_list = df_test.select("mvv").rdd.flatMap(list).collect()
print(type(test_list))
print(test_list)
which gives
<type 'list'>
[1, 2, 3, 4]
The callback is made in a different context. You need to bind
to this
in order to have access inside the callback:
VK.api('users.get',{fields: 'photo_50'},function(data){
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
}.bind(this));
EDIT:
Looks like you have to bind both the init
and api
calls:
VK.init(function(){
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},function(data){
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
}.bind(this));
}.bind(this), function(){
console.info("API initialisation failed");
}, '5.34');
The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.
const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation
var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
First change the method parameter Enum supportedPermissions
to SupportedPermissions supportedPermissions
.
Then create your file like this
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
And the call to your method should be
CreateFile(id, name, description, SupportedPermissions.basic);
First of all you should create property with employee details in the Employee
class:
public class Employee
{
public Employee()
{
EmployeeDetails = new EmployeeDetails();
EmployeeDetails.EmpID = 123;
EmployeeDetails.EmpName = "ABC";
}
public EmployeeDetails EmployeeDetails { get; set; }
}
If you don't do that, you will create instance of object in Employee
constructor and you lose reference to it.
In the XAML you should create instance of Employee
class, and after that you can assign it to DataContext
.
Your XAML should look like this:
<Window x:Class="SampleApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:SampleApplication"
>
<Window.Resources>
<local:Employee x:Key="Employee" />
</Window.Resources>
<Grid DataContext="{StaticResource Employee}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
<Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
<TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
<TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
</Grid>
</Window>
Now, after you created property with employee details you should binding by using this property:
Text="{Binding EmployeeDetails.EmpID}"
var text = File.ReadAllText(file, Encoding.GetEncoding(codePage));
List of codepages : http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]
If tsStart > tsFinish Then
' Take Hours difference and adjust accordingly
tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)
' Add Minutes to Difference
tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))
' Add Seonds to Difference
tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))
<select>
<option value="" disabled="disabled" selected="selected">Please select name</option>
<option value="Tom">Tom</option>
<option value="Marry">Marry</option>
<option value="Jane">Jane</option>
<option value="Harry">Harry</option>
</select>
I often use list comprehensions for these types of tasks because they're often faster.
There can be big differences in performance between the various methods for doing things like this (i.e. modifying every element of a series within a DataFrame). Often a list comprehension can be fastest - see code race below for this task:
import pandas as pd
#Map
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))
10000 loops, best of 3: 187 µs per loop
#List comprehension
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = [x.lstrip('+-').rstrip('aAbBcC') for x in data['result']]
10000 loops, best of 3: 117 µs per loop
#.str
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = data['result'].str.lstrip('+-').str.rstrip('aAbBcC')
1000 loops, best of 3: 336 µs per loop
Ctrl+A , Ctrl+Shift+U
should do the trick!
Edit: Ctrl+U is the shortcut to be used to convert capital letters to lowercase (reverse scenario)
If you support IE, for versions of Internet Explorer 8 and above, this:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />
Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.
If you separate with semi-colon, it sets compatibility levels for different versions. For example:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />
Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:
<meta http-equiv="X-UA-Compatible" content="IE=8" />
This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
For this:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
It forces the browser the render at whatever the most recent version's standards are.
For more information, there is plenty to read about on MSDN,
I know this is an older thread but I just bumped into this. If the user is trying to run inserts on the Identity column after some other session Set IDENTITY_INSERT ON, then he is bound to get the above error.
Setting the Identity Insert value and the subsequent Insert DML commands are to be run by the same session.
Here @Beginner was setting Identity Insert ON separately and then running the inserts from his application. That is why he got the below Error:
Cannot insert explicit value for identity column in table 'Baskets' when
IDENTITY_INSERT is set to OFF.
ORA-01034 and ORA-27101 normally indicate that the database instance you're attempting to connect to is shut down and that you're not connected as a user who has permission to start it up. Log on to the server 192.168.1.53 and start up the orcl
instance, or ask your DBA to do this for you.
Solution
Angular2 developed on the ground of modern technologies like TypeScript and ES6.
So you can just do let copy = Object.assign({}, myObject)
.
Object assign - nice examples.
For nested objects :
let copy = JSON.parse(JSON.stringify(myObject))
Updating lines in place in a file is not supported on most file system (a line in a file is just some data that ends with newline, the next line start just after that).
As I see it you have two options:
Small example for the first method:
from itertools import islice, izip, count
print list(islice(izip(count(1), count(2), count(3)), 10))
This will print
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10), (9, 10, 11), (10, 11, 12)]
even though count
generate an infinite sequence of numbers
Usually StaleElementReferenceException when element we try to access has appeared but other elements may affect the position of element we are intrested in hence when we try to click or getText or try to do some action on WebElement we get exception which usually says element not attached with DOM.
Solution I tried is as follows:
protected void clickOnElement(By by) {
try {
waitForElementToBeClickableBy(by).click();
} catch (StaleElementReferenceException e) {
for (int attempts = 1; attempts < 100; attempts++) {
try {
waitFor(500);
logger.info("Stale element found retrying:" + attempts);
waitForElementToBeClickableBy(by).click();
break;
} catch (StaleElementReferenceException e1) {
logger.info("Stale element found retrying:" + attempts);
}
}
}
protected WebElement waitForElementToBeClickableBy(By by) {
WebDriverWait wait = new WebDriverWait(getDriver(), 10);
return wait.until(ExpectedConditions.elementToBeClickable(by));
}
In above code I first try to wait and then click on element if exception occurs then I catch it and try to loop it as there is a possibility that still all elements may not be loaded and again exception can occur.
This trick worked for me in Eclipse Luna (4.4.2): For a jar file I am using (htsjdk), I packed the source in a separate jar file (named htsjdk-2.0.1-src.jar; I could do this since htsjdk is open source) and stored it in the lib-src folder of my project. In my own Java source I selected an element I was using from the jar and hit F3 (Open declaration). Eclipse opened the class file and showed the button "Attach source". I clicked the button and pointed to the src jar file I had just put into the lib-src folder. Now I get the Javadoc when hovering over anything I’m using from the jar.
The better approach uses Shredder's css rule: padding: 0 15px 0 15px only instead of inline css, define a css rule that applies to all tds. Do This by using a style tag in your page:
<style type="text/css">
td
{
padding:0 15px;
}
</style>
or give the table a class like "paddingBetweenCols" and in the site css use
.paddingBetweenCols td
{
padding:0 15px;
}
The site css approach defines a central rule that can be reused by all pages.
If your doing to use the site css approach, it would be best to define a class like above and apply the padding to the class...unless you want all td's on the entire site to have the same rule applied.
I added the ISAPI/CGI paths for .Net 4. Which didn't fix the issue. So I then ran a repair on the .Net V4 (Client and Extended) installation. Which asked for a reboot. This fixed it for me.
import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
At this point you have a color and a gray image. We are dealing with 8-bit
, uint8
images here. That means the images can have pixel values in the range of [0, 255]
and the values have to be integers.
Let's do a binary thresholding operation. It creates a black and white masked image. The black regions have value 0
and the white regions 255
_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
The mask can be seen below on the left. The image on it's right is the result of applying bitwise_and
operation between the gray image and the mask. What happened is, the spatial locations where the mask had a pixel value zero (black), became pixel value zero in the result image. The locations where the mask had pixel value 255 (white), the resulting image retained it's original gray value.
To apply this mask to our original color image, we need to convert the mask into a 3 channel image as the original color image is a 3 channel image.
mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
Then, we can apply this 3 channel mask to our color image using the same bitwise_and
function.
im_thresh_color = cv.bitwise_and(im_color, mask3)
mask3
from the code is the image below on the left, and im_thresh_color
is on its right.
You can plot the results and see for yourself.
cv.imshow("original image", im_color)
cv.imshow("binary mask", mask)
cv.imshow("3 channel mask", mask3)
cv.imshow("im_thresh_gray", im_thresh_gray)
cv.imshow("im_thresh_color", im_thresh_color)
cv.waitKey(0)
The original image is lenacolor.png
that I found here.
Navigate to Sublime Text>Preferences>Browse Packages. You should see a file tree.
In the Packages folder, you should see
Theme - Default > Default.sublime-theme (substitute Default for your theme name)
Open that file and find the "class": "sidebar_label: entry and add "font.size".
example:
{
"class": "sidebar_label",
"color": [0, 0, 0],
"font.bold": false,
"font.size": 14
},
Use JavaScript setInterval()
method to redirect page after some specified time. The following script will redirect page after 5 seconds.
var count = 5;
setInterval(function(){
count--;
document.getElementById('countDown').innerHTML = count;
if (count == 0) {
window.location = 'https://www.google.com';
}
},1000);
Example script and live demo can be found from here - Redirect page after delay using JavaScript
From the docs:
urllib.quote(string[, safe])
Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'
That means passing '' for safe will solve your first issue:
>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'
About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:
>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller
By the way have a look at urlencode
The same, except replace urllib.quote
with urllib.parse.quote
.
If you're only looking for a webkit version this is nifty: http://s3.amazonaws.com/37assets/svn/463-single_spinner.html from http://37signals.com/svn/posts/2577-loading-spinner-animation-using-css-and-webkit
In case somebody prefers sed
and removing without wildcard expansion:
sed -e "s/^\(.*\)$/rm -f -- \'\1\'/" deletelist.txt | /bin/sh
Reminder: use absolute pathnames in the file or make sure you are in the right directory.
And for completeness the same with awk
:
awk '{printf "rm -f -- '\''%s'\''\n",$1}' deletelist.txt | /bin/sh
Wildcard expansion will work if the single quotes are remove, but this is dangerous in case the filename contains spaces. This would need to add quotes around the wildcards.
Sorry to reanimate a dead thread, but I have just been dealing with this myself, and after finding all sorts of crazy bloated solutions, I managed to come up with this.
[Long]$actualSize = 0
foreach ($item in (Get-ChildItem $path -recurse | Where {-not $_.PSIsContainer} | ForEach-Object {$_.FullName})) {
$actualSize += (Get-Item $item).length
}
Quickly and in few lines of code gives me a folder size in Bytes, than can easily be converted to any units you want with / 1MB
or the like.
Am I missing something? Compared to this overwrought mess it seems rather simple and to the point. Not to mention that code doesn't even work since the called function is not the same name as the defined function. And has been wrong for 6 years. ;)
So, any reasons NOT to use this stripped down approach?
Hibernate also is picky about the capitalization. By default it's going to be the class name with the First letter Capitalized. So if your class is called FooBar
, don't pass "foobar"
. You have to pass "FooBar"
with that exact capitalization for it to work.
You can use a regular expresion to for example replace all non-alphanumeric characters with commas:
s = Regex.Replace(s, "[^0-9A-Za-z]+", ",");
Note: The +
after the set will make it replace each group of non-alphanumeric characters with a comma. If you want to replace each character with a comma, just remove the +
.
Here are the Registry exports (*.reg
files) for Git GUI and Git Bash directly from the Windows installer —Git GUI:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\background\shell\git_gui]
@="Git &GUI Here"
"Icon"="C:\\Program Files\\Git\\cmd\\git-gui.exe"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\background\shell\git_gui\command]
@="\"C:\\Program Files\\Git\\cmd\\git-gui.exe\" \"--working-dir\" \"%v.\""
Git bash:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\background\shell\git_shell]
@="Git Ba&sh Here"
"Icon"="C:\\Program Files\\Git\\git-bash.exe"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\background\shell\git_shell\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%v.\""
For detail about *.reg
files, see “How to add, modify, or delete registry subkeys and values by using a .reg file” from Microsoft.
OK, you’ve been told, or have found out yourself, that globals (namespace scope variables that can be accessed outside the translation unit) are Evil™. But did you know how truly Evil™ they are? Consider the program below, consisting of two files [main.cpp] and [numbers.cpp]:
// [main.cpp]
#include <iostream>
extern int* numbers;
int main()
{
using namespace std;
for( int i = 0; i < 42; ++i )
{
cout << (i > 0? ", " : "") << numbers[i];
}
cout << endl;
}
// [numbers.cpp]
int numbers[42] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
In Windows 7 this compiles and links fine with both MinGW g++ 4.4.1 and Visual C++ 10.0.
Since the types don't match, the program crashes when you run it.
In-the-formal explanation: the program has Undefined Behavior (UB), and instead of crashing it can therefore just hang, or perhaps do nothing, or it can send threating e-mails to the presidents of the USA, Russia, India, China and Switzerland, and make Nasal Daemons fly out of your nose.
In-practice explanation: in main.cpp
the array is treated as a pointer, placed
at the same address as the array. For 32-bit executable this means that the first
int
value in the array, is treated as a pointer. I.e., in main.cpp
the
numbers
variable contains, or appears to contain, (int*)1
. This causes the
program to access memory down at very bottom of the address space, which is
conventionally reserved and trap-causing. Result: you get a crash.
The compilers are fully within their rights to not diagnose this error, because C++11 §3.5/10 says, about the requirement of compatible types for the declarations,
[N3290 §3.5/10]
A violation of this rule on type identity does not require a diagnostic.
The same paragraph details the variation that is allowed:
… declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4).
This allowed variation does not include declaring a name as an array in one translation unit, and as a pointer in another translation unit.
memset
& friends).Not written yet
With deep C experience it’s natural to write …
#define N_ITEMS( array ) (sizeof( array )/sizeof( array[0] ))
Since an array
decays to pointer to first element where needed, the
expression sizeof(a)/sizeof(a[0])
can also be written as
sizeof(a)/sizeof(*a)
. It means the same, and no matter how it’s
written it is the C idiom for finding the number elements of array.
Main pitfall: the C idiom is not typesafe. For example, the code …
#include <stdio.h>
#define N_ITEMS( array ) (sizeof( array )/sizeof( *array ))
void display( int const a[7] )
{
int const n = N_ITEMS( a ); // Oops.
printf( "%d elements.\n", n );
}
int main()
{
int const moohaha[] = {1, 2, 3, 4, 5, 6, 7};
printf( "%d elements, calling display...\n", N_ITEMS( moohaha ) );
display( moohaha );
}
passes a pointer to N_ITEMS
, and therefore most likely produces a wrong
result. Compiled as a 32-bit executable in Windows 7 it produces …
7 elements, calling display...
1 elements.
int const a[7]
to just int const a[]
.int const a[]
to int const* a
.N_ITEMS
is therefore invoked with a pointer.sizeof(array)
(size of a pointer) is then 4.sizeof(*array)
is equivalent to sizeof(int)
, which for a 32-bit executable is also 4.In order to detect this error at run time you can do …
#include <assert.h>
#include <typeinfo>
#define N_ITEMS( array ) ( \
assert(( \
"N_ITEMS requires an actual array as argument", \
typeid( array ) != typeid( &*array ) \
)), \
sizeof( array )/sizeof( *array ) \
)
7 elements, calling display...
Assertion failed: ( "N_ITEMS requires an actual array as argument", typeid( a ) != typeid( &*a ) ), file runtime_detect ion.cpp, line 16This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
The runtime error detection is better than no detection, but it wastes a little processor time, and perhaps much more programmer time. Better with detection at compile time! And if you're happy to not support arrays of local types with C++98, then you can do that:
#include <stddef.h>
typedef ptrdiff_t Size;
template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }
#define N_ITEMS( array ) n_items( array )
Compiling this definition substituted into the first complete program, with g++, I got …
M:\count> g++ compile_time_detection.cpp
compile_time_detection.cpp: In function 'void display(const int*)':
compile_time_detection.cpp:14: error: no matching function for call to 'n_items(const int*&)'M:\count> _
How it works: the array is passed by reference to n_items
, and so it does
not decay to pointer to first element, and the function can just return the
number of elements specified by the type.
With C++11 you can use this also for arrays of local type, and it's the type safe C++ idiom for finding the number of elements of an array.
constexpr
array size function.With C++11 and later it's natural, but as you'll see dangerous!, to replace the C++03 function
typedef ptrdiff_t Size;
template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }
with
using Size = ptrdiff_t;
template< class Type, Size n >
constexpr auto n_items( Type (&)[n] ) -> Size { return n; }
where the significant change is the use of constexpr
, which allows
this function to produce a compile time constant.
For example, in contrast to the C++03 function, such a compile time constant can be used to declare an array of the same size as another:
// Example 1
void foo()
{
int const x[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
constexpr Size n = n_items( x );
int y[n] = {};
// Using y here.
}
But consider this code using the constexpr
version:
// Example 2
template< class Collection >
void foo( Collection const& c )
{
constexpr int n = n_items( c ); // Not in C++14!
// Use c here
}
auto main() -> int
{
int x[42];
foo( x );
}
The pitfall: as of July 2015 the above compiles with MinGW-64 5.1.0 with
-pedantic-errors
, and,
testing with the online compilers at gcc.godbolt.org/, also with clang 3.0
and clang 3.2, but not with clang 3.3, 3.4.1, 3.5.0, 3.5.1, 3.6 (rc1) or
3.7 (experimental). And important for the Windows platform, it does not compile
with Visual C++ 2015. The reason is a C++11/C++14 statement about use of
references in constexpr
expressions:
A conditional-expression
e
is a core constant expression unless the evaluation ofe
, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
?
- an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
- it is initialized with a constant expression or
- it is a non-static data member of an object whose lifetime began within the evaluation of e;
One can always write the more verbose
// Example 3 -- limited
using Size = ptrdiff_t;
template< class Collection >
void foo( Collection const& c )
{
constexpr Size n = std::extent< decltype( c ) >::value;
// Use c here
}
… but this fails when Collection
is not a raw array.
To deal with collections that can be non-arrays one needs the overloadability of an
n_items
function, but also, for compile time use one needs a compile time
representation of the array size. And the classic C++03 solution, which works fine
also in C++11 and C++14, is to let the function report its result not as a value
but via its function result type. For example like this:
// Example 4 - OK (not ideal, but portable and safe)
#include <array>
#include <stddef.h>
using Size = ptrdiff_t;
template< Size n >
struct Size_carrier
{
char sizer[n];
};
template< class Type, Size n >
auto static_n_items( Type (&)[n] )
-> Size_carrier<n>;
// No implementation, is used only at compile time.
template< class Type, size_t n > // size_t for g++
auto static_n_items( std::array<Type, n> const& )
-> Size_carrier<n>;
// No implementation, is used only at compile time.
#define STATIC_N_ITEMS( c ) \
static_cast<Size>( sizeof( static_n_items( c ).sizer ) )
template< class Collection >
void foo( Collection const& c )
{
constexpr Size n = STATIC_N_ITEMS( c );
// Use c here
(void) c;
}
auto main() -> int
{
int x[42];
std::array<int, 43> y;
foo( x );
foo( y );
}
About the choice of return type for static_n_items
: this code doesn't use std::integral_constant
because with std::integral_constant
the result is represented
directly as a constexpr
value, reintroducing the original problem. Instead
of a Size_carrier
class one can let the function directly return a
reference to an array. However, not everybody is familiar with that syntax.
About the naming: part of this solution to the constexpr
-invalid-due-to-reference
problem is to make the choice of compile time constant explicit.
Hopefully the oops-there-was-a-reference-involved-in-your-constexpr
issue will be fixed with
C++17, but until then a macro like the STATIC_N_ITEMS
above yields portability,
e.g. to the clang and Visual C++ compilers, retaining type safety.
Related: macros do not respect scopes, so to avoid name collisions it can be a
good idea to use a name prefix, e.g. MYLIB_STATIC_N_ITEMS
.
Oh no no! That's not how you redirect. It's far more simpler:
public class ModHelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.sendRedirect("http://www.google.com");
}
}
Also, it's a bad practice to write HTML code within a servlet. You should consider putting all that markup into a JSP and invoking the JSP using:
response.sendRedirect("/path/to/mynewpage.jsp");
A good way of going about this is not to use nargin
, but to check whether the variables have been set using exist('opt', 'var')
.
Example:
function [a] = train(x, y, opt)
if (~exist('opt', 'var'))
opt = true;
end
end
See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?
Set the width of post-content and post-thumb so that you get a two-column layout.
If you are having this issue and can't find the MySQL service either, just launch "MySQL Installer" from the Start menu (or download it), then choose "Reconfigure" on MySQL Server. Follow the steps to set a root user password and then the service will be created and started automatically (and set to auto-start on boot).
I've used MPDF library. For more information view this tutorial https://arjunphp.com/generating-a-pdf-in-codeigniter-using-mpdf/
As Already mentioned we have two ways!
And it's done interactively! And take effect immediately!
CTRL + A followed by : And we type scrollback 1000000
And hit ENTER
You detach from the screen and come back! It will be always the same.
You open another new screen! And the value is reset again to default! So it's not a global setting!
Which is done by adding defscrollback 1000000
to .screenrc
(in home)
defscrollback
and not scrollback
(def stand for default)
What you need to know is if the file is not created ! You create it !
> cd ~ && vim .screenrc
And you add defscrollback 1000000
to it!
Or in one command
> echo "defscrollback 1000000" >> .screenrc
(if not created already)
When you add the default to .screenrc
! The already running screen at re-attach will not take effect! The .screenrc
run at the screen creation! And it make sense! Just as with a normal console and shell launch!
And all the new created screens will have the set value!
To check type CTRL + A followed by i
And The result will be as
Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)
Note too that when you change it interactively! The effect is immediate and take over the default value!
CTRL+ A followed by ESC (to enter the copy mode).
Then navigate with Up,Down or PgUp PgDown
And ESC again to quit that mode.
(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)
Now the buffer is bigger!
And that's sum it up for the important details!
Let me show you how to dev the tool.you can do so:
I dev a tool solve the problem.it is well design and quick more. get the code from my github.
enjoy it from here,I have deploy it on webserver.
I try the top 2 answer's suggestion.one web is can not open.one is slower than my tool.hope you will enjoy my tool.
I worked on a project that required a pdf report. After searching for online I found the PoDoFo library. Seemed very robust. I did not need all the features, so I created a wrapper to abstract away some of the complexity. Wasn't too difficult. You can find the library here:
http://podofo.sourceforge.net/
Enjoy!
The absolutely best way is neither of the 2, but the 3rd. The first parameter to encode
defaults to 'utf-8'
ever since Python 3.0. Thus the best way is
b = mystring.encode()
This will also be faster, because the default argument results not in the string "utf-8"
in the C code, but NULL
, which is much faster to check!
Here be some timings:
In [1]: %timeit -r 10 'abc'.encode('utf-8')
The slowest run took 38.07 times longer than the fastest.
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 183 ns per loop
In [2]: %timeit -r 10 'abc'.encode()
The slowest run took 27.34 times longer than the fastest.
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 137 ns per loop
Despite the warning the times were very stable after repeated runs - the deviation was just ~2 per cent.
Using encode()
without an argument is not Python 2 compatible, as in Python 2 the default character encoding is ASCII.
>>> 'äöä'.encode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Maybe your default cerficate has expired. to renew it through admin console go "Security >SSL certificate and key management > Key stores and certificates > NodeDefaultKeyStore > Personal certificates" select the "default" alias and click on "renew" after then restart WAS.
go to my start-documents-iisExpress-config and then right click on applicationhost and select open with visual studio 2013 for web you will get into applicationhost.config window in the visual studio and now in the region chsnge the physical path to the path where your project is placed
a = ('A','B','C') # see it as the string "ABC"
b = ('A','B','D')
A is converted to its corresponding ASCII ord('A') #65
same for other elements
So,
>> a>b # True
you can think of it as comparing between string (It is exactly, actually)
the same thing goes for integers too.
x = (1,2,2) # see it the string "123"
y = (1,2,3)
x > y # False
because (1 is not greater than 1, move to the next, 2 is not greater than 2, move to the next 2 is less than three -lexicographically -)
The key point is mentioned in the answer above
think of it as an element is before another alphabetically not element is greater than an element and in this case consider all the tuple elements as one string.
Would like to thank you for some excellent replies. @AR., your a star and it works perfectly. I had noticed last night that the Excel.exe
was not closing; so I did some research and found out about how to release the COM objects. Here is my final code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Excel;
namespace testExcelconsoleApp
{
class Program
{
private String fileLoc = @"C:\temp\test.xls";
static void Main(string[] args)
{
Program p = new Program();
p.createExcel();
}
private void createExcel()
{
Excel.Application excelApp = null;
Excel.Workbook workbook = null;
Excel.Sheets sheets = null;
Excel.Worksheet newSheet = null;
try
{
FileInfo file = new FileInfo(fileLoc);
if (file.Exists)
{
excelApp = new Excel.Application();
workbook = excelApp.Workbooks.Open(fileLoc, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
sheets = workbook.Sheets;
//check columns exist
foreach (Excel.Worksheet sheet in sheets)
{
Console.WriteLine(sheet.Name);
sheet.Select(Type.Missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
}
newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);
newSheet.Name = "My New Sheet";
newSheet.Cells[1, 1] = "BOO!";
workbook.Save();
workbook.Close(null, null, null);
excelApp.Quit();
}
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(newSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
newSheet = null;
sheets = null;
workbook = null;
excelApp = null;
GC.Collect();
}
}
}
}
Thank you for all your help.
I had similar issue. I updated android studio build tools and my project didn't find "android-22". I looked in android sdk manager and it was installed.
To fix this issue I uninstalled "android-22" and installed again.
The best method for setting a socket as non-blocking in C is to use ioctl. An example where an accepted socket is set to non-blocking is following:
long on = 1L;
unsigned int len;
struct sockaddr_storage remoteAddress;
len = sizeof(remoteAddress);
int socket = accept(listenSocket, (struct sockaddr *)&remoteAddress, &len)
if (ioctl(socket, (int)FIONBIO, (char *)&on))
{
printf("ioctl FIONBIO call failed\n");
}
This is basically the same answer provided by Evert, but extended to show-off
some cool options of fill_between
from matplotlib import pyplot as pl
import numpy as np
pl.clf()
pl.hold(1)
x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')
x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')
y = np.cos(x/6*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
linewidth=4, linestyle='dashdot', antialiased=True)
y = np.cos(x/6*np.pi) + np.sin(x/3*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
linewidth=0)
pl.show()
Visual Studio 2017 and newer support a new lightweight .csproj
format which has come to be known as "SDK format". One of several advantages of this format is that instead of containing a list of files and folders which are included, files are wildcard included by default. Therefore, with this new format, your files and folders - added in Explorer or on the command line - will get picked up automatically!
The SDK format .csproj
file currently works with the following project types:
Class library projects
Console apps
ASP.NET Core web apps
.NET Core projects of any type
To use the new format, create a new .NET Core or .NET Standard project. Because the templates haven't been updated for the full .NET Framework even in Visual Studio 2019, to create a .NET class library choose the .NET Standard Library template, and then edit the project file to target the framework version of your choice (the new style project format can be edited inside Visual Studio - just right click the project in the Solution Explorer and select "Edit project file"). For example:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net46</TargetFramework>
</PropertyGroup>
</Project>
Further reading:
For those not using Windows the file to change is netbeans-8.0/etc/netbeans.conf
and the line(s) to change is:
netbeans_jdkhome="/usr/lib/jvm/java-8-oracle"
commenting out the old value and inserting the new value
Suppose you have defined your route name like this:
https://localhost:3000/user/:userid
which will become:
https://localhost:3000/user/5896544
Here, if you will print: request.params
{
userId : 5896544
}
so
request.params.userId = 5896544
so request.params is an object containing properties to the named route
and request.query comes from query parameters in the URL eg:
https://localhost:3000/user?userId=5896544
request.query
{
userId: 5896544
}
so
request.query.userId = 5896544
Any element can have a class or an id.
A class is used to reference a certain type of display, for example you may have a css class for a div that represents the answer to this question. As there will be many answers, multiple divs would need the same styling and you would use a class.
An id refers to only a single element, for example the related section at the right may have styling specific to it not reused elsewhere, it would use an id.
Technically you can use classes for all of it, or split them up logically. You can not, however, reuse id's for multiple elements.
There is a small difference between both.
Second declaration assignates the reference associated to the constant SOME
to the variable str
First declaration creates a new String having for value the value of the constant SOME
and assignates its reference to the variable str
.
In the first case, a second String has been created having the same value that SOME
which implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOME
are transformed into the same instance, which uses far less memory.
As a consequence, always prefer second syntax.
To do this, I had to come up with an intermediate data structure:
class KeyDataPoint {
String key;
DateTime timestamp;
Number data;
// obvious constructor and getters
}
With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.
Then, we apply a groupingBy
operation on the string key in order to gather the data for each key together. Note that a simple groupingBy
would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy
which is a mapping
operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping
operation is simply toList
which collects the DataPoint objects of the same group into a list.
Now we have a Map<String, List<DataPoint>>
and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.
The code ends up looking like this:
Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.getData().entrySet().stream()
.map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
.collect(groupingBy(KeyDataPoint::getKey,
mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
I took some liberties with constructors and getters, but I think they should be obvious.
Add OSHI dependency via maven:
<dependency>
<groupId>com.github.dblock</groupId>
<artifactId>oshi-core</artifactId>
<version>2.2</version>
</dependency>
Get a battery capacity left in percentage:
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
for (PowerSource pSource : hal.getPowerSources()) {
System.out.println(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));
}
It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.
Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.
It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."
Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.
There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.
First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.
And other aspect is providing proper result. So you want to truncate the number or round it.
So before you start you should ask your self, am i interested on the value or not.
To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png
in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window
family such as JFrame
or JDialog
:
IconImageUtilities.setIconImage(this);
You can experiment with the native DB driver for Excel in language/platform of your choice. In Java world, you can try with http://code.google.com/p/sqlsheet/ which provides a JDBC driver for working with Excel sheets directly. Similarly, you can get drivers for the DB technology for other platforms.
However, I can guarantee that you will soon hit a wall with the number of features these wrapper libraries provide. Better way will be to use Apache HSSF/POI or similar level of library but it will need more coding effort.
add these dependecies to your .pom file:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.healthmarketscience.jackcess</groupId>
<artifactId>jackcess-encrypt</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
and add to your code to call a driver:
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://{file_location}/{accessdb_file_name.mdb};memory=false");
Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:
- React events are named using camelCase, rather than lowercase.
- With JSX you pass a function as the event handler, rather than a string.
So as mentioned in React documentation, they quite similar to normal HTML when it comes to Event Handling, but event names in React using camelcase, because they are not really HTML, they are JavaScript, also, you pass the function while we passing function call in a string format for HTML, they are different, but the concepts are pretty similar...
Look at the example below, pay attention to the way event get passed to the function:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.
iloc
works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing
df.iloc[0]
or the last five rows by doing
df.iloc[-5:]
You can also use it on the columns. This retrieves the 3rd column:
df.iloc[:, 2] # the : in the first position indicates all rows
You can combine them to get intersections of rows and columns:
df.iloc[:3, :3] # The upper-left 3 X 3 entries (assuming df has 3+ rows and columns)
On the other hand, .loc
use named indices. Let's set up a data frame with strings as row and column labels:
df = pd.DataFrame(index=['a', 'b', 'c'], columns=['time', 'date', 'name'])
Then we can get the first row by
df.loc['a'] # equivalent to df.iloc[0]
and the second two rows of the 'date'
column by
df.loc['b':, 'date'] # equivalent to df.iloc[1:, 1]
and so on. Now, it's probably worth pointing out that the default row and column indices for a DataFrame
are integers from 0 and in this case iloc
and loc
would work in the same way. This is why your three examples are equivalent. If you had a non-numeric index such as strings or datetimes, df.loc[:5]
would raise an error.
Also, you can do column retrieval just by using the data frame's __getitem__
:
df['time'] # equivalent to df.loc[:, 'time']
Now suppose you want to mix position and named indexing, that is, indexing using names on rows and positions on columns (to clarify, I mean select from our data frame, rather than creating a data frame with strings in the row index and integers in the column index). This is where .ix
comes in:
df.ix[:2, 'time'] # the first two rows of the 'time' column
I think it's also worth mentioning that you can pass boolean vectors to the loc
method as well. For example:
b = [True, False, True]
df.loc[b]
Will return the 1st and 3rd rows of df
. This is equivalent to df[b]
for selection, but it can also be used for assigning via boolean vectors:
df.loc[b, 'name'] = 'Mary', 'John'
These configurations worked in January of 2020 on my new machine build:
(1 - x64 only) Windows 10 x64, Office 365 x64, AccessDatabaseEngine_x64 2016 installed with /passive argument, VStudio build settings set to x64 explicitly, with the following connection string: Provider= Microsoft.ACE.OLEDB.16.0; Data Source=D:...\MyDatabase.accdb
(2 - x64 or x32) Windows 10 x64, Office 365 x64, AccessDatabaseEngine_x64 2016 installed with /passive argument, PLUS AccessDatabaseEngine 2010 (32bit) installed with /passive argument, VStudio build settings set to AnyCPU, with the following connection string: Provider= Microsoft.ACE.OLEDB.16.0; Data Source=D:...\MyDatabase.accdb
(3 - x32 only) Windows 10 x64, Office 365 x32, AccessDatabaseEngine 2010 (32bit) installed with /passive argument, VStudio build settings set to x86, with the following connection string: Provider= Microsoft.ACE.OLEDB.12.0; Data Source=D:...\MyDatabase.accdb
FAILURE NOTES
Using the ACE.OLEDB.12.0 x64 provider in the connection string failed with only the AccessDatabaseEngine_x64 2016 installed as above in (1).
Using AnyCPU in the visual studio build settings failed in (1). Setting x64 is required. Maybe this is because AnyCPU means that Vstudio must see an x32 ACE.OLEDB.nn.0 provider at compile time.
The ACE.OLEDB.12.0 2016 x32 /passive engine would NOT install when it saw x64 applications around. (The ACE.OLEDB.12.0 2010 x32 /passive installer worked.)
CONCLUSIONS
To use x64 build settings, you need to have the 2016 x64 database engine AND the ACE.OLEDB.16.0 connection-string provider AND explicit x64 build settings to work with Office 365 in January of 2020. Using the /passive option makes installations easy. Credit to whoever posted that tip!
To use AnyCPU, I needed to have both the ACE.OLEDB.12.0 2010 x32 engine and the ACE.OLEDB.16.0 x64 engines installed. That way Vstudio could see both x32 and x64 engines at "AnyCPU" compile time. I could change the provider connection string to ACE.OLEDB.12.0 for x32 operation or to ACE.OLEDB.16.0 for x64 operation. Both worked fine.
To use x86 build settings, you need to have the 2010 x32 database engine AND the ACE.OLEDB.12.0 connection-string provider AND explicit x86 build settings to work with Office 365 x32 in January of 2020.
I solve this issue set my settings in vscode.
Regards
I had the same problem using Spring Boot 2.0.0.M7 + Spring Security + Springfox 2.8.0. And I solved the problem using the following security configuration that allows public access to Swagger UI resources.
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
// -- Swagger UI v2
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
// -- Swagger UI v3 (OpenAPI)
"/v3/api-docs/**",
"/swagger-ui/**"
// other public endpoints of your API may be appended to this array
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
// ... here goes your custom security configuration
authorizeRequests().
antMatchers(AUTH_WHITELIST).permitAll(). // whitelist Swagger UI resources
// ... here goes your custom security configuration
antMatchers("/**").authenticated(); // require authentication for any endpoint that's not whitelisted
}
}
I made this function for my needs.
Feel free to use it. Works great on mobile devices.
function detectswipe(el,func) {
swipe_det = new Object();
swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
var min_x = 30; //min x swipe for horizontal swipe
var max_x = 30; //max x difference for vertical swipe
var min_y = 50; //min y swipe for vertical swipe
var max_y = 60; //max y difference for horizontal swipe
var direc = "";
ele = document.getElementById(el);
ele.addEventListener('touchstart',function(e){
var t = e.touches[0];
swipe_det.sX = t.screenX;
swipe_det.sY = t.screenY;
},false);
ele.addEventListener('touchmove',function(e){
e.preventDefault();
var t = e.touches[0];
swipe_det.eX = t.screenX;
swipe_det.eY = t.screenY;
},false);
ele.addEventListener('touchend',function(e){
//horizontal detection
if ((((swipe_det.eX - min_x > swipe_det.sX) || (swipe_det.eX + min_x < swipe_det.sX)) && ((swipe_det.eY < swipe_det.sY + max_y) && (swipe_det.sY > swipe_det.eY - max_y) && (swipe_det.eX > 0)))) {
if(swipe_det.eX > swipe_det.sX) direc = "r";
else direc = "l";
}
//vertical detection
else if ((((swipe_det.eY - min_y > swipe_det.sY) || (swipe_det.eY + min_y < swipe_det.sY)) && ((swipe_det.eX < swipe_det.sX + max_x) && (swipe_det.sX > swipe_det.eX - max_x) && (swipe_det.eY > 0)))) {
if(swipe_det.eY > swipe_det.sY) direc = "d";
else direc = "u";
}
if (direc != "") {
if(typeof func == 'function') func(el,direc);
}
direc = "";
swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
},false);
}
function myfunction(el,d) {
alert("you swiped on element with id '"+el+"' to "+d+" direction");
}
To use the function just use it like
detectswipe('an_element_id',myfunction);
detectswipe('an_other_element_id',my_other_function);
If a swipe is detected the function "myfunction" is called with parameter element-id and "l,r,u,d" (left,right,up,down).
Example: http://jsfiddle.net/rvuayqeo/1/
I (UlysseBN) made a new version of this script based on this one which use more modern JavaScript, it looks like it behaves better on some cases. If you think it should rather be an edit of this answer let me know, if you are the original author and you end up editing, I'll delete my answer.
Based on the error you showed ('footballforum' is missing required Java project: 'ApiDemos'), I would check your build path. Right-click the footballforum project and choose Build Path > Configure Build Path. Make sure ApiDemos is on the projects tab of the build path options.
You can use http://adodson.com/hello.js/ which has
git config [--global] user.name "Full Name"
git config [--global] user.email "[email protected]"
Per repo basis you could also edit .git/config
manually instead.
When performing step 2 if you see credential.helper=manager
you need to open the credential manager of your computer (Win or Mac) and update the credentials there
Some other options if you do not want your own "Utils"-class:
Use Apache commons lang (ArrayUtils):
@Test
public void arrayCommonLang(){
char[] test = {'h', 'e', 'l', 'l', 'o'};
Assert.assertTrue(ArrayUtils.contains(test, 'o'));
Assert.assertFalse(ArrayUtils.contains(test, 'p'));
}
Or use the builtin Arrays:
@Test
public void arrayTest(){
char[] test = {'h', 'e', 'l', 'l', 'o'};
Assert.assertTrue(Arrays.binarySearch(test, 'o') >= 0);
Assert.assertTrue(Arrays.binarySearch(test, 'p') < 0);
}
Or use the Chars class from Google Guava:
@Test
public void testGuava(){
char[] test = {'h', 'e', 'l', 'l', 'o'};
Assert.assertTrue(Chars.contains(test, 'o'));
Assert.assertFalse(Chars.contains(test, 'p'));
}
Slightly off-topic, the Chars class allows to find a subarray in an array.
You are most likely looking for the IIS_IUSRS account.
OpenOffice templates + OOo command line interface.
There are tools and libraries available to ease each of those steps.
May be that helps.
The gorand package has a UUID method that returns a Version 4 (randomly generated) UUID in its canonical string representation ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") and it's RFC 4122 compliant.
It also uses the crypto/rand package to ensure the most cryptographically secure generation of UUIDs across all platforms supported by Go.
import "github.com/leonelquinteros/gorand"
func main() {
uuid, err := gorand.UUID()
if err != nil {
panic(err.Error())
}
println(uuid)
}
In the endpoint tag you need to include the property address=""
<endpoint address="" binding="webHttpBinding" bindingConfiguration="SecureBasicRest" behaviorConfiguration="svcEndpoint" name="webHttp" contract="SvcContract.Authenticate" />
Query all users and filter by the list from your text file:
$Users = Get-Content 'C:\scripts\Users.txt'
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users -contains $_.SamAccountName } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
Get-ADUser -Filter '*'
returns all AD user accounts. This stream of user objects is then piped into a Where-Object
filter, which checks for each object if its SamAccountName
property is contained in the user list from your input file ($Users
). Only objects with a matching account name are passed forward to the next step of the pipeline. The output can be limited by selecting the relevant properties before exporting the data.
You can further optimize the code by replacing the -contains
operator with hashtable lookups:
$Users = @{}
Get-Content 'C:\scripts\Users.txt' | ForEach-Object { $Users[$_] = $true }
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users.ContainsKey($_.SamAccountName) } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
This one is for using HTTPClient class
request.headers.add("body", json.encode(map));
I attached the encoded json body data to the header and added to it. It works for me.
You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.
dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);
Check this
EDIT
As per the comment posted by Frank and Mat, you can also enable it with Null
exec dbms_output.enable(NULL);
buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).
I managed to find a solution using css/jQuery that I'm comfortable with. The original issue: I had to force the visibility to be shown while animating as I have elements hanging outside the area. Doing so, made large blocks of text now hang outside the content area during animation as well.
The solution was to start the main text elements with an opacity of 0 and use addClass
to inject and transition to an opacity of 1. Then removeClass
when clicked on again.
I'm sure there's an all jQquery way to do this. I'm just not the guy to do it. :)
So in it's most basic form...
.slideDown().addClass("load");
.slideUp().removeClass("load");
Thanks for the help everyone.
Use json_encode() if possible (PHP 5.2+).
See this one (maybe duplicate?): Pass a PHP string to a JavaScript variable (and escape newlines)
Try this:
Import RouterModule
into your app.module.ts
import { RouterModule } from '@angular/router';
Add RouterModule
into your imports []
like this:
imports: [ RouterModule, ]
I needed to do replicate these heights properly in a pre-ICS compatibility app and dug into the framework core source. Both answers above are sort of correct.
It basically boils down to using qualifiers. The height is defined by the dimension "action_bar_default_height"
It is defined to 48dip for default. But for -land it is 40dip and for sw600dp it is 56dip.
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
i dont know whether it is relevant to your issue, i got similar issue which i got solved by
1) In eclipse right click server and clean
if it still didnt work
2) export the project and delete the project create the project with same name and import the project and add the project to server and run.
If you have an SMTP service running, you can outfile to the drop directory. If you have high volume, you may result with duplicate file names, but there are ways to avoid that.
Otherwise, you will need to create a UDF.
Here's a sample trigger solution:
CREATE TRIGGER test.autosendfromdrop BEFORE INSERT ON test.emaildrop
FOR EACH ROW BEGIN
/* START THE WRITING OF THE EMAIL FILE HERE*/
SELECT concat("To: ",NEW.To),
concat("From: ",NEW.From),
concat("Subject: ",NEW.Subject),
NEW.Body
INTO OUTFILE
"C:\\inetpub\\mailroot\\pickup\\mail.txt"
FIELDS TERMINATED by '\r\n' ESCAPED BY '';
END;
To markup the message body you will need something like this...
CREATE FUNCTION `HTMLBody`(Msg varchar(8192))
RETURNS varchar(17408) CHARSET latin1 DETERMINISTIC
BEGIN
declare tmpMsg varchar(17408);
set tmpMsg = cast(concat(
'Date: ',date_format(NOW(),'%e %b %Y %H:%i:%S -0600'),'\r\n',
'MIME-Version: 1.0','\r\n',
'Content-Type: multipart/alternative;','\r\n',
' boundary=\"----=_NextPart_000_0000_01CA4B3F.8C263EE0\"','\r\n',
'Content-Class: urn:content-classes:message','\r\n',
'Importance: normal','\r\n',
'Priority: normal','\r\n','','\r\n','','\r\n',
'This is a multi-part message in MIME format.','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/plain;','\r\n',
' charset=\"iso-8859-1\"','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n','','\r\n',
Msg,
'\r\n','','\r\n','','\r\n',
'------=_NextPart_000_0000_01CA4B3F.8C263EE0','\r\n',
'Content-Type: text/html','\r\n',
'Content-Transfer-Encoding: 7bit','\r\n','','\r\n',
Msg,
'\r\n','------=_NextPart_000_0000_01CA4B3F.8C263EE0--'
) as char);
RETURN tmpMsg;
END ;
var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
alert ("Error!");
}
try out like this
body {
background: #fff url("!--MIZO-PRO--!") no-repeat center 15px top 15px/100px;
}
/* 100px is the background size */
From oracle documentation link
Making methods synchronized has two effects:
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads
Have a look at this documentation page to understand intrinsic locks and lock behavior.
This will answer your question: On same object x , you can't call x.addA() and x.addB() at same time when one of the synchronized methods execution is in progress.
Sending a docker image to a remote server can be done in 3 simple steps:
docker save -o <path for created tar file> <image name>
Locally, use scp to transfer .tar to remote
On remote server, load image into docker:
docker load -i <path to docker image tar file>
I was able to change the button's text like this:
import android.widget.RemoteViews;
//grab the layout, then set the text of the Button called R.id.Counter:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");
In my case, nginx was not able to open the log file which is located here /var/log/nginx/error.log
This was because I had deleted the log directory to free up space in root (which turned out to be stupid)
I then created a log folder in var and an nginx folder in log.
Then simply run sudo service nginx start
simple and best way to use date function
example
SELECT * FROM
data
WHERE date(datetime) = '2009-10-20'
OR
SELECT * FROM
data
WHERE date(datetime ) >= '2009-10-20' && date(datetime ) <= '2009-10-20'
Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.
void foo(int a)
void foo(int a, float b)
Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override
annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.
class Parent {
void foo(double d) {
// do something
}
}
class Child extends Parent {
@Override
void foo(double d){
// this method is overridden.
}
}
Usage:
CountDownTimer timer = new CountDownTimer();
//set to 30 mins
timer.SetTime(30,0);
timer.Start();
//update label text
timer.TimeChanged += () => Label1.Text = timer.TimeLeftMsStr;
// show messageBox on timer = 00:00.000
timer.CountDownFinished += () => MessageBox.Show("Timer finished the work!");
//timer step. By default is 1 second
timer.StepMs = 77; // for nice milliseconds time switch
and don't forget to Dispose();
when timer is useless for you;
Source code:
using System;
using System.Diagnostics;
using System.Windows.Forms;
public class CountDownTimer : IDisposable
{
public Stopwatch _stpWatch = new Stopwatch();
public Action TimeChanged;
public Action CountDownFinished;
public bool IsRunnign => timer.Enabled;
public int StepMs
{
get => timer.Interval;
set => timer.Interval = value;
}
private Timer timer = new Timer();
private TimeSpan _max = TimeSpan.FromMilliseconds(30000);
public TimeSpan TimeLeft => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) > 0 ? TimeSpan.FromMilliseconds(_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) : TimeSpan.FromMilliseconds(0);
private bool _mustStop => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) < 0;
public string TimeLeftStr => TimeLeft.ToString(@"\mm\:ss");
public string TimeLeftMsStr => TimeLeft.ToString(@"mm\:ss\.fff");
private void TimerTick(object sender, EventArgs e)
{
TimeChanged?.Invoke();
if (_mustStop)
{
CountDownFinished?.Invoke();
_stpWatch.Stop();
timer.Enabled = false;
}
}
public CountDownTimer(int min, int sec)
{
SetTime(min, sec);
Init();
}
public CountDownTimer(TimeSpan ts)
{
SetTime(ts);
Init();
}
public CountDownTimer()
{
Init();
}
private void Init()
{
StepMs = 1000;
timer.Tick += new EventHandler(TimerTick);
}
public void SetTime(TimeSpan ts)
{
_max = ts;
TimeChanged?.Invoke();
}
public void SetTime(int min, int sec = 0) => SetTime(TimeSpan.FromSeconds(min * 60 + sec));
public void Start() {
timer.Start();
_stpWatch.Start();
}
public void Pause()
{
timer.Stop();
_stpWatch.Stop();
}
public void Stop()
{
Reset();
Pause();
}
public void Reset()
{
_stpWatch.Reset();
}
public void Restart()
{
_stpWatch.Reset();
timer.Start();
}
public void Dispose() => timer.Dispose();
}
(updated 6.6.2020, because of problems with time calculation)
No, you need to wrap your TextBlock in a Border. Example:
<Border BorderThickness="1" BorderBrush="Black">
<TextBlock ... />
</Border>
Of course, you can set these properties (BorderThickness
, BorderBrush
) through styles as well:
<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Black" />
</Style>
<Border Style="{StaticResource notCalledBorder}">
<TextBlock ... />
</Border>
Alternate solution to doing shallow clone (git clone --depth=1 <URL>
) would be, if remote side supports it, to use --remote
option of git archive:
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -
Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.
define() is part of the AMD spec of js
See:
Edit: Also see Claudio's answer below. Likely the more relevant explanation.
Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:
ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);
int arr[10] = {0, 5, 3, 64};
arr[4] = 5;
EDIT: So I was asked to explain what's happening when you do:
int arr[10] = {0, 5, 3, 64};
you create an array with 10 elements and you allocate values for the first 4 elements of the array.
Also keep in mind that arr
starts at index arr[0]
and ends at index arr[9]
- 10 elements
arr[0] has value 0;
arr[1] has value 5;
arr[2] has value 3;
arr[3] has value 64;
after that the array contains garbage values / zeroes because you didn't allocated any other values
But you could still allocate 6 more values so when you do
arr[4] = 5;
you allocate the value 5 to the fifth element of the array.
You could do this until you allocate values for the last index of the arr
that is arr[9]
;
Sorry if my explanation is choppy, but I have never been good at explaining things.
npm test <filepath>
eg :
npm test test/api/controllers/test.js
here 'test/api/controllers/test.js' is filepath.
The easiest way to do this is just to add zero to your result.
i.e.
$A=($row['SUM'Price']+0);
echo $A;
hope this helps!!
I set .navbar-brand { min-height: inherit }
which solved the issue for me (thanks @creimers for inspiration).
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
The suggestions don't work because they are for the standard MySQL driver, not for mysqli:
$this->db_link->error
contains the error if one did occur
Or
mysqli_error($this->db_link)
will work.
hi if are you new in android use this way Apply your view to make it gone GONE is one way, else, get hold of the parent view, and remove the child from there..... else get the parent layout and use this method an remove all child parentView.remove(child)
I would suggest using the GONE approach...
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
I faced the same issue. Setting relative path of the parent in module projects solved the issue.
Use <relativePath>../Parent Project Name/pom.xml</relativePath>
Just simple modification of @silgon answer:
while true; do
inotifywait -r -e modify,create,delete /directory
rsync -avz /directory /target
done
(@silgon version sometimes crashes on Ubuntu 16 if you run it in cron)
In the source header you can declare:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
....
It is described in the PEP 0263:
Then you can use UTF-8 in strings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)
This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).
In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.
You can get the width and height of PDF document like below,
var doc = new jsPDF("p", "mm", "a4");
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
Then you can use this width and height for your image to fit the entire PDF document.
var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJ......';
doc.addImage(imgData, 'JPEG', 0, 0, width, height);
Make sure that your image has the same size (resolution) of the PDF document. Otherwise it will look distorted (stretched).
If you want convert px
to mm
use this link http://www.endmemo.com/sconvert/millimeterpixel.php
May this help to someone if they have the same requirement.
This will read a file that contains the Jenkins Job name and run them iteratively from one single job.
Please change below code accordingly in your Jenkins.
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
git branch: 'Your Branch name', credentialsId: 'Your crendiatails', url: ' Your BitBucket Repo URL '
##To read file from workspace which will contain the Jenkins Job Name ###
def filePath = readFile "${WORKSPACE}/ Your File Location"
##To read file line by line ###
def lines = filePath.readLines()
##To iterate and run Jenkins Jobs one by one ####
for (line in lines) {
build(job: "$line/branchName",
parameters:
[string(name: 'vertical', value: "${params.vert}"),
string(name: 'environment', value: "${params.env}"),
string(name: 'branch', value: "${params.branch}"),
string(name: 'project', value: "${params.project}")
]
)
}
}
}
}
}
}
_x000D_
If you understand how factors are stored, you can avoid using apply-based functions to accomplish this. Which isn't at all to imply that the apply solutions don't work well.
Factors are structured as numeric indices tied to a list of 'levels'. This can be seen if you convert a factor to numeric. So:
> fact <- as.factor(c("a","b","a","d")
> fact
[1] a b a d
Levels: a b d
> as.numeric(fact)
[1] 1 2 1 3
The numbers returned in the last line correspond to the levels of the factor.
> levels(fact)
[1] "a" "b" "d"
Notice that levels()
returns an array of characters. You can use this fact to easily and compactly convert factors to strings or numerics like this:
> fact_character <- levels(fact)[as.numeric(fact)]
> fact_character
[1] "a" "b" "a" "d"
This also works for numeric values, provided you wrap your expression in as.numeric()
.
> num_fact <- factor(c(1,2,3,6,5,4))
> num_fact
[1] 1 2 3 6 5 4
Levels: 1 2 3 4 5 6
> num_num <- as.numeric(levels(num_fact)[as.numeric(num_fact)])
> num_num
[1] 1 2 3 6 5 4
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
You can use awk. Set the record separator (RS
) to a regexp that matches all possible newline character, or characters. And set the output record separator (ORS
) to the unix-style newline character.
awk 'BEGIN{RS="\r|\n|\r\n|\n\r";ORS="\n"}{print}' windows_or_macos.txt > unix.txt
Dangling Pointer
If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.
#include<stdio.h>
int *call();
void main(){
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
}
int * call(){
int x=25;
++x;
return &x;
}
Output: Garbage value
Note: In some compiler you may get warning message returning address of local variable or temporary
Explanation: variable x is local variable. Its scope and lifetime is within the function call hence after returning address of x variable x became dead and pointer is still pointing ptr is still pointing to that location.
Solution of this problem: Make the variable x is as static variable. In other word we can say a pointer whose pointing object has been deleted is called dangling pointer.
Memory Leak
In computer science, a memory leak occurs when a computer program incorrectly manages memory allocations. As per simple we have allocated the memory and not Free other language term say not release it call memory leak it is fatal to application and unexpected crash.
If I properly understood your question, supposing your running script is
/relative/path/to/script/index.php
This would give you the parent directory of your running script relative to the document www:
$parent_dir = dirname(dirname($_SERVER['SCRIPT_NAME'])) . '/';
//$parent_dir will be '/relative/path/to/'
If you want the parent directory of your running script relative to server root:
$parent_dir = dirname(dirname($_SERVER['SCRIPT_FILENAME'])) . '/';
//$parent_dir will be '/root/some/path/relative/path/to/'
"bindEmail" it will check email is available or not. if email is exist than Logout will show otherwise Login will show
<li *ngIf="bindEmail;then logout else login"></li>
<ng-template #logout><li><a routerLink="/logout">Logout</a></li></ng-template>
<ng-template #login><li><a routerLink="/login">Login</a></li></ng-template>
You need to use delimiters with regexes in PHP. You can use the often used /
, but PHP lets you use any matching characters, so @
and #
are popular.
If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote()
.
Any user with a valid shell in /etc/passwd
can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys
file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.
To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.
We were suffering a similar problem and noticed that Bootstrap 3 doesn't have the problem on their tabs (in Chrome). It looks like they're using outline-style which allows the browser to decide what best to do and Chrome seems to do what you want: show the outline when focused unless you just clicked the element.
Support for outline-style
is hard to pin down since the browser gets to decide what that means. Best to check in a few browsers and have a fall-back rule.
@Query("SELECT rd FROM ReleaseDateType rd, CacheMedia cm WHERE ...")
You can use Perl::Tidy for Perl.
A gem like https://rubygems.org/gems/to_bool can be used, but it can easily be written in one line using a regex or ternary.
regex example:
boolean = (var.to_s =~ /^true$/i) == 0
ternary example:
boolean = var.to_s.eql?('true') ? true : false
The advantage to the regex method is that regular expressions are flexible and can match a wide variety of patterns. For example, if you suspect that var could be any of "True", "False", 'T', 'F', 't', or 'f', then you can modify the regex:
boolean = (var.to_s =~ /^[Tt].*$/i) == 0
If you are ok to do transformation, you may try this.
DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
I have one more solution, I think. I recently had changed my computer name so, after I couldn't connect still after trying all above methods. I changed the Server name.. Server name => (browse for more) => under database engine, a new server was found same as computers new name. This worked, and life is good again.
Try this :
html_source_code = requests.get("http://www.example.com/",
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36',
'Upgrade-Insecure-Requests': '1',
'x-runtime': '148ms'},
allow_redirects=True).content
The new line character is \n
, like so:
echo __("Thanks for your email.\n<br />\n<br />Your order's details are below:", 'jigoshop');
manglesky's solution is great, but not obfuscated enough. :-) So:
#include <stdio.h>
#define TEN(S) S S S S S S S S S S
int main() { int i = 1; TEN(TEN(TEN(printf("%d\n", i++);))) return 0; }
I would like to answer this question from a coding-politics perspective, which may or may not be helpful to anyone. But particularly when you're dealing with tools that are intended for 9-5 corporate programmers, people who write documentation tend to use words like "should not" and "never" to mean "don't do this unless you really know what you're doing and why".
A couple of my other favorites in the C# world are that they tell you to "never call lock(this)" or "never call GC.Collect()". These two are forcefully declared in many blogs and official documentation, and IMO are complete misinformation. On some level this misinformation serves its purpose, in that it keeps the beginners away from doing things they don't understand before fully researching the alternatives, but at the same time, it makes it difficult to find REAL information via search-engines that all seem to point to articles telling you not to do something while offering no answer to the question "why not?"
Politically, it boils down to what people consider "good design" or "bad design". Official documentation should not be dictating the design of my application. If there's truly a technical reason that you shouldn't call sleep(), then IMO the documentation should state that it is totally okay to call it under specific scenarios, but maybe offer some alternative solutions that are scenario independent or more appropriate for the other scenarios.
Clearly calling "sleep()" is useful in many situations when deadlines are clearly defined in real-world-time terms, however, there are more sophisticated systems for waiting on and signalling threads that should be considered and understood before you start throwing sleep() into your code, and throwing unnecessary sleep() statements in your code is generally considered a beginners' tactic.
In my experience it may be the result of auto-generation by a string-based tools, where the author did not understand the rules of HTML.
When some developers generate HTML without the use of special XML-oriented tools, they may try to be sure the resulting HTML is valid by taking the approach that everything must be escaped.
Referring to your example, the reason why every occurrence of "
is represented by "
could be because using that approach, you can safely use such "special" characters in both attributes and values.
Another motivation I've seen is where people believe, "We must explicitly show that our symbols are not part of the syntax." Whereas, valid HTML can be created by using the proper string-manipulation tools, see the previous paragraph again.
Here is some pseudo-code loosely based on C#, although it is preferred to use valid methods and tools:
public class HtmlAndXmlWriter
{
private string Escape(string badString)
{
return badString.Replace("&", "&").Replace("\"", """).Replace("'", "'").Replace(">", ">").Replace("<", "<");
}
public string GetHtmlFromOutObject(Object obj)
{
return "<div class='type_" + Escape(obj.Type) + "'>" + Escape(obj.Value) + "</div>";
}
}
It's really very common to see such approaches taken to generate HTML.
Take below reference to convert a JSON into POJO and vice-versa
Let's suppose your JSON schema looks like:
{
"type":"object",
"properties": {
"dataOne": {
"type": "string"
},
"dataTwo": {
"type": "integer"
},
"dataThree": {
"type": "boolean"
}
}
}
Then to covert into POJO, your need to decleare some classes as explained in below style:
==================================
package ;
public class DataOne
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataTwo
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataThree
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class Properties
{
private DataOne dataOne;
private DataTwo dataTwo;
private DataThree dataThree;
public void setDataOne(DataOne dataOne){
this.dataOne = dataOne;
}
public DataOne getDataOne(){
return this.dataOne;
}
public void setDataTwo(DataTwo dataTwo){
this.dataTwo = dataTwo;
}
public DataTwo getDataTwo(){
return this.dataTwo;
}
public void setDataThree(DataThree dataThree){
this.dataThree = dataThree;
}
public DataThree getDataThree(){
return this.dataThree;
}
}
==================================
package ;
public class Root
{
private String type;
private Properties properties;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
public void setProperties(Properties properties){
this.properties = properties;
}
public Properties getProperties(){
return this.properties;
}
}
For shallow copying you could use Object.assign which is a ES6 feature
let x = { name: 'Marek', age: 20 };
let y = Object.assign({}, x);
x === y; //false
DO NOT use it for deep cloning
The issue I had was also with serialization. The cause was some of my DTO/business classes and properties were renamed or deleted without updating the service reference. I'm surprised I didn't get a contract filter mismatch error
instead. But updating the service ref fixed the error for me (same error as OP).
Maybe you coul'd use UTF8 bold chars.
For examples: https://yaytext.com/bold-italic/
It works on Chromium 80.0, I don't know on other browsers...
If you reconfigure IIS7 to use your new location, then there's no problem. Just test that the new location is working, before deleting the old location.
Change IIS7 Inetpub path
- Open %windir%\system32\inetsrv\config\applicationhost.config and search for
%SystemDrive%\inetpub\wwwroot
- Change the path.
You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.
If you don't use the onLocationChanged it always will be the old location.
Here is the Swift-4.2 code for automatic fix your image orientation Returns UIImage
func AutofixImageOrientation(_ image: UIImage)->UIImage {
UIGraphicsBeginImageContext(image.size)
image.draw(at: .zero)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? image
}
Kotlin has a built-in function for this, removeSuffix
(Documentation)
var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"
If the suffix does not exist in the string, it just returns the original
var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"
You can also check out removePrefix
and removeSurrounding
which are similar
I know some trick works in Chrome:
When dropping files into drop zone you get a dataTransfer.files
object, that is a FileList
type of object, that contains all the files you dragged. Meanwhile, <input type="file" />
element has the property files
, that is the same FileList
type object.
So, you can simply assign the dataTransfer.files
object to the input.files
property.
Use the variations of d
like dd
to cut.
To write a range of lines to another file you can use:
:<n>,<m> w filename
Where <n>
and <m>
are numbers (or symbols) that designate a range of lines.
For using the desktop clipboard, take a look at the +g
commands.
My case, the server was encrypting with padding disabled. But the client was trying to decrypt with the padding enabled.
While using EVP_CIPHER*, by default the padding is enabled. To disable explicitly we need to do
EVP_CIPHER_CTX_set_padding(context, 0);
So non matching padding options can be one reason.
Datalist includes autocomplete and suggestions natively, it can also allow a user to enter a value that is not defined in the suggestions.
Select only gives you pre-defined options the user has to select from