This works well for specific articles where the text is all wrapped in <p>
tags. Since the web is an ugly place, it's not always the case.
Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span>
or a <div>
, or an <li>
).
To find all text nodes in the DOM, you can use soup.find_all(text=True)
.
This is going to return some undesired text, like the contents of <script>
and <style>
tags. You'll need to filter out the text contents of elements you don't want.
blacklist = [
'style',
'script',
# other elements,
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]
If you are working with a known set of tags, you can tag the opposite approach:
whitelist = [
'p'
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]
sudo du -x -h / | sort -h | tail -40
/tmp
or /home/user_name/.cache
folder if these are taking up a lot of memory. You can do this by running sudo rm -R /path/to/folder
Step 2 outlines fairly common folders to delete from (/tmp
and /home/user_name/.cache
). If you get back other results when running the first command showing you have lots of memory being used elsewhere, I advise being a bit more cautious when deleting from those locations.
In Simpler words, Pig is a high-level platform for creating MapReduce programs used with Hadoop, using pig scripts we will process the large amount of data into desired format.
Once the processed data obtained, this processed data is kept in HDFS for later processing to obtain the desired results.
On top of the stored processed data we will apply HIVE SQL commands to get the desired results, internally this hive sql commands runs MAP Reduce programs.
Also take a look at ILSpy by SharpDevelop. It's in early stages of development and they just made a release on the 24th of February. That in itself works pretty good for me. From their website:
ILSpy is the open-source .NET assembly browser and decompiler.
Development started after Red Gate announced that the free version of .NET Reflector would cease to exist by end of February 2011.
Update: JetBrains has released dotPeek, its free .NET decompiler.
Update 2: Telerik also has a free decompiler: JustDecompile.
i solved with a max-width
in my main css-file.
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
max-width: 280px;
}
It's a simple solution with little "code"
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
From the documentation:
It is necessary to keep in mind that the browsers do not know how to correctly show this error.
I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.
Without dragging ostream into it:
constexpr char const* to_c_str(bool b) {
return
std::array<char const*, 2>{"false", "true "}[b]
;
};
Dollar sign is used in ecmascript 2015-2016 as 'template literals'. Example:
var a = 5;
var b = 10;
console.log(`Sum is equal: ${a + b}`); // 'Sum is equlat: 15'
Here working example: https://es6console.com/j3lg8xeo/ Notice this sign " ` ",its not normal quotes.
U can also meet $ while working with library jQuery.
$ sign in Regular Expressions means end of line.
It separates Model and View controlled by a Controller, As far as Model is concerned, Your Models has to follow OO architecture, future enhancements and other maintenance of the code base should be very easy and the code base should be reusable.
Same model can have any no.of views e.g) same info can be shown in as different graphical views. Same view can have different no.of models e.g) different detailed can be shown as a single graph say as a bar graph. This is what is re-usability of both View and Model.
Enhancements in views and other support of new technologies for building the view can be implemented easily.
Guy who is working on view dose not need to know about the underlying Model code base and its architecture, vise versa for the model.
I'd use RestSharp - https://github.com/restsharp/RestSharp
Create class to deserialize to:
public class MyObject {
public string Id { get; set; }
public string Text { get; set; }
...
}
And the code to get that object:
RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");
// The above code will make a request URL of
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need
var response = client.Execute<MyObject>(request);
MyObject obj = response.Data;
Check out http://restsharp.org/ to get started.
(Update) V5.1 & Hooks (Requires React >= 16.8)
You can use useHistory
, useLocation
and useRouteMatch
in your component to get match
, history
and location
.
const Child = () => {
const location = useLocation();
const history = useHistory();
const match = useRouteMatch("write-the-url-you-want-to-match-here");
return (
<div>{location.pathname}</div>
)
}
export default Child
(Update) V4 & V5
You can use withRouter
HOC in order to inject match
, history
and location
in your component props.
class Child extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
(Update) V3
You can use withRouter
HOC in order to inject router
, params
, location
, routes
in your component props.
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
Original answer
If you don't want to use the props, you can use the context as described in React Router documentation
First, you have to set up your childContextTypes
and getChildContext
class App extends React.Component{
getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
Then, you will be able to access to the location object in your child components using the context like this
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}
If you get that error message (Peer authentication failed for user (PG::Error)
) when running unit tests, make sure the test database exists.
Since bootstrap 4 use div class="form-row" in combination with div class="form-group col-X". X is the width you need. You will get nice inline columns. See fiddle.
<form class="form-horizontal" name="FORMNAME" method="post" action="ACTION" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-sm-2" for="naam">Naam: *</label>
<div class="col-sm-10">
<input type="text" require class="form-control" id="naam" name="Naam" placeholder="Uw naam" value="{--NAAM--}" >
<div id="naamx" class="form-error form-hidden">Wat is uw naam?</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-5">
<label class="control-label col-sm-4" for="telefoon">Telefoon: *</label>
<div class="col-sm-12">
<input type="tel" require class="form-control" id="telefoon" name="Telefoon" placeholder="Telefoon nummer" value="{--TELEFOON--}" >
<div id="telefoonx" class="form-error form-hidden">Wat is uw telefoonnummer?</div>
</div>
</div>
<div class="form-group col-5">
<label class="control-label col-sm-4" for="email">E-mail: </label>
<div class="col-sm-12">
<input type="email" require class="form-control" id="email" name="E-mail" placeholder="E-mail adres" value="{--E-MAIL--}" >
<div id="emailx" class="form-error form-hidden">Wat is uw e-mail adres?</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="titel">Titel: *</label>
<div class="col-sm-10">
<input type="text" require class="form-control" id="titel" name="Titel" placeholder="Titel van uw vraag of aanbod" value="{--TITEL--}" >
<div id="titelx" class="form-error form-hidden">Wat is de titel van uw vraag of aanbod?</div>
</div>
</div>
<from>
ES6 array destructuring is used to swap two variables. See example
var [x,y]=[1,2];
[x,y]=[y,x];
Easier way possible with :
x === 1
and y === 2
;
But after destructuring, x
is y
, i.e. 2
, and y
is x
, i.e. 1
.
Everything in Java is passed by value .
In the case of the array the reference is copied into a new reference, but remember that everything in Java is passed by value .
Take a look at this interesting article for further information ...
If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:
$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");
Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.
AJAX requests are no different from GET and POST requests initiated through a <form>
element. Which means you can use $_GET and $_POST to retrieve the data.
When you're making an AJAX request (jQuery example):
// JavaScript file
elements = [1, 2, 9, 15].join(',')
$.post('/test.php', {elements: elements})
It's (almost) equivalent to posting this form:
<form action="/test.php" method="post">
<input type="text" name="elements" value="1,2,9,15">
</form>
In both cases, on the server side you can read the data from the $_POST variable:
// test.php file
$elements = $_POST['elements'];
$elements = explode(',', $elements);
For the sake of simplicity I'm joining the elements with comma here. JSON serialization is a more universal solution, though.
The main reason why the error has been generated is because there is already an existing value of 1
for the column ID
in which you define it as PRIMARY KEY
(values are unique) in the table you are inserting.
Why not set the column ID
as AUTO_INCREMENT
?
CREATE TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`viale` VARCHAR(45) NULL ,
.....
and when you are inserting record, you can now skip the column ID
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`viale`, `num_civico`, ...)
VALUES ('Viale Cogel ', '120', ...)
Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null
is supplied for a parameter value.
For example:
public void myMethod(int par1, String optionalPar2) {
String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
.trim()
.toUpperCase(getDefaultLocale());
}
In the above example, passing null
as the String
parameter value gets you a default string value instead of a NullPointerException
. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
Moreover, this pattern enables you to make the String
parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:
public void myMethod(int par1) {
return myMethod(par1, null);
}
As per the documentation, most browsers will display the <ul>
, <ol>
and <li>
elements with the following default values:
Default CSS settings for UL or OL tag:
ul, ol {
display: block;
list-style: disc outside none;
margin: 1em 0;
padding: 0 0 0 40px;
}
ol {
list-style-type: decimal;
}
Default CSS settings for LI tag:
li {
display: list-item;
}
Style nested list items as well:
ul ul, ol ul {
list-style-type: circle;
margin-left: 15px;
}
ol ol, ul ol {
list-style-type: lower-latin;
margin-left: 15px;
}
Note: The result will be perfect if we use the above styles with a class. Also see different List-Item markers.
I have found solution at https://www.youtube.com/watch?v=dm4z9l26O0I
You would need to use Tools > Script Editor. Create .gs and .html files there. See example at http://goo.gl/LxGXfU (link can be also found under Youtube video). Just copy
Once you have .gs and .html files in place save them and reload your spreadsheet. You will see "Custom menu" as the last item of your top menu. Select cell you would like to manage and click on this menu item.
During the first time it will ask you to authorize application - go ahead and do this.
Note (1): make sure that your cell has "Data validation" defined before you click on "Custom menu".
Note (2): it appeared that solution works with "List from a range" criteria for Data validation (it does not work with "List of items")
One way you could do it in SQL Server would be to return the table content as XML (for XML raw), convert the result to a string and then replace the tags with ", ".
If you like fun, then you can just go to the listing page of you branches (for example merged) and just run in the javascript console:
document.querySelectorAll('tr td div a:first-child').forEach(function(item) { fetch('https://bitbucket.org/snippets/new?owner=<yourprofilenick>', {'credentials': 'same-origin'}).then((response) => {return response.text()}).then(function(string) { return /'csrfmiddlewaretoken' value='(.*)'/g.exec(string)[1] }).then(function(csrf) { if (!~item.innerText.indexOf('/')) return;
fetch(`https://bitbucket.org/!api/2.0/repositories/<your_organization_path>/refs/branches/${item.innerText}`, {headers: {"x-csrftoken": csrf}, credentials: "same-origin", method: 'DELETE'}).then(() => console.log(`${item.innerText} DELETED!`)) }) })
<yourprofilenick>
with your BitBucket nick<your_organization_path>
with your organization pathFirst we need a page with with a CSRF token in the page source, so I choose:
https://bitbucket.org/snippets/new?owner=<yourprofilenick>
Then for each branch (in a branch listing) it gets CSRF token and deletes that branch.
Remeber to prevent sensitive branches before deleting in repo settings.
It WON'T delete the main branch.
You have to be logged in.
It deletes only branches visible on that page (so to delete the rest of branches you have to go to the next page).
You don't need 2 style attributes - just use one:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
style="height:100px;width:100px;" alt="25"/>
Consider, however, using a CSS class instead:
CSS:
.100pxSquare
{
width: 100px;
height: 100px;
}
HTML:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
class="100pxSquare" alt="25"/>
In Kotlin will be :
activity?.applicationContext?.let {
it//<- you context
}
Here the Implementation of Paul Burkes answer:
public class ShadowImageView extends ImageView {
public ShadowImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ShadowImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ShadowImageView(Context context) {
super(context);
}
private Paint createShadow() {
Paint mShadow = new Paint();
float radius = 10.0f;
float xOffset = 0.0f;
float yOffset = 2.0f;
// color=black
int color = 0xFF000000;
mShadow.setShadowLayer(radius, xOffset, yOffset, color);
return mShadow;
}
@Override
protected void onDraw(Canvas canvas) {
Paint mShadow = createShadow();
Drawable d = getDrawable();
if (d != null){
setLayerType(LAYER_TYPE_SOFTWARE, mShadow);
Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
} else {
super.onDraw(canvas);
}
};
}
TODO:
execute setLayerType(LAYER_TYPE_SOFTWARE, mShadow);
only if API Level is > 10
If you have a text box to type the file path, just use sendkeys to input the file path and click on submit button. If there is no text box to type the file path and only able to click on browse button and to select the file from windows popup, you can use AutoIt tool, see the step below to use AutoIt for the same,
Download and Install Autoit tool from http://www.autoitscript.com/site/autoit/
Open Programs -> Autoit tool -> SciTE Script Editor.
Paste the following code in Autoit editor and save it as “filename.exe “(eg: new.exe)
Then compile and build the file to make it exe. (Tools ? Compile)
Autoit Code:
WinWaitActive("File Upload"); Name of the file upload window (Windows Popup Name: File Upload)
Send("logo.jpg"); File name
Send("{ENTER}")
Then Compile and Build from Tools menu of the Autoit tool -> SciTE Script Editor.
Paste the below Java code in Eclipse editor and save
Java Code:
driver.findElement(By.id("uploadbutton")).click; // open the Upload window using selenium
Thread.sleep("20000"); // wait for page load
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "C:\\Documents and Settings\\new.exe"); // Give path where the exe is saved.
It was on Chrome for Android in my case. All the static files served from a CDN with a CNAME that's SSL encrypted were not showing up. On Chrome desktop, it all showed fine.
When I properly added the certs in ca_bundle the files displayed correctly.
Chrome for Android takes encryption seriously unlike Desktop. I hope this saves you time and stress
Using the documented jquery .data(obj) syntax allows you to store an object on the DOM element. Inspecting the element will not show the data-
attribute because there is no key specified for the value of the object. However, data within the object can be referenced by key with .data("foo")
or the entire object can be returned with .data()
.
So assuming you set up a loop and result[i] = { name: "image_name" }
:
$('.delete')[i].data(results[i]); // => <button class="delete">Delete</delete>
$('.delete')[i].data('name'); // => "image_name"
$('.delete')[i].data(); // => { name: "image_name" }
In Spring boot: 2.1.6, you can use like below:
@GetMapping("/orders")
@ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
public List<OrderResponse> getOrders(
@RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
@RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
@RequestParam(value = "location_id", required = true) String location_id) {
// TODO...
return response;
@ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.
I found that by using attr
you would end up with multiple options selected when you didn't want to - solution is to use prop
:
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().
<?php
function var_export_min($var, $return = false) {
if (is_array($var)) {
$toImplode = array();
foreach ($var as $key => $value) {
$toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
}
$code = 'array('.implode(',', $toImplode).')';
if ($return) return $code;
else echo $code;
} else {
return var_export($var, $return);
}
}
?>
I wanted to share another solution for adding roles:
<h2>Create Role</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<span class="label label-primary">Role name:</span>
<p>
@Html.TextBox("RoleName", null, new { @class = "form-control input-lg" })
</p>
<input type="submit" value="Save" class="btn btn-primary" />
}
Controller:
[HttpGet]
public ActionResult AdminView()
{
return View();
}
[HttpPost]
public ActionResult AdminView(FormCollection collection)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(collection["RoleName"]) == false)
{
Guid guid = Guid.NewGuid();
roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = collection["RoleName"] });
}
return View();
}
on button click, first open the database, fetch the data and close the data base like this
public class cytaty extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galeria);
Button bLosuj = (Button) findViewById(R.id.button1);
bLosuj.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myDatabaseHelper = new DatabaseHelper(cytaty.this);
myDatabaseHelper.openDataBase();
String text = myDatabaseHelper.getYourData(); //this is the method to query
myDatabaseHelper.close();
// set text to your TextView
}
});
}
}
and your getYourData()
in database class would be like this
public String[] getAppCategoryDetail() {
final String TABLE_NAME = "name of table";
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
if (cursor.moveToFirst()) {
do {
// get the data into array, or class variable
} while (cursor.moveToNext());
}
cursor.close();
return data;
}
If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.
For this example however I don't think you need the first s:
DELETE s
FROM spawnlist AS s
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate
WHERE n.type = "monster";
It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:
SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";
You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html
You can OpenGL without a wrapper and use it natively in C#. Just as Jeff Mc said, you would have to import all the functions you need with DllImport.
What he left out is having to create context before you can use any of the OpenGL functions. It's not hard, but there are few other not-so-intuitive DllImports that need to be done.
I have created an example C# project in VS2012 with almost the bare minimum necessary to get OpenGL running on Windows box. It only paints the window blue, but it should be enough to get you started. The example can be found at http://www.glinos-labs.org/?q=programming-opengl-csharp. Look for the No Wrapper example at the bottom.
No.
But, if it's really that important, you have 2 options (first is tested, second isn't):
First, use setters and getters, like so:
var myobj = {a : 1};
function create_gets_sets(obj) { // make this a framework/global function
var proxy = {}
for ( var i in obj ) {
if (obj.hasOwnProperty(i)) {
var k = i;
proxy["set_"+i] = function (val) { this[k] = val; };
proxy["get_"+i] = function () { return this[k]; };
}
}
for (var i in proxy) {
if (proxy.hasOwnProperty(i)) {
obj[i] = proxy[i];
}
}
}
create_gets_sets(myobj);
then you can do something like:
function listen_to(obj, prop, handler) {
var current_setter = obj["set_" + prop];
var old_val = obj["get_" + prop]();
obj["set_" + prop] = function(val) { current_setter.apply(obj, [old_val, val]); handler(val));
}
then set the listener like:
listen_to(myobj, "a", function(oldval, newval) {
alert("old : " + oldval + " new : " + newval);
}
Second, you could put a watch on the value:
Given myobj above, with 'a' on it:
function watch(obj, prop, handler) { // make this a framework/global function
var currval = obj[prop];
function callback() {
if (obj[prop] != currval) {
var temp = currval;
currval = obj[prop];
handler(temp, currval);
}
}
return callback;
}
var myhandler = function (oldval, newval) {
//do something
};
var intervalH = setInterval(watch(myobj, "a", myhandler), 100);
myobj.set_a(2);
With SQL Developer 4.x, the language option is to be added to ..\sqldeveloper\bin\sqldeveloper.conf
, rather than ..\sqldeveloper\bin\ide.conf
:
# ----- MODIFICATION BEGIN -----
AddVMOption -Duser.language=en
# ----- MODIFICATION END -----
Added more complex example with "custom validation" on the side of controller http://jsfiddle.net/82PX4/3/
<div class='line' ng-repeat='line in ranges' ng-form='lineForm'>
low: <input type='text'
name='low'
ng-pattern='/^\d+$/'
ng-change="lowChanged(this, $index)" ng-model='line.low' />
up: <input type='text'
name='up'
ng-pattern='/^\d+$/'
ng-change="upChanged(this, $index)"
ng-model='line.up' />
<a href ng-if='!$first' ng-click='removeRange($index)'>Delete</a>
<div class='error' ng-show='lineForm.$error.pattern'>
Must be a number.
</div>
<div class='error' ng-show='lineForm.$error.range'>
Low must be less the Up.
</div>
</div>
I had to sort on several criterion (date, and, if same date; other things...). What was working on Eclipse with an older version of Java, did not worked any more on Android : comparison method violates contract ...
After reading on StackOverflow, I wrote a separate function that I called from compare() if the dates are the same. This function calculates the priority, according to the criteria, and returns -1, 0, or 1 to compare(). It seems to work now.
Yet another alternative is double brace initialization, e.g.
new ArrayList<String>() {{ add(s); }};
but it is inefficient and obscure. Therefore only suitable:
You can use this syntax to reset your bootstrap datepicker
$('#datepicker').datepicker('update','');
reference http://bootstrap-datepicker.readthedocs.org/en/latest/methods.html#update
i had this problem too . i was running different solutions at the same time using visual studio , when closing other solutions and running just the target solution , it worked fine without that error .
htmlspecialchars()
is perfectly adequate for filtering user input that is displayed in html forms.
To create a popup you'll need the following script:
<script language="javascript" type="text/javascript">
function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
</script>
Then, you link to it by:
<a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>
If you want you can call the function directly from document.ready also. Or maybe from another function.
$('#link1').text("Replacement text");
The .text()
method drops the text you pass it into the element content. Unlike using .html()
, .text()
implicitly ignores any embedded HTML markup, so if you need to embed some inline <span>
, <i>
, or whatever other similar elements, use .html()
instead.
Adding to @Paco Zarate's terrific answer above, if you want to transpose a table which has multiple types of columns, then add this to the end of line 39, so it only transposes int
columns:
and C.system_type_id = 56 --56 = type int
Here is the full query that is being changed:
select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id(@tableToPivot) and
C.name <> @columnToPivot and C.system_type_id = 56 --56 = type int
for xml path('')), 1, 1, '')
To find other system_type_id
's, run this:
select name, system_type_id from sys.types order by name
Speaking as a mere mortal, I would stick with $str[0]
. As far as I'm concerned, it's quicker to grasp the meaning of $str[0]
at a glance than substr($str, 0, 1)
. This probably boils down to a matter of preference.
As far as performance goes, well, profile profile profile. :) Or you could peer into the PHP source code...
If the reimport does not work (i.e. doesn't remove old versions of dependencies after a pom update), there is one more chance:
I think you are all wrong. IDs versus Class is not a question of specificity; they have completely different logical uses.
IDs should be used to identify specific parts of a page: the header, the nav bar, the main article, author attribution, footer.
Classes should be used to apply styles to the page. Let's say you have a general magazine site. Every page on the site is going to have the same elements--header, nav, main article, sidebar, footer. But your magazine has different sections--economics, sports, entertainment. You want the three sections to have different looks--economics conservative and square, sports action-y, entertainment bright and young.
You use classes for that. You don't want to have to make multiple IDs--#economics-article and #sports-article and #entertainment-article. That doesn't make sense. Rather, you would define three classes, .economics, sports, and .entertainment, then define the #nav, #article, and #footer ids for each.
There are some actions which are not working in chrome, inside of the unload event. Alert or confirm boxes are such things.
But what is possible (AFAIK):
Example for #2:
$(window).on('beforeunload', function() {
return 'Your own message goes here...';
});
Try this:
$('.datepicker').datepicker('update', new Date(year,month,day));
Use Range in Python 3.
Here is a example function that return in between numbers from two numbers
def get_between_numbers(a, b):
"""
This function will return in between numbers from two numbers.
:param a:
:param b:
:return:
"""
x = []
if b < a:
x.extend(range(b, a))
x.append(a)
else:
x.extend(range(a, b))
x.append(b)
return x
Result
print(get_between_numbers(5, 9))
print(get_between_numbers(9, 5))
[5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
// original_x000D_
var arr = [{_x000D_
key: '11',_x000D_
value: '1100',_x000D_
$$hashKey: '00X'_x000D_
},_x000D_
{_x000D_
key: '22',_x000D_
value: '2200',_x000D_
$$hashKey: '018'_x000D_
}_x000D_
];_x000D_
_x000D_
// My solution_x000D_
var obj = {};_x000D_
for (let i = 0; i < arr.length; i++) {_x000D_
obj[arr[i].key] = arr[i].value;_x000D_
}_x000D_
console.log(obj)
_x000D_
and the fully automated way with bash and expect ( in this example we provision a new postgres admin with the newly provisioned postgres pw both on OS and postgres run-time level )
# the $postgres_usr_pw and the other bash vars MUST be defined
# for reference the manual way of doing things automated with expect bellow
#echo "copy-paste: $postgres_usr_pw"
#sudo -u postgres psql -c "\password"
# the OS password could / should be different
sudo -u root echo "postgres:$postgres_usr_pw" | sudo chpasswd
expect <<- EOF_EXPECT
set timeout -1
spawn sudo -u postgres psql -c "\\\password"
expect "Enter new password: "
send -- "$postgres_usr_pw\r"
expect "Enter it again: "
send -- "$postgres_usr_pw\r"
expect eof
EOF_EXPECT
cd /tmp/
# at this point the postgres uses the new password
sudo -u postgres PGPASSWORD=$postgres_usr_pw psql \
--port $postgres_db_port --host $postgres_db_host -c "
DO \$\$DECLARE r record;
BEGIN
IF NOT EXISTS (
SELECT
FROM pg_catalog.pg_roles
WHERE rolname = '"$postgres_db_useradmin"') THEN
CREATE ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
CREATEDB REPLICATION BYPASSRLS
PASSWORD '"$postgres_db_useradmin_pw"' LOGIN ;
END IF;
END\$\$;
ALTER ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
CREATEDB REPLICATION BYPASSRLS
PASSWORD '"$postgres_db_useradmin_pw"' LOGIN ;
"
From JDK 14+ which includes JEP 305 we can do Pattern Matching for instanceof
Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type.
Before Java 14
if (obj instanceof String) {
String str = (String) obj; // need to declare and cast again the object
.. str.contains(..) ..
}else{
str = ....
}
Java 14 enhancements
if (!(obj instanceof String str)) {
.. str.contains(..) .. // no need to declare str object again with casting
} else {
.. str....
}
We can also combine the type check and other conditions together
if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
The use of pattern matching in instanceof
should reduce the overall number of explicit casts in Java programs.
PS: instanceOf
will only match when the object is not null, then only it can be assigned to str
.
In case of Request to a REST Service:
You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:
@CrossOrigin(origins = "http://localhost:8080")
Very good tutorial: https://spring.io/guides/gs/rest-service-cors/
SQLParam = cmd.Parameters.Add("@RetailerID", SqlDbType.Int, 4)
If p_RetailerID.Length = 0 Or p_RetailerID = "0" Then
SQLParam.Value = DBNull.Value
Else
SQLParam.Value = p_RetailerID
End If
I find that I run into Net::HTTP and Net::FTP problems like this periodically, and when I do, surrounding the call with a timeout() makes all of those issues vanish. So where this will occasionally hang for 3 minutes or so and then raise an EOFError:
res = Net::HTTP.post_form(uri, args)
This always fixes it for me:
res = timeout(120) { Net::HTTP.post_form(uri, args) }
Download the file of website and start it with the commandline switch "/layout" (see msdn to download visual studio 2015 installer for offline installation). So C:\vs_community.exe /layout
for example. It asks for a location and the download begins.
EDIT: With the ISO version you still need internet connection to be able to install ALL the features. As pointed out by Augusto Barreto.
you can use setInterval()
in javascript
<script>
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall(){...}
</script>
SELECT product FROM Your_table_name WHERE Product LIKE '%XYZ%';
The above statement will show result from a single table. If you want to add more tables then simply use the UNION statement.
SELECT product FROM Table_name_1
WHERE Product LIKE '%XYZ%'
UNION
SELECT product FROM Table_name_2
WHERE Product LIKE '%XYZ%'
UNION
SELECT product FROM Table_name_3
WHERE Product LIKE '%XYZ%'
... and so on
URL url = new URL("https://www.google.com");
//if you are using
URLConnection conn =url.openConnection();
//change it to
HttpURLConnection conn =(HttpURLConnection )url.openConnection();
From a tech perspective: Just model what Google does when you hit them with too many queries at once. That should put a halt to a lot of it.
From a legal perspective: It sounds like the data you're publishing is not proprietary. Meaning you're publishing names and stats and other information that cannot be copyrighted.
If this is the case, the scrapers are not violating copyright by redistributing your information about artist name etc. However, they may be violating copyright when they load your site into memory because your site contains elements that are copyrightable (like layout etc).
I recommend reading about Facebook v. Power.com and seeing the arguments Facebook used to stop screen scraping. There are many legal ways you can go about trying to stop someone from scraping your website. They can be far reaching and imaginative. Sometimes the courts buy the arguments. Sometimes they don't.
But, assuming you're publishing public domain information that's not copyrightable like names and basic stats... you should just let it go in the name of free speech and open data. That is, what the web's all about.
Jonathan Feinberg's answer prints each field on a separate line. You could use printf
to rebuild the record for output on the same line, but you can also just move the fields a jump to the left.
awk '{for (i=1; i<=NF-2; i++) $i = $(i+2); NF-=2; print}' logfile
For people landing here from google like me and just want to build containers using multiple docker-compose files with one shared service:
Sometimes you have different projects that would share e.g. a database docker container. Only the first run should start the DB-Docker, the second should be detect that the DB is already running and skip this. To achieve such a behaviour we need the Dockers to lay in the same network and in the same project. Also the docker container name needs to be the same.
1st: Set the same network and container name in docker-compose
docker-compose in project 1:
version: '3'
services:
service1:
depends_on:
- postgres
# ...
networks:
- dockernet
postgres:
container_name: project_postgres
image: postgres:10-alpine
restart: always
# ...
networks:
- dockernet
networks:
dockernet:
docker-compose in project 2:
version: '3'
services:
service2:
depends_on:
- postgres
# ...
networks:
- dockernet
postgres:
container_name: project_postgres
image: postgres:10-alpine
restart: always
# ...
networks:
- dockernet
networks:
dockernet:
2nd: Set the same project using -p
param or put both files in the same directory.
docker-compose -p {projectname} up
You cannot select a row like that. You have to specify a field whose values will be 3
Here is a query that will work, if the field you are comparing against is id
select * from customer where `id` = 3
You can output special color control codes to get colored terminal output, here's a good resource on how to print colors.
For example:
printf("\033[22;34mHello, world!\033[0m"); // shows a blue hello world
EDIT: My original one used prompt color codes, which doesn't work :( This one does (I tested it).
I upgraded from Silverlight 4 to Silverlight 5 and then I was having this issue. Although I had a reference to "System.ComponentModel.DataAnnotations" under "References" in my project, it had a yellow yield sign by it that indicated the previously referenced assembly could not be found. It turned out that the properties of the "System.ComponentModel.DataAnnotations" reference indicated "Specific Version = True", when I changed this to "Specific Version = False" it fixed the issue. Right click on the "System.ComponentModel.DataAnnotations" assembly under "References" and select "Properties" from the context menu. Check that the property value for "Specific Version = False".
It must have been referencing the old Silverlight 4 assembly which was no longer available after the upgrade to Silverlight 5.
Little addition in answer if you have different user rather then dbo
then do like this.
EXEC [ServerName].[DatabaseName].dbo.sp_HelpText '[user].[storedProcName]'
By default, np.genfromtxt
uses dtype=float
: that's why you string columns are converted to NaNs because, after all, they're Not A Number...
You can ask np.genfromtxt
to try to guess the actual type of your columns by using dtype=None
:
>>> from StringIO import StringIO
>>> test = "a,1,2\nb,3,4"
>>> a = np.genfromtxt(StringIO(test), delimiter=",", dtype=None)
>>> print a
array([('a',1,2),('b',3,4)], dtype=[('f0', '|S1'),('f1', '<i8'),('f2', '<i8')])
You can access the columns by using their name, like a['f0']
...
Using dtype=None
is a good trick if you don't know what your columns should be. If you already know what type they should have, you can give an explicit dtype
. For example, in our test, we know that the first column is a string, the second an int, and we want the third to be a float. We would then use
>>> np.genfromtxt(StringIO(test), delimiter=",", dtype=("|S10", int, float))
array([('a', 1, 2.0), ('b', 3, 4.0)],
dtype=[('f0', '|S10'), ('f1', '<i8'), ('f2', '<f8')])
Using an explicit dtype
is much more efficient than using dtype=None
and is the recommended way.
In both cases (dtype=None
or explicit, non-homogeneous dtype
), you end up with a structured array.
[Note: With dtype=None
, the input is parsed a second time and the type of each column is updated to match the larger type possible: first we try a bool, then an int, then a float, then a complex, then we keep a string if all else fails. The implementation is rather clunky, actually. There had been some attempts to make the type guessing more efficient (using regexp), but nothing that stuck so far]
There is nothing wrong with returning a void @ResponseBody
and you should for POST
requests.
Use HTTP status codes to define errors within exception handler routines instead as others are mentioning success status. A normal method as you have will return a response code of 200
which is what you want, any exception handler can then return an error object and a different code (i.e. 500
).
The OP's question: What is the difference between the return and exit statement in BASH functions with respect to exit codes?
Firstly, some clarification is required:
A (return|exit) statement is not required to terminate execution of a (function|shell). A (function|shell) will terminate when it reaches the end of its code list, even with no (return|exit) statement.
A (return|exit) statement is not required to pass a value back from a terminated (function|shell). Every process has a built-in variable $?
which always has a numeric value. It is a special variable that cannot be set like "?=1", but it is set only in special ways (see below *).
The value of $? after the last command to be executed in the (called function | sub shell) is the value that is passed back to the (function caller | parent shell). That is true whether the last command executed is ("return [n]"| "exit [n]") or plain ("return" or something else which happens to be the last command in the called function's code.
In the above bullet list, choose from "(x|y)" either always the first item or always the second item to get statements about functions and return, or shells and exit, respectively.
What is clear is that they both share common usage of the special variable $?
to pass values upwards after they terminate.
* Now for the special ways that $?
can be set:
$?
in the terminated function.$?
in the parent shell will be equal to the final value of $?
in the terminated sub shell.$?
depending upon their result. But some don't.$?
with argument, and terminate execution.It is worth noting that $?
can be assigned a value by calling exit in a sub shell, like this:
# (exit 259)
# echo $?
3
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
If you are using plain LINQ-to-objects and don't want to take a dependency on an external library it is not hard to achieve what you want.
The OrderBy()
clause accepts a Func<TSource, TKey>
that gets a sort key from a source element. You can define the function outside the OrderBy()
clause:
Func<Item, Object> orderByFunc = null;
You can then assign it to different values depending on the sort criteria:
if (sortOrder == SortOrder.SortByName)
orderByFunc = item => item.Name;
else if (sortOrder == SortOrder.SortByRank)
orderByFunc = item => item.Rank;
Then you can sort:
var sortedItems = items.OrderBy(orderByFunc);
This example assumes that the source type is Item
that have properties Name
and Rank
.
Note that in this example TKey
is Object
to not constrain the property types that can be sorted on. If the func returns a value type (like Int32
) it will get boxed when sorting and that is somewhat inefficient. If you can constrain TKey
to a specific value type you can work around this problem.
if name in ("Jesse", "jesse"):
would be the correct way to do it.
Although, if you want to use or
, the statement would be
if name == 'Jesse' or name == 'jesse':
>>> ("Jesse" or "jesse")
'Jesse'
evaluates to 'Jesse'
, so you're essentially not testing for 'jesse'
when you do if name == ("Jesse" or "jesse")
, since it only tests for equality to 'Jesse'
and does not test for 'jesse'
, as you observed.
If you want something like the python3 print function but to a string:
def sprint(*args, **kwargs):
sio = io.StringIO()
print(*args, **kwargs, file=sio)
return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}\n"
or without the '\n'
at the end:
def sprint(*args, end='', **kwargs):
sio = io.StringIO()
print(*args, **kwargs, end=end, file=sio)
return sio.getvalue()
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}"
If lakes
is your DataFrame
, you can do something like
area_dict = dict(zip(lakes.area, lakes.count))
Check this Plugin for eclipse which can do the job you are looking for.
From Pro C# 5.0 and the .NET 4.5 Framework
The ObservableCollection<T>
class is very useful in that it has the ability to inform external objects
when its contents have changed in some way (as you might guess, working with
ReadOnlyObservableCollection<T>
is very similar, but read-only in nature).
In many ways, working with
the ObservableCollection<T>
is identical to working with List<T>
, given that both of these classes
implement the same core interfaces. What makes the ObservableCollection<T>
class unique is that this
class supports an event named CollectionChanged
. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified.
Like any event, CollectionChanged is defined in terms of a delegate, which in this case is
NotifyCollectionChangedEventHandler
. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs
as the second. Consider the following Main()
method, which populates an observable collection containing Person objects and wires up the
CollectionChanged
event:
class Program
{
static void Main(string[] args)
{
// Make a collection to observe and add a few Person objects.
ObservableCollection<Person> people = new ObservableCollection<Person>()
{
new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
};
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;
// Now add a new item.
people.Add(new Person("Fred", "Smith", 32));
// Remove an item.
people.RemoveAt(0);
Console.ReadLine();
}
static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// What was the action that caused the event?
Console.WriteLine("Action for this event: {0}", e.Action);
// They removed something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
Console.WriteLine("Here are the OLD items:");
foreach (Person p in e.OldItems)
{
Console.WriteLine(p.ToString());
}
Console.WriteLine();
}
// They added something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
// Now show the NEW items that were inserted.
Console.WriteLine("Here are the NEW items:");
foreach (Person p in e.NewItems)
{
Console.WriteLine(p.ToString());
}
}
}
}
The incoming NotifyCollectionChangedEventArgs
parameter defines two important properties,
OldItems
and NewItems
, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when
items are added, removed, relocated, or reset. To discover which of these actions triggered the event,
you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be
tested against any of the following members of the NotifyCollectionChangedAction
enumeration:
public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}
If its simply a case of knowing/seeing who is in a file at any particular time (and if you're using windows) just select the file 'view' as 'details', i.e. rather than Thumbnails, tiles or icons etc. Once in 'details' view, by default you will be shown; - File name - Size - Type, and - Date modified
All you you need to do now is right click anywhere along said toolbar (file name, size, type etc...) and you will be given a list of other options that the toolbar can display.
Select 'Owner' and a new column will show the username of the person using the file or who originally created it if nobody else is using it.
This can be particularly useful when using a shared MS Access database.
you just need to use word boundary (\b
) instead of ^
and $
:
\bgarp\b
A cast, as Blaz Bratanic suggested:
size_t data = 99999999;
int convertdata = static_cast<int>(data);
is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).
But it doesn't solve the problem that the warning was telling you about, namely that a conversion from size_t
to int
really could overflow.
If at all possible, design your program so you don't need to convert a size_t
value to int
. Just store it in a size_t
variable (as you've already done) and use that.
Converting to double
will not cause an overflow, but it could result in a loss of precision for a very large size_t
value. Again, it doesn't make a lot of sense to convert a size_t
to a double
; you're still better off keeping the value in a size_t
variable.
(R Sahu's answer has some suggestions if you can't avoid the cast, such as throwing an exception on overflow.)
For those using the Google API Client Library for PHP and seeking offline access and refresh tokens beware as of the time of this writing the docs are showing incorrect examples.
currently it's showing:
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true); // incremental auth
source: https://developers.google.com/identity/protocols/OAuth2WebServer#offline
All of this works great - except ONE piece
$client->setApprovalPrompt("consent");
After a bit of reasoning I changed this line to the following and EVERYTHING WORKED
$client->setPrompt("consent");
It makes sense since using the HTTP requests it was changed from approval_prompt=force to prompt=consent. So changing the setter method from setApprovalPrompt to setPrompt follows natural convention - BUT IT'S NOT IN THE DOCS!!! That I found at least.
Just add parenthesis around the query:
set @user = 123456;
set @group = (select GROUP from USER where User = @user);
select * from USER where GROUP = @group;
docker-compose down
If VPN is connected, then disconnect it and try again to up docker container:
docker-compose up -d container_name
We can convert Today's date in the format of 'JUN 12, 2020'.
String.valueOf(DateFormat.getDateInstance().format(new Date())));
With java-8, you'll be able to do this in one line using streams, and the Collectors
class.
Map<String, Item> map =
list.stream().collect(Collectors.toMap(Item::getKey, item -> item));
Short demo:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test{
public static void main (String [] args){
List<Item> list = IntStream.rangeClosed(1, 4)
.mapToObj(Item::new)
.collect(Collectors.toList()); //[Item [i=1], Item [i=2], Item [i=3], Item [i=4]]
Map<String, Item> map =
list.stream().collect(Collectors.toMap(Item::getKey, item -> item));
map.forEach((k, v) -> System.out.println(k + " => " + v));
}
}
class Item {
private final int i;
public Item(int i){
this.i = i;
}
public String getKey(){
return "Key-"+i;
}
@Override
public String toString() {
return "Item [i=" + i + "]";
}
}
Output:
Key-1 => Item [i=1]
Key-2 => Item [i=2]
Key-3 => Item [i=3]
Key-4 => Item [i=4]
As noted in comments, you can use Function.identity()
instead of item -> item
, although I find i -> i
rather explicit.
And to be complete note that you can use a binary operator if your function is not bijective. For example let's consider this List
and the mapping function that for an int value, compute the result of it modulo 3:
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<String, Integer> map =
intList.stream().collect(toMap(i -> String.valueOf(i % 3), i -> i));
When running this code, you'll get an error saying java.lang.IllegalStateException: Duplicate key 1
. This is because 1 % 3 is the same as 4 % 3 and hence have the same key value given the key mapping function. In this case you can provide a merge operator.
Here's one that sum the values; (i1, i2) -> i1 + i2;
that can be replaced with the method reference Integer::sum
.
Map<String, Integer> map =
intList.stream().collect(toMap(i -> String.valueOf(i % 3),
i -> i,
Integer::sum));
which now outputs:
0 => 9 (i.e 3 + 6)
1 => 5 (i.e 1 + 4)
2 => 7 (i.e 2 + 5)
Hope it helps! :)
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
In addition to what was already said - in order to avoid this error from interfering (stopping) other Javascript code on your page, you could try forcing the YouTube iframe to load last - after all other Javascript code is loaded.
can be done with the plugin: https://wiki.jenkins-ci.org/display/JENKINS/Next+Build+Number+Plugin
more info: http://www.alexlea.me/2010/10/howto-set-hudson-next-build-number.html
if you don't like the plugin:
If you want to change build number via nextBuildNumber file you should "Reload Configuration from Disk" from "Manage Jenkins" page.
git log --grep=<pattern>
Limit the commits output to ones with log message that matches the
specified pattern (regular expression).
Acepted solution implemented in PyQt5
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.le.setText("Host")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("Connect")
self.pb.clicked.connect(self.button_click)
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.pb)
self.setLayout(layout)
self.setWindowTitle("Learning")
def button_click(self):
# shost is a QString object
shost = self.le.text()
print (shost)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
sed 's/^.\{,5\}//' file.dat
After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...
You can use expandtabs
to specify the tabstop, like this:
>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))
#Output:
Location:10-10-10-10 Revision: 1
District: Tower Date: May 16, 2012
In general, there should be one class per file. If you organise things that way, then when you search for a class, you know you only need to search for the file with that name.
The exception is when a class is best implemented using one or more small helper classes. Usually, the code is easiest to follow when those classes are present in the same file. For instance, you might need a small 'tuple' wrapper class to pass some data between method calls. Another example are 'task' classes implementing Runnable or Callable. They may be so small that they are best combined with the parent class creating and calling them.
Make a virtual enviroment using python3
virtualenv env_name --python="python3"
and run the following command
pip3 install opencv-python
In order to count the number of keywords in a dictionary:
def dict_finder(dict_finders):
x=input("Enter the thing you want to find: ")
if x in dict_finders:
print("Element found")
else:
print("Nothing found:")
My answer is a mod of some prior answers from @JoeMills and @user.
Get a cURL
command to log into server:
Modify cURL command to be able to save session cookie after login
-H 'Cookie: <somestuff>'
curl
at beginning -c login_cookie.txt
'login_cookie.txt'
in the same folderCall a new web page using this new cookie that requires you to be logged in
curl -b login_cookie.txt <url_that_requires_log_in>
I have tried this on Ubuntu 20.04 and it works like a charm.
Try Like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class UserController extends Controller
{
function index(){
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
}
}
?>
You can find all database names with this:-
select name from sys.sysdatabases
Specify the paths explicitly:
git diff HEAD:full/path/to/foo full/path/to/bar
Check out the --find-renames
option in the git-diff
docs.
Credit: twaggs.
Format with Currency format string
=Format(Fields!Price.Value, "C")
It will give you 2 decimal places with "$" prefixed.
You can find other format strings on MSDN: Adding Style and Formatting to a ReportViewer Report
Note: The MSDN article has been archived to the "VS2005_General" document, which is no longer directly accessible online. Here is the excerpt of the formatting strings referenced:
Formatting Numbers
The following table lists common .NET Framework number formatting strings.
Format string, Name
C or c Currency
D or d Decimal
E or e Scientific
F or f Fixed-point
G or g General
N or n Number
P or p Percentage
R or r Round-trip
X or x Hexadecimal
You can modify many of the format strings to include a precision specifier that defines the number of digits to the right of the
decimal point. For example, a formatting string of D0 formats the number so that it has no digits after the decimal point. You
can also use custom formatting strings, for example, #,###.
Formatting Dates
The following table lists common .NET Framework date formatting strings.
Format string, Name
d Short date
D Long date
t Short time
T Long time
f Full date/time (short time)
F Full date/time (long time)
g General date/time (short time)
G General date/time (long time)
M or m Month day
R or r RFC1123 pattern
Y or y Year month
You can also a use custom formatting strings; for example, dd/MM/yy. For more information about .NET Framework formatting strings, see Formatting Types.
The best approach depends on what you want to do:
Edited on 2016 October
In this code example I use "array.filter(...)" function to remove unwanted items from an array. This function doesn't change the original array and creates a new one. If your browser doesn't support this function (e.g. Internet Explorer before version 9, or Firefox before version 1.5), consider using the filter polyfill from Mozilla.
var value = 3
var arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(function(item) {
return item !== value
})
console.log(arr)
// [ 1, 2, 4, 5 ]
let value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
IMPORTANT ECMAScript 6 "() => {}" arrow function syntax is not supported in Internet Explorer at all, Chrome before 45 version, Firefox before 22 version, and Safari before 10 version. To use ECMAScript 6 syntax in old browsers you can use BabelJS.
An additional advantage of this method is that you can remove multiple items
let forDeletion = [2, 3, 5]
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => !forDeletion.includes(item))
// !!! Read below about array.includes(...) support !!!
console.log(arr)
// [ 1, 4 ]
IMPORTANT "array.includes(...)" function is not supported in Internet Explorer at all, Chrome before 47 version, Firefox before 43 version, Safari before 9 version, and Edge before 14 version so here is polyfill from Mozilla.
If the "This-Binding Syntax" proposal is ever accepted, you'll be able to do this:
// array-lib.js
export function remove(...forDeletion) {
return this.filter(item => !forDeletion.includes(item))
}
// main.js
import { remove } from './array-lib.js'
let arr = [1, 2, 3, 4, 5, 3]
// :: This-Binding Syntax Proposal
// using "remove" function as "virtual method"
// without extending Array.prototype
arr = arr::remove(2, 3, 5)
console.log(arr)
// [ 1, 4 ]
Reference
Instead of editing the bringup service, add a post-start delay to the service which it depends on. Edit cassandra.service
like so:
ExecStartPost=/bin/sleep 30
This way the added sleep shouldn't slow down restarts of starting services that depend on it (though does slow down its own start, maybe that's desirable?).
You need to do this:
OleDbConnection connection = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet DS = new DataSet();
connection.Open();
string query =
@"SELECT tbl_Computer.*, tbl_Besitzer.*
FROM tbl_Computer
INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID
WHERE (((tbl_Besitzer.Vorname)='ma'))";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection);
DBAdapter.Fill(DS);
By the way, what is this DataSet1? This should be "DataSet".
I used modified (added signed_request param to the link) Whiteagle's trick and it worked ok for safari, but IE is constantly refreshing the page in that case. So my solution for safari and internet explorer is:
$fbapplink = 'https://apps.facebook.com/[appnamespace]/';
$isms = stripos($_SERVER['HTTP_USER_AGENT'], 'msie') !== false;
// safari fix
if(! $isms && !isset($_SESSION['signed_request'])) {
if (isset($_GET["start_session"])) {
$_SESSION['signed_request'] = $_GET['signed_request'];
die(header("Location:" . $fbapplink ));
}
if (!isset($_GET["sid"])) {
die(header("Location:?sid=" . session_id() . '&signed_request='.$_REQUEST['signed_request']));
}
$sid = session_id();
if (empty($sid) || $_GET["sid"] != $sid) {
?>
<script>
top.window.location="?start_session=true";
</script>
<?php
exit;
}
}
// IE fix
header('P3P: CP="CAO PSA OUR"');
header('P3P: CP="HONK"');
.. later in the code
$sr = $_REQUEST['signed_request'];
if($sr) {
$_SESSION['signed_request'] = $sr;
} else {
$sr = $_SESSION['signed_request'];
}
Just because it is so difficult to find and it has to be spread: in mySQL this can be done much simpler, but I don't know if it works in other SQL.
SELECT * FROM `comments`
WHERE `comments`.`id` IN ('12','5','3','17')
ORDER BY FIELD(`comments`.`id`,'12','5','3','17')
This way:
<script type="text/javascript">
function yourFunction(element) {
alert(element);
}
</script>
<input id="myinput" onblur="yourFunction(this)">
Or if you attach the listener via JavaScript (jQuery in this example):
var input = $('#myinput').blur(function() {
alert(this);
});
Edit: sorry. I misread the question.
grep -n "YOUR SEARCH STRING" * > output-file
The -n
will print the line number and the >
will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe |
for example:
grep -n "test" * | grep -v "mytest" > output-file
will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v
) - and will redirect the result to an output file.
A few good grep-tips can be found on this post
Starting with Android Studio 2.0 you can do it with the new emulator:
Just click 3 "Take Screenshot". Standard location is the desktop.
Or
UPDATE 22/07/2020
If you keep the emulator in Android Studio as possible since Android Studio 4.1 click here to save the screenshot in your standard location:
<style type="text/css">
div.inline { display:inline; }
</style>
<div class="inline">a</div>
<div class="inline">b</div>
<div class="inline">c</div>
Are you sure you have a column DEPARTEMENT_CODE on your table PS_TBL_DEPARTMENT_DETAILS
More informations about your ERROR
ORA-00904: string: invalid identifier Cause: The column name entered is either missing or invalid. Action: Enter a valid column name. A valid column name must begin with a letter, be less than or equal to 30 characters, and consist of only alphanumeric characters and the special characters $, _, and #. If it contains other characters, then it must be enclosed in d double quotation marks. It may not be a reserved word.
It's better to separate 'development' and 'production' configs.
I use following way: Here is my config/index.js file:
const config = {
dev : {
ip_address : '0.0.0.0',
port : 8080,
mongo :{
url : "mongodb://localhost:27017/story_box_dev",
options : ""
}
},
prod : {
ip_address : '0.0.0.0',
port : 3000,
mongo :{
url : "mongodb://localhost:27017/story_box_prod",
options : ""
}
}
}
For require the config use following:
const config = require('../config')[process.env.NODE_ENV];
Than you can use your config object:
const ip_address = config.ip_address;
const port = config.port;
I am not able to run my own build on the other suggestions here. I even tried different versions of maven-compiler-plugin: 3.1, 3.7.0, etc.
I made it work adding this:
<testSourceDirectory>/src/test/java</testSourceDirectory>
I tried this approach because it seems like the /src/test/java directory is considered a java class that is why it is compiled the same time as /src/test/java. So my hunch were right in my case.
Maybe it is to others too, so just try this one.
5 step to do what you want if you made the pull request from a forked repository:
And everything is done, good luck!
In my case:
sudo -E add-apt-repository ppa:linuxuprising/java
sudo apt-get update
sudo apt install oracle-java12-installer
that works fine
Have you tried this:
function doSomething() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
}
$('.tag1, .tag2').click(doSomething);
Close PHP Storm in terminal go to the project folder type
git rm -rf .idea; git commit -m "delete .idea"; git push;
Then go to project folder and delete the folder .idea
sudo rm -r .idea/
Start PhpStorm and you are done
There are a couple ways to do this.
First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:
E:\> openssl x509 -pubkey -noout -in cert.pem > pubkey.pem
If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.
openssl> x509 -pubkey -noout -in cert.pem
Output will look something like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----
Are you using JTextArea
's append(String)
method to add additional text?
JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");
You can try it with DecimalFormat
. With this class you are very flexible in parsing your numbers.
You can exactly set the pattern you want to use.
In your case for example:
double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678
The same solution can be written in a slightly different way as I would like to set the columns only once I have written about both the tables. Working in mysql.
UPDATE Table t,
(SELECT col1, col2 FROM other_table WHERE sql = 'cool' ) o
SET t.col1 = o.col1, t.col2=o.col2
WHERE t.id = o.id
Date
is Comparable
so just create list of List<Date>
and sort it using Collections.sort()
. And use Collections.reverseOrder()
to get comparator in reverse ordering
.
From Java Doc
Returns a comparator that imposes the reverse ordering of the specified comparator. If the specified comparator is null, this method is equivalent to reverseOrder() (in other words, it returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface).
It seems like the $in
operator would serve your purposes just fine.
You could do something like this (pseudo-query):
if (db.courses.find({"students" : {"$in" : [studentId]}, "course" : courseId }).count() > 0) {
// student is enrolled in class
}
Alternatively, you could remove the "course" : courseId
clause and get back a set of all classes the student is enrolled in.
Can we see the structure of your table? If I am understanding this, then the assumption made by the query is that a record can be only meta_key - 'lat'
or meta_key = 'long'
not both because each row only has one meta_key
column and can only contain 1 corresponding value, not 2. That would explain why you don't get results when you connect the with an AND
; it's impossible.
One of the challenges I had with the answers is that it assumed that the object was a single level. For example,
const testObj = { testKey: 'testValue' }
const refString = 'testKey';
const refObj = testObj[refString];
works fine, but
const testObj = { testKey:
{ level2Key: 'level2Value' }
}
const refString = 'testKey.level2Key';
const refObj = testObj[refString];
does not work.
What I ended up doing was building a function to access multi-level objects:
objVar(str) {
let obj = this;
const parts = str.split('.');
for (let p of parts) {
obj = obj[p];
}
return obj;
}
In the second scenario, then, I can pass the string to this function to get back the object I'm looking for:
const testObj = { testKey:
{ level2Key: 'level2Value' }
}
const refString = 'testObj.testKey.level2Key';
const refObj = objVar[refString];
Here are my 2 cents. Nothing new, but some explanations, improvements and newer code.
By default, RestTemplate
has infinite timeout.
There are two kinds of timeouts: connection timeout and read time out. For instance, I could connect to the server but I could not read data. The application was hanging and you have no clue what's going on.
I am going to use annotations, which these days are preferred over XML.
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
var factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(3000);
factory.setReadTimeout(3000);
return new RestTemplate(factory);
}
}
Here we use SimpleClientHttpRequestFactory
to set the connection and read time outs.
It is then passed to the constructor of RestTemplate
.
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.setConnectTimeout(Duration.ofMillis(3000))
.setReadTimeout(Duration.ofMillis(3000))
.build();
}
}
In the second solution, we use the RestTemplateBuilder
. Also notice the parameters of the two methods: they take Duration
. The overloaded methods that take directly milliseconds are now deprecated.
Edit Tested with Spring Boot 2.1.0 and Java 11.
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
Firebug + console.log(myObjectInstance)
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="retun callMethod();" />
<script type="text/javascript">
function callMethod() {
//your logic should be here and make sure your logic code note returing function
return false;
}
</script>
Try the following:
SELECT *, (FieldA + FieldB) AS Sum
FROM Table
If u want to add Hello world at the end of each line:
:%s/$/HelloWorld/
If you want to do this for specific number of line say, from 20 to 30 use:
:20,30s/$/HelloWorld/
If u want to do this at start of each line then use:
:20,30s/^/HelloWorld/
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
Some differences are as follows:
1- React-Native is a framework which used to create Mobile Apps, where ReactJS is a javascript library you can use for your website.
2- React-Native doesn’t use HTML to render the app while React uses.
3- React-Native used for developing only Mobile App while React use for website and Mobile.
Well I found the answer set "aaSorting" to an empty array:
$(document).ready( function() {
$('#example').dataTable({
/* Disable initial sort */
"aaSorting": []
});
})
For newer versions of Datatables (>= 1.10) use order option:
$(document).ready( function() {
$('#example').dataTable({
/* No ordering applied by DataTables during initialisation */
"order": []
});
})
Instant i = Instant.ofEpochSecond(cal.getTime);
Read more here and here
The series of vim commands ggVGg?
applies a Rot13 cipher to the text in your current document.
Gung vf zl zbfg cebqhpgvir fubegphg fvapr V nyjnlf glcr va Ebg13.
try
myDiv.offsetHeight
console.log("Height:", myDiv.offsetHeight );
_x000D_
#myDiv { width: 100px; height: 666px; background: red}
_x000D_
<div id="myDiv"></div>
_x000D_
The answer by Andrew Toulouse can be extended to division.
The division by integer constants is considered in details in the book "Hacker's Delight" by Henry S. Warren (ISBN 9780201914658).
The first idea for implementing division is to write the inverse value of the denominator in base two.
E.g.,
1/3 = (base-2) 0.0101 0101 0101 0101 0101 0101 0101 0101 .....
So,
a/3 = (a >> 2) + (a >> 4) + (a >> 6) + ... + (a >> 30)
for 32-bit arithmetics.
By combining the terms in an obvious manner we can reduce the number of operations:
b = (a >> 2) + (a >> 4)
b += (b >> 4)
b += (b >> 8)
b += (b >> 16)
There are more exciting ways to calculate division and remainders.
EDIT1:
If the OP means multiplication and division of arbitrary numbers, not the division by a constant number, then this thread might be of use: https://stackoverflow.com/a/12699549/1182653
EDIT2:
One of the fastest ways to divide by integer constants is to exploit the modular arithmetics and Montgomery reduction: What's the fastest way to divide an integer by 3?
Same thing, Just start the table name with #
or ##
:
CREATE TABLE #TemporaryTable -- Local temporary table - starts with single #
(
Col1 int,
Col2 varchar(10)
....
);
CREATE TABLE ##GlobalTemporaryTable -- Global temporary table - note it starts with ##.
(
Col1 int,
Col2 varchar(10)
....
);
Temporary table names start with #
or ##
- The first is a local temporary table and the last is a global temporary table.
Here is one of many articles describing the differences between them.
<!-- ToolBar -->
<style name="ToolBarTheme.ToolBarStyle" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:textColorPrimary">@android:color/white</item>
<item name="android:textColor">@color/white</item>
<item name="android:textColorPrimaryInverse">@color/white</item>
</style>
Too late to post, this worked for me to change the color of the back button
Building on Allison and Deepak's answer, I started using logrus and really like it:
var log = logrus.New()
func init() {
// log to console and file
f, err := os.OpenFile("crawler.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
wrt := io.MultiWriter(os.Stdout, f)
log.SetOutput(wrt)
}
I have a defer f.Close() in the main function
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
Visual Studio defines _DEBUG
when you specify the /MTd
or /MDd
option, NDEBUG
disables standard-C assertions. Use them when appropriate, ie _DEBUG
if you want your debugging code to be consistent with the MS CRT debugging techniques and NDEBUG
if you want to be consistent with assert()
.
If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.
Use os.rename
. But you have to pass full path of both files to the function. If I have a file a.txt
on my desktop so I will do and also I have to give full of renamed file too.
os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')
This works for me:
<c:forEach var="i" begin="1970" end="2000">
<option value="${2000-(i-1970)}">${2000-(i-1970)}
</option>
</c:forEach>
Class methods provide a "semantic sugar" (don't know if this term is widely used) - or "semantic convenience".
Example: you got a set of classes representing objects. You might want to have the class method all()
or find()
to write User.all()
or User.find(firstname='Guido')
. That could be done using module level functions of course...
For Intellij go to View > Tool Windows > Gradle > Refresh All Projects (the blue circular arrows at the top of the Gradle window.
i found i had to do something akin to
=(countifs (A1:A196,"yes", j1:j196, "agree") + (countifs (A1:A196,"no", j1:j196, "agree"))
#use chrome webdriver
driver = webdriver.Chrome('path to /chromedriver')
driver.set_window_size(1400,1000)
Jenkins export jobs to a directory
#! /bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
declare -i j=0
for i in $(java -jar jenkins-cli.jar -s http://server:8080/jenkins list-jobs --username **** --password ***);
do
let "j++";
echo $j;
if [ $j -gt 283 ] // If you have more jobs do it in chunks as it will terminate in the middle of the process. So Resume your job from where it ends.
then
java -jar jenkins-cli.jar -s http://lxvbmcbma:8080/jenkins get-job --username **** --password **** ${i} > ${i}.xml;
echo "done";
fi
done
Import jobs
for f in *.xml;
do
echo "Processing ${f%.*} file.."; //truncate the .xml extention and load the xml file for job creation
java -jar jenkins-cli.jar -s http://server:8080/jenkins create-job ${f%.*} < $f
done
Have you tried:
$("#iFrameId").on("load", function () {
// do something once the iframe is loaded
});
Using Java 1.8 you can use Optional
public class Main {
public static void main(String[] args) {
//example call, the methods are just dumb templates, note they are static
FutureMeal meal = getChicken().orElse(getFreeRangeChicken());
//another possible way to call this having static methods is
FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference
//or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
// as nonstatic methods (assume static would be replaced with public for this)
Main m = new Main();
FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference
//or
FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call
}
static Optional<FutureMeal> getChicken(){
//instead of returning null, you would return Optional.empty()
//here I just return it to demonstrate
return Optional.empty();
//if you would return a valid object the following comment would be the code
//FutureMeal ret = new FutureMeal(); //your return object
//return Optional.of(ret);
}
static FutureMeal getFreeRangeChicken(){
return new FutureMeal();
}
}
You would implement a logic for getChicken
to return either Optional.empty()
instead of null, or Optional.of(myReturnObject)
, where myReturnObject
is your chicken
.
Then you can call getChicken()
and if it would return Optional.empty()
the orElse(fallback)
would give you whatever the fallback would be, in your case the second method.
[Update]
Matt Johnsons answer is much better than this one was.
new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()
Based on the work of Denis Nek, it works well if the sum of item's widths is smaller than the size of the container. other than that, it will make the recyclerview non scrollable and only will show subset of the data.
to solve this problem, i modified the solution alittle so that it choose the min of the provided size and calculated size. see below:
package com.linkdev.gafi.adapters;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.linkdev.gafi.R;
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
this.c = context;
}
private Context c;
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
int widthDesired = Math.min(widthSize,width);
setMeasuredDimension(widthDesired, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}}
Median Finding
This is the simplest method to find the median of an attribute.
Select round(S.salary,4) median from employee S where (select count(salary) from station where salary < S.salary ) = (select count(salary) from station where salary > S.salary)
Saving a Keras model:
model = ... # Get model (Sequential, Functional Model, or Model subclass)
model.save('path/to/location')
Loading the model back:
from tensorflow import keras
model = keras.models.load_model('path/to/location')
For more information, read Documentation
Now in rails 5 yu can do:
rails restart
This print by rails --tasks
Restart app by touching tmp/restart.txt
I think that is usefully if you run rails as a demon
You have a TH floating at the top of your table which isn't within a TR. Fix that.
With regards to your image problem you;re referencing the image absolutely from your computer's hard drive. Don't do that.
You also have a closing tag which shouldn't be there.
It should be:
<img src="h.gif" alt="" border="3" height="100" width="100" />
Also this:
<table border = 5 bordercolor = red align = center>
Your colspans are also messed up. You only seem to have three columns but have colspans of 14 and 4 in your code.
Should be:
<table border="5" bordercolor="red" align="center">
Also you have no DOCTYPE declared. You should at least add:
<!DOCTYPE html>
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
brew switch openssl 1.0.2t
catalina this is ok.
You can use:
sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>
Example:
sed -i -e 's/Hello/Bye/' file.txt
This works flawless in Mac.
// Bind combobox to dictionary
Dictionary<string, string>test = new Dictionary<string, string>();
test.Add("1", "dfdfdf");
test.Add("2", "dfdfdf");
test.Add("3", "dfdfdf");
comboBox1.DataSource = new BindingSource(test, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
// Get combobox selection (in handler)
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;
SQL> SELECT JOB,COUNT(JOB) FROM EMP GROUP BY JOB;
JOB COUNT(JOB)
--------- ----------
ANALYST 2
CLERK 4
MANAGER 3
PRESIDENT 1
SALESMAN 4
If pip install mysqlclient produces an error and you use Ubuntu, try:
sudo apt-get install -y python-dev libmysqlclient-dev && sudo pip install mysqlclient
To show $message in your input:
<?php
if(isset($_POST['insert'])){
$message= "The insert function is called.";
}
if(isset($_POST['select'])){
$message="The select function is called.";
}
?>
<form method="post">
<input type="text" name="txt" value="<?php if(isset($message)){ echo $message;}?>" >
<input type="submit" name="insert" value="insert">
<input type="submit" name="select" value="select" >
</form>
To use functioncalling.php as an external file you have to include it somehow in your HTML document.
You have several options:
string[] items = { "Item1", "Item2", "Item3", "Item4" };
string[] items = new string[]
{
"Item1", "Item2", "Item3", "Item4"
};
string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...
Some people, like me, will benefit from using the :focus-within
pseudo-class.
Using it will apply the css you want to a div, for instance.
You can read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within
This answer is not the direct answer for the question. But it should help you figure out which solution fits best for your problem.
When analysing the problem you should activate the debug option -vv
Then rsync will output which files are included or excluded by which pattern:
building file list ...
[sender] hiding file FILE1 because of pattern FILE1*
[sender] showing file FILE2 because of pattern *
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])
x*y
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit x*y
1000000 loops, best of 3: 421 ns per loop
np.multiply(x,y)
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop
Both np.multiply
and *
would yield element wise multiplication known as the Hadamard Product
%timeit
is ipython magic
I don't know if it would work, but maybe you could break the page into columns using the multicol package.
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}[Your list here]
\end{multicols}
In php 5.2 you can use:
<? $d = date_create();
print date_create($d->format('Y-m-1'))->format('Y-m-d') ?>
See answer here: How to control web page caching, across all browsers?
The list is just examples of different techniques, it's not for direct insertion. If copied, the second would overwrite the first and the fourth would overwrite the third because of the http-equiv declarations AND fail with the W3C validator. At most, one could have one of each http-equiv declarations; pragma, cache-control and expires. These are completely outdated when using modern up to date browsers. After IE9 anyway. Chrome and Firefox specifically does not work with these as you would expect, if at all.
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
Caching headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.
This is for them who has two different pem file and for any security purpose want to discard one of the two. Let's say we want to discard 1.pem
This worked like charm:
pip3 install git+https://github.com/deepak1725/fabric8-analytics-worker.git@develop
Where :
develop: Branch
fabric8-analytics-worker.git : Repo
deepak1725: user
Here is a modified version of the chosen answer:
getMonth("Feb")
function getMonth(month) {
d = new Date().toString().split(" ")
d[1] = month
d = new Date(d.join(' ')).getMonth()+1
if(!isNaN(d)) {
return d
}
return -1;
}
Same as jkp's answer, but here's the full command:
git reset --hard a0d3fe6
where a0d3fe6 is found by doing
git reflog
and looking at the point at which you want to undo to.
To the great answers that already included here I want to add something that missing in my perspective - an illustration.
As you already JVM divides the allocated memory to a Java program into two parts. one is stack and another one is heap. Stack is used for execution purpose and heap is used for storage purpose. In that heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called string constants pool.
So for example, if you init the following objects:
String s1 = "abc";
String s2 = "123";
String obj1 = new String("abc");
String obj2 = new String("def");
String obj3 = new String("456);
String literals s1
and s2
will go to string constant pool, objects obj1, obj2, obj3 to the heap. All of them, will be referenced from the Stack.
Also, please note that "abc" will appear in heap and in string constant pool. Why is String s1 = "abc"
and String obj1 = new String("abc")
will be created this way? It's because String obj1 = new String("abc")
explicitly creates a new and referentially distinct instance of a String object and String s1 = "abc"
may reuse an instance from the string constant pool if one is available. For a more elaborate explanation: https://stackoverflow.com/a/3298542/2811258
The synchronized
keyword prevents concurrent access to a block of code or object by multiple threads. All the methods of Hashtable
are synchronized
, so only one thread can execute any of them at a time.
When using non-synchronized
constructs like HashMap
, you must build thread-safety features in your code to prevent consistency errors.
Eagerly evaluated (2.x range
):
[x * .5 for x in range(10)]
Lazily evaluated (2.x xrange
, 3.x range
):
itertools.imap(lambda x: x * .5, xrange(10)) # or range(10) as appropriate
Alternately:
itertools.islice(itertools.imap(lambda x: x * .5, itertools.count()), 10)
# without applying the `islice`, we get an infinite stream of half-integers.
Since you are providing a relative pathway to the image, the image location is looked for from the location in which you have the css file. So if you have the image in a different location to the css file you could either try giving the absolute URL(pathway starting from the root folder) or give the relative file location path. In your case since img and css are in the folder assets to move from location of css file to the img file, you can use '..' operator to refer that the browser has to move 1 folder back and then follow the pathway you have after the '..' operator. This is basically how relative pathway works and you can use it to access resoures in different folders. Hope it helps.
Something like this?:
INSERT INTO destTable
SELECT s.* FROM srcTable s
LEFT JOIN destTable d ON d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...
WHERE d.Key1 IS NULL
print(df.to_csv(sep='\t', index=False))
Or possibly:
print(df.to_csv(columns=['A', 'B', 'C'], sep='\t', index=False))
AtomicBoolean
has methods that perform their compound operations atomically and without having to use a synchronized
block. On the other hand, volatile boolean
can only perform compound operations if done so within a synchronized
block.
The memory effects of reading/writing to volatile boolean
are identical to the get
and set
methods of AtomicBoolean
respectively.
For example the compareAndSet
method will atomically perform the following (without a synchronized
block):
if (value == expectedValue) {
value = newValue;
return true;
} else {
return false;
}
Hence, the compareAndSet
method will let you write code that is guaranteed to execute only once, even when called from multiple threads. For example:
final AtomicBoolean isJobDone = new AtomicBoolean(false);
...
if (isJobDone.compareAndSet(false, true)) {
listener.notifyJobDone();
}
Is guaranteed to only notify the listener once (assuming no other thread sets the AtomicBoolean
back to false
again after it being set to true
).
If you don't want to use Regex then another option is to use
char.IsLetterOrDigit
You can use this to loop through each char of the string and only return if true.
Example for Spring Boot. My WSDL-file is in Resources in "wsdl" folder. The path to the WSDL-file is:
resources/wsdl/WebServiceFile.wsdl
To get the path from some method to this file you can do the following:
String pathToWsdl = this.getClass().getClassLoader().
getResource("wsdl\\WebServiceFile.wsdl").toString();
open Developer command prompt as Admin and navigate to
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Now use path where is your .exe
there
InstallUtil "D:\backup\WindowsService\WindowsService1\WindowsService1\obj\Debug\TestService.exe"
You should definitely avoid using <jsp:...>
tags. They're relics from the past and should always be avoided now.
Use the JSTL.
Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a
public SomeType getQuestionPaperID() {
//...
}
method in your bean.
Once you have that, you can display the value of this property using this code :
<c:out value="${Questions.questionPaperID}" />
or, to specifically target the session scoped attributes (in case of conflicts between scopes) :
<c:out value="${sessionScope.Questions.questionPaperID}" />
Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.
Scanner.hasNextXXX
methodsjava.util.Scanner
has many hasNextXXX
methods that can be used to validate input. Here's a brief overview of all of them:
hasNext()
- does it have any token at all?hasNextLine()
- does it have another line of input?hasNextInt()
- does it have a token that can be parsed into an int
?hasNextDouble()
, hasNextFloat()
, hasNextByte()
, hasNextShort()
, hasNextLong()
, and hasNextBoolean()
hasNextBigInteger()
and hasNextBigDecimal()
hasNext(String pattern)
hasNext(Pattern pattern)
is the Pattern.compile
overloadScanner
is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern)
, which lets you define what pattern separates your tokens. There are also find
and skip
methods that ignores delimiters.
The following discussion will keep the regex as simple as possible, so the focus remains on Scanner
.
Here's a simple example of using hasNextInt()
to validate positive int
from the input.
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
Here's an example session:
Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5
Note how much easier Scanner.hasNextInt()
is to use compared to the more verbose try/catch
Integer.parseInt
/NumberFormatException
combo. By contract, a Scanner
guarantees that if it hasNextInt()
, then nextInt()
will peacefully give you that int
, and will not throw any NumberFormatException
/InputMismatchException
/NoSuchElementException
.
hasNextXXX
on the same tokenNote that the snippet above contains a sc.next()
statement to advance the Scanner
until it hasNextInt()
. It's important to realize that none of the hasNextXXX
methods advance the Scanner
past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!
This has two consequences:
hasNextXXX
test, then you need to advance the Scanner
one way or another (e.g. next()
, nextLine()
, skip
, etc).hasNextXXX
test fails, you can still test if it perhaps hasNextYYY
!Here's an example of performing multiple hasNextXXX
tests.
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
System.out.println(
sc.hasNextInt() ? "(int) " + sc.nextInt() :
sc.hasNextLong() ? "(long) " + sc.nextLong() :
sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
"(String) " + sc.next()
);
}
Here's an example session:
5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit
Note that the order of the tests matters. If a Scanner
hasNextInt()
, then it also hasNextLong()
, but it's not necessarily true
the other way around. More often than not you'd want to do the more specific test before the more general test.
Scanner
has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);
Here's an example session:
Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e
In regex, as a Java string literal, the pattern "[aeiou]"
is what is called a "character class"; it matches any of the letters a
, e
, i
, o
, u
. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner
.
hasNext(String pattern)
- Returns true
if the next token matches the pattern constructed from the specified string.java.util.regex.Pattern
Scanner
at onceSometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner
, where the second Scanner
takes the nextLine()
from the first Scanner
as input. Here's an example:
Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
Scanner lineSc = new Scanner(sc.nextLine());
int sum = 0;
while (lineSc.hasNextInt()) {
sum += lineSc.nextInt();
}
System.out.println("Sum is " + sum);
}
Here's an example session:
Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit
In addition to Scanner(String)
constructor, there's also Scanner(java.io.File)
among others.
Scanner
provides a rich set of features, such as hasNextXXX
methods for validation.hasNextXXX/nextXXX
in combination means that a Scanner
will NEVER throw an InputMismatchException
/NoSuchElementException
.hasNextXXX
does not advance the Scanner
past any input.Scanner
if necessary. Two simple Scanner
is often better than one overly complex Scanner
.Scanner
method that takes a String pattern
argument is regex-based.
String
into a literal pattern is to Pattern.quote
it.From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.
you can write the function in a separate file (say common-functions.php) and include it wherever needed.
function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}
You can include common-functions.php in another file as below.
include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);
You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.
One neat trick to disable margin collapsing that has no visual impact, as far as I know, is setting the padding of the parent to 0.05px
:
.parentClass {
padding: 0.05px;
}
The padding is no longer 0 so collapsing won't occur anymore but at the same time the padding is small enough that visually it will round down to 0.
If some other padding is desired, then apply padding only to the "direction" in which margin collapsing is not desired, for example padding-top: 0.05px;
.
Working example:
.noCollapse {_x000D_
padding: 0.05px;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
background-color: red;_x000D_
width: 150px;_x000D_
}_x000D_
_x000D_
.children {_x000D_
margin-top: 50px;_x000D_
_x000D_
background-color: lime; _x000D_
width: 100px;_x000D_
height: 100px;_x000D_
}
_x000D_
<h3>Border collapsing</h3>_x000D_
<div class="parent">_x000D_
<div class="children">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h3>No border collapsing</h3>_x000D_
<div class="parent noCollapse">_x000D_
<div class="children">_x000D_
</div>_x000D_
</div>
_x000D_
Edit: changed the value from 0.1
to 0.05
. As Chris Morgan mentioned in a comment bellow, and from this small test, it seems that indeed Firefox takes the 0.1px
padding into consideration. Though, 0.05px
seemes to do the trick.
On Ubuntu or Debian, when installed through apt-get
/dpkg
:
$ sudo /etc/init.d/jenkins restart
Usage: /etc/init.d/jenkins {start|stop|status|restart|force-reload}
Try:
$("#myTable").append("<tr><%= escape_javascript( render :partial => name_of_partial ) %></tr>");
And in the partial
, you should have:
<td>row1</td>
<td>row2</td>
I solved my problem with this code
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
onConfigurationChanged(conf);
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
iv.setImageDrawable(getResources().getDrawable(R.drawable.keyboard));
greet.setText(R.string.greet);
textView1.setText(R.string.langselection);
super.onConfigurationChanged(newConfig);
}
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end