You need to call tf.global_variables_initializer()
on you session, like
init = tf.global_variables_initializer()
sess.run(init)
Full example is available in this great tutorial https://www.tensorflow.org/get_started/mnist/mechanics
To revert a revert in GIT:
git revert <commit-hash-of-previous-revert>
This is significantly faster than the EXISTS
way:
SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
(SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)
![Clear Cache] Ctrl+Shift+Delete
http://i.stack.imgur.com/QpqhJ.jpg
Sometimes it’s necessary to do a hard refresh to see the updates take effect. But it’s unlikely that average web users know what a hard refresh is, nor can you expect them to keep refreshing the page until things straighten out.
Here’s one way to do it:<link rel="stylesheet" href="style.css?v=1.1">
If you want it outside of loop then use the below code.
<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id );
echo $display_name;
?>
Please go to this quick example I've created jsFiddle. Hopefull it's easy to understand. You can use a wrapper
div with the width of the site to center align. The reason you must put width
is that so browser knows you are not going for a liquid layout.
Every derived table (AKA sub-query) must indeed have an alias. I.e. each query in brackets must be given an alias (AS whatever
), which can the be used to refer to it in the rest of the outer query.
SELECT ID FROM (
SELECT ID, msisdn FROM (
SELECT * FROM TT2
) AS T
) AS T
In your case, of course, the entire query could be replaced with:
SELECT ID FROM TT2
You don't have to use hidden field. Use "title" property. It will show browser default tooltip. You can then use jQuery plugin (like before mentioned bootstrap tooltip) to show custom formatted tooltip.
<label for="male" title="Hello This Will Have Some Value">Hello ...</label>
Hint: you can also use css to trim text, that does not fit into the box (text-overflow property). See http://jsfiddle.net/8eeHs/
There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
Use the Date
object provided by javascript. It's not unique or special to Google's scripting environment.
asp.net mvc ActionLink new tab with angular parameter
<a target="_blank" class="btn" data-ng-href="@Url.Action("RunReport", "Performance")?hotelCode={{hotel.code}}">Select Room</a>
While the OP is the original author of the database, and likely created a simple data model, I had experienced a similar behavior on a more complicated system. In my scenario the main .mdb file was on a network share location with read/write access by the user. The .mdb file referenced tables in another .mdb file in a different network location - where the user did not have proper access.
For others viewing this post to solve similar problems, verify the linked tables path and access.
To verify linked tables...(assuming Access 2010)
Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.
Associative Array
var a = new Array(1,2,3);
a['key'] = 'experiment';
Array.isArray(a);
returns true
Keep in mind that a.length
will be undefined, because length
is treated as a key, you should use Object.keys(a).length
to get the length of an Associative Array.
Object
var a = {1:1, 2:2, 3:3,'key':'experiment'};
Array.isArray(a)
returns false
JSON returns an Object ... could return an Associative Array ... but it is not like that
You can use the following regex globally:
\[(.*?)\]
Explanation:
\[
: [
is a meta char and needs to be escaped if you want to match it literally.(.*?)
: match everything in a non-greedy way and capture it.\]
: ]
is a meta char and needs to be escaped if you want to match it literally.Add this line in style of v21 if you use two style.
<item name="android:statusBarColor">#43434f</item>
You may not be able to do it with @ResponseBody, but something like this should work:
package xxx;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class FooBar {
@RequestMapping(value="foo/bar", method = RequestMethod.GET)
public void fooBar(HttpServletResponse response) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(myService.getJson().getBytes());
response.setContentType("application/json");
response.setContentLength(out.size());
response.getOutputStream().write(out.toByteArray());
response.getOutputStream().flush();
}
}
If you want to only pass certain arguments, you can do so like this:
Foo.bar(TheClass, 'theMethod', 'arg1', 'arg2')
Foo.js
bar (obj, method, ...args) {
obj[method](...args)
}
obj
and method
are used by the bar()
method, while the rest of args are passed to the actual call.
Try to set date.timezone
in php.ini
file. Or you can manually set it using ini_set()
or date_default_timezone_set()
.
I appreciate all the answers above. However, like some answers and comments pointed out, the axes_grid1
module cannot address GeoAxes, whereas adjusting fraction
, pad
, shrink
, and other similar parameters cannot necessarily give the very precise order, which really bothers me. I believe that giving the colorbar
its own axes
might be a better solution to address all the issues that have been mentioned.
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax = plt.axes()
im = ax.imshow(np.arange(100).reshape((10,10)))
# Create an axes for colorbar. The position of the axes is calculated based on the position of ax.
# You can change 0.01 to adjust the distance between the main image and the colorbar.
# You can change 0.02 to adjust the width of the colorbar.
# This practice is universal for both subplots and GeoAxes.
cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
plt.colorbar(im, cax=cax) # Similar to fig.colorbar(im, cax = cax)
Later on, I find matplotlib.pyplot.colorbar
official documentation also gives ax
option, which are existing axes that will provide room for the colorbar. Therefore, it is useful for multiple subplots, see following.
fig, ax = plt.subplots(2,1,figsize=(12,8)) # Caution, figsize will also influence positions.
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
fig.colorbar(im1, ax=ax)
Again, you can also achieve similar effects by specifying cax, a more accurate way from my perspective.
fig, ax = plt.subplots(2,1,figsize=(12,8))
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
cax = fig.add_axes([ax[1].get_position().x1-0.25,ax[1].get_position().y0,0.02,ax[0].get_position().y1-ax[1].get_position().y0])
fig.colorbar(im1, cax=cax)
The URL parameters are available in request.args
, which is an ImmutableMultiDict that has a get
method, with optional parameters for default value (default
) and type (type
) - which is a callable that converts the input value to the desired format. (See the documentation of the method for more details.)
from flask import request
@app.route('/my-route')
def my_route():
page = request.args.get('page', default = 1, type = int)
filter = request.args.get('filter', default = '*', type = str)
Examples with the code above:
/my-route?page=34 -> page: 34 filter: '*'
/my-route -> page: 1 filter: '*'
/my-route?page=10&filter=test -> page: 10 filter: 'test'
/my-route?page=10&filter=10 -> page: 10 filter: '10'
/my-route?page=*&filter=* -> page: 1 filter: '*'
You can escape it like this.
/\//ig; // Matches /
or just use indexOf
if(str.indexOf("/") > -1)
I know this topic is old, but there are no correct answers.
rotation transform rotates the element from its center, so, a wider element will rotate this way:
Applying overflow: hidden
hides the longest dimension as you can see here:
img{_x000D_
border: 1px solid #000;_x000D_
transform: rotate(270deg);_x000D_
-ms-transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg);_x000D_
-webkit-transform: rotate(270deg);_x000D_
-o-transform: rotate(270deg);_x000D_
}_x000D_
.imagetest{_x000D_
overflow: hidden_x000D_
}
_x000D_
<article>_x000D_
<section class="photo">_x000D_
<div></div>_x000D_
<div class="imagetest">_x000D_
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqVNRUwpfOwZ5n4kvVXea2VHd6QZGACVVaBOl5aJ2EGSG-WAIF" width=100%/>_x000D_
</div>_x000D_
</section>_x000D_
</article>
_x000D_
So, what I do is some calculations, in my example the picture is 455px width and 111px height and we have to add some margins based on these dimensions:
in CSS:
margin: calc((455px - 111px)/2) calc((111px - 455px)/2);
Result:
img{_x000D_
border: 1px solid #000;_x000D_
transform: rotate(270deg);_x000D_
-ms-transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg);_x000D_
-webkit-transform: rotate(270deg);_x000D_
-o-transform: rotate(270deg);_x000D_
/* 455 * 111 */_x000D_
margin: calc((455px - 111px)/2) calc((111px - 455px)/2);_x000D_
}
_x000D_
<article>_x000D_
<section class="photo">_x000D_
<div></div>_x000D_
<div class="imagetest">_x000D_
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqVNRUwpfOwZ5n4kvVXea2VHd6QZGACVVaBOl5aJ2EGSG-WAIF" />_x000D_
</div>_x000D_
</section>_x000D_
</article>
_x000D_
I hope it helps someone!
func getAPICalling(mainUrl:String) {
//create URL
guard let url = URL(string: mainUrl) else {
print("Error: cannot create URL")
return
}
//create request
let urlRequest = URLRequest(url: url)
// create the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET")
print(error!.localizedDescription)
return
}
// make sure we got data
guard let responseData = data else {
print("error: did not receive data")
return
}
// convert Data in JSON && parse the result as JSON, since that's what the API provides
do {
guard let object = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
//JSON Response
guard let todoTitle = object["response"] as? NSDictionary else {
print("Could not get todo title from JSON")
return
}
//Get array in response
let responseList = todoTitle.value(forKey: "radioList") as! NSArray
for item in responseList {
let dic = item as! NSDictionary
let str = dic.value(forKey: "radio_des") as! String
self.arrName.append(str)
print(item)
}
DispatchQueue.main.async {
self.tblView.reloadData()
}
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
Usage:
getAPICalling(mainUrl:"https://dousic.com/api/radiolist?user_id=16")
To print off_t
:
printf("%jd\n", (intmax_t)x);
To print size_t
:
printf("%zu\n", x);
To print ssize_t
:
printf("%zd\n", x);
See 7.19.6.1/7 in the C99 standard, or the more convenient POSIX documentation of formatting codes:
http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html
If your implementation doesn't support those formatting codes (for example because you're on C89), then you have a bit of a problem since AFAIK there aren't integer types in C89 that have formatting codes and are guaranteed to be as big as these types. So you need to do something implementation-specific.
For example if your compiler has long long
and your standard library supports %lld
, you can confidently expect that will serve in place of intmax_t
. But if it doesn't, you'll have to fall back to long
, which would fail on some other implementations because it's too small.
You can do...
JavaScript (shell):
db.getCollectionNames()
Node.js:
db.listCollections()
Non-JavaScript (shell only):
show collections
The reason I call that non-JavaScript is because:
$ mongo prodmongo/app --eval "show collections"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
2016-10-26T19:34:34.886-0400 E QUERY [thread1] SyntaxError: missing ; before statement @(shell eval):1:5
$ mongo prodmongo/app --eval "db.getCollectionNames()"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
[
"Profiles",
"Unit_Info"
]
If you really want that sweet, sweet show collections
output, you can:
$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
Profiles
Unit_Info
Use max-height:100%; max-width:100%;
for the image inside the div.
Do not use passwords. Use peer authentication instead:
postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb
I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No
You can achieve that effect using a combination of CSS linear-gradient and mix-blend-mode.
HTML
<p>
Enter your message here...
To be or not to be,
that is the question...
maybe, I think,
I'm not sure
wait, you're still reading this?
Type a good message already!
</p>
CSS
p {
width: 300px;
position: relative;
}
p::after {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(45deg, red, orange, yellow, green, blue, purple);
mix-blend-mode: screen;
}
What this does is add a linear gradient on the paragraph's ::after
pseudo-element and make it cover the whole paragraph element. But with mix-blend-mode: screen
, the gradient will only show on parts where there is text.
Here's a jsfiddle to show this at work. Just modify the linear-gradient
values to achieve what you want.
I am using this one with my codes.
Simply add this to your criteria:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
that code will be like the select distinct * from table of the native sql. Hope this one helps.
I just want to add something to these great answers. If your DOM
element ins't loading in time. You can still set the value.
let Ctrl = $('#mySelectElement');
...
Ctrl.attr('value', myValue);
after that most DOM
elements that accept a value attribute should populate correctly.
Place your layout in a ScrollView.
For Python:
ActionChains(driver).key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL).perform();
I just want to fill only 80% of the screen for that I did like this below
DisplayMetrics metrics = getResources().getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.80);
setContentView(R.layout.mylayout);
getWindow().setLayout(screenWidth, LayoutParams.WRAP_CONTENT); //set below the setContentview
it works only when I put the getwindow().setLayout... line below the setContentView(..)
thanks @Matthias
I have not used bundle exec
much, but am setting it up now.
I have had instances where the wrong rake was used and much time wasted tracking down the problem. This helps you avoid that.
Here's how to set up RVM so you can use bundle exec
by default within a specific project directory:
I was in a predicament where I had a signed byte array (sbyte[]
) as input to a Test class and I wanted to replace it with a normal byte array (byte[]
) for simplicity. I arrived here from a Google search but Tom's answer wasn't useful to me.
I wrote a helper method to print out the initializer of a given byte[]
:
public void PrintByteArray(byte[] bytes)
{
var sb = new StringBuilder("new byte[] { ");
foreach (var b in bytes)
{
sb.Append(b + ", ");
}
sb.Append("}");
Console.WriteLine(sb.ToString());
}
You can use it like this:
var signedBytes = new sbyte[] { 1, 2, 3, -1, -2, -3, 127, -128, 0, };
var unsignedBytes = UnsignedBytesFromSignedBytes(signedBytes);
PrintByteArray(unsignedBytes);
// output:
// new byte[] { 1, 2, 3, 255, 254, 253, 127, 128, 0, }
The ouput is valid C# which can then just be copied into your code.
And just for completeness, here is the UnsignedBytesFromSignedBytes
method:
// http://stackoverflow.com/a/829994/346561
public static byte[] UnsignedBytesFromSignedBytes(sbyte[] signed)
{
var unsigned = new byte[signed.Length];
Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
return unsigned;
}
Select the column with duplicate values then go to Data Tab, Then Data Tools select remove duplicate select 1) "Continue with the current selection" 2) Click on Remove duplicate.... button 3) Click "Select All" button 4) Click OK
now you get the unique value list.
A simple example for writing multiple data to excel at a time. And also when you want to append data to a sheet on a written excel file (closed excel file).
When it is your first time writing to an excel. (Writing "df1" and "df2" to "1st_sheet" and "2nd_sheet")
import pandas as pd
from openpyxl import load_workbook
df1 = pd.DataFrame([[1],[1]], columns=['a'])
df2 = pd.DataFrame([[2],[2]], columns=['b'])
df3 = pd.DataFrame([[3],[3]], columns=['c'])
excel_dir = "my/excel/dir"
with pd.ExcelWriter(excel_dir, engine='xlsxwriter') as writer:
df1.to_excel(writer, '1st_sheet')
df2.to_excel(writer, '2nd_sheet')
writer.save()
After you close your excel, but you wish to "append" data on the same excel file but another sheet, let's say "df3" to sheet name "3rd_sheet".
book = load_workbook(excel_dir)
with pd.ExcelWriter(excel_dir, engine='openpyxl') as writer:
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
## Your dataframe to append.
df3.to_excel(writer, '3rd_sheet')
writer.save()
Be noted that excel format must not be xls, you may use xlsx one.
for anyone who's using react-moment
:
simply use format
prop to your needed format:
const now = new Date()
<Moment format="DD/MM/YYYY">{now}</Moment>
I don't believe you can do this with an accordion since it's specifically designed preserve the property that at most one item will be opened. However, even though you say you don't want to re-implement accordion, you might be over estimating the complexity involved.
Consider the following scenario where you have a vertical stack of elements,
++++++++++++++++++++
+ Header 1 +
++++++++++++++++++++
+ +
+ Item 1 +
+ +
++++++++++++++++++++
+ Header 2 +
++++++++++++++++++++
+ +
+ Item 2 +
+ +
++++++++++++++++++++
If you're lazy you could build this using a table, otherwise, suitably styled DIVs will also work.
Each of the item blocks can have a class of itemBlock
. Clicking on a header will cause all elements of class itemBlock to be hidden ($(".itemBlock").hide()
). You can then use the jquery slideDown()
function to expand the item below the header. Now you've pretty much implemented accordion.
To expand all items, just use $(".itemBlock").show()
or if you want it animated, $(".itemBlock").slideDown(500)
. To hide all items, just use $(".itemBlock").hide()
.
@Will, git immersion is a really nice and simple git tutorial. it will show you how to undo changes for the following cases: unstaged, staged and committed. labs 14-18
The first option in @Nathan Skerl's list is what was implemented in a project I once worked with, where a similar relationship was established between three tables. (One of them referenced two others, one at a time.)
So, the referencing table had two foreign key columns, and also it had a constraint to guarantee that exactly one table (not both, not neither) was referenced by a single row.
Here's how it could look when applied to your tables:
CREATE TABLE dbo.[Group]
(
ID int NOT NULL CONSTRAINT PK_Group PRIMARY KEY,
Name varchar(50) NOT NULL
);
CREATE TABLE dbo.[User]
(
ID int NOT NULL CONSTRAINT PK_User PRIMARY KEY,
Name varchar(50) NOT NULL
);
CREATE TABLE dbo.Ticket
(
ID int NOT NULL CONSTRAINT PK_Ticket PRIMARY KEY,
OwnerGroup int NULL
CONSTRAINT FK_Ticket_Group FOREIGN KEY REFERENCES dbo.[Group] (ID),
OwnerUser int NULL
CONSTRAINT FK_Ticket_User FOREIGN KEY REFERENCES dbo.[User] (ID),
Subject varchar(50) NULL,
CONSTRAINT CK_Ticket_GroupUser CHECK (
CASE WHEN OwnerGroup IS NULL THEN 0 ELSE 1 END +
CASE WHEN OwnerUser IS NULL THEN 0 ELSE 1 END = 1
)
);
As you can see, the Ticket
table has two columns, OwnerGroup
and OwnerUser
, both of which are nullable foreign keys. (The respective columns in the other two tables are made primary keys accordingly.) The CK_Ticket_GroupUser
check constraint ensures that only one of the two foreign key columns contains a reference (the other being NULL, that's why both have to be nullable).
(The primary key on Ticket.ID
is not necessary for this particular implementation, but it definitely wouldn't harm to have one in a table like this.)
this is the implementation of O(n*lg n) using binary search implementation inside a loop.
#include <iostream>
using namespace std;
bool *inMemory;
int pairSum(int arr[], int n, int k)
{
int count = 0;
if(n==0)
return count;
for (int i = 0; i < n; ++i)
{
int start = 0;
int end = n-1;
while(start <= end)
{
int mid = start + (end-start)/2;
if(i == mid)
break;
else if((arr[i] + arr[mid]) == k && !inMemory[i] && !inMemory[mid])
{
count++;
inMemory[i] = true;
inMemory[mid] = true;
}
else if(arr[i] + arr[mid] >= k)
{
end = mid-1;
}
else
start = mid+1;
}
}
return count;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
inMemory = new bool[10];
for (int i = 0; i < 10; ++i)
{
inMemory[i] = false;
}
cout << pairSum(arr, 10, 11) << endl;
return 0;
}
You can download source fonts from https://github.com/google/fonts
After that use font-ranger
tool to split your large Unicode font into multiple subsets (e.g. latin, cyrillic). You should do the following with the tool:
Font-Ranger: https://www.npmjs.com/package/font-ranger
P.S. You can also automate this using Node.js API
You can also do it using reredirect
(https://github.com/jerome-pouiller/reredirect/).
The command bellow redirects the outputs (standard and error) of the process PID
to FILE
:
reredirect -m FILE PID
The README
of reredirect
also explains other interesting features: how to restore the original state of the process, how to redirect to another command or to redirect only stdout or stderr.
The tool also provides relink
, a script allowing to redirect the outputs to the current terminal:
relink PID
relink PID | grep usefull_content
(reredirect
seems to have same features than Dupx described in another answer but, it does not depend on Gdb).
This syntax isn't valid in any version of PostgreSQL:
ALTER SEQUENCE payments_id_seq LASTVALUE 22
This would work:
ALTER SEQUENCE payments_id_seq RESTART WITH 22;
And is equivalent to:
SELECT setval('payments_id_seq', 22, FALSE);
More in the current manual for ALTER SEQUENCE
and sequence functions.
Note that setval()
expects either (regclass, bigint)
or (regclass, bigint, boolean)
. In the above example I am providing untyped literals. That works too. But if you feed typed variables to the function you may need explicit type casts to satisfy function type resolution. Like:
SELECT setval(my_text_variable::regclass, my_other_variable::bigint, FALSE);
For repeated operations you might be interested in:
ALTER SEQUENCE payments_id_seq START WITH 22; -- set default
ALTER SEQUENCE payments_id_seq RESTART; -- without value
START [WITH]
stores a default RESTART
number, which is used for subsequent RESTART
calls without value. You need Postgres 8.4 or later for the last part.
An alternative method to using upgrade
from the default CPAN shell is to use cpanminus
and cpan-outdated
.
These are so easy and nimble to use that I hardly ever go back to CPAN shell. To upgrade all of your modules in one go, the command is:
cpan-outdated -p | cpanm
I recommend you install cpanminus
like the docs describe:
curl -L https://cpanmin.us | perl - App::cpanminus
And then install cpan-outdated
along with all other CPAN modules using cpanm
:
cpanm App::cpanoutdated
BTW: If you are using perlbrew
then you will need to repeat this for every Perl you have installed under it.
You can find out more about cpanminus
and cpan-outdated
at the Github repos here:
You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(
If you don't wrap the text node in a <span>
like @Jacob suggests, you could instead give the surrounding element padding
as opposed to margin
:
<p id="theParagraph">The text node!</p>
p#theParagraph
{
border: 1px solid red;
padding-bottom: 10px;
}
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">
How about
# pattern is by finding a set of numbers in the start and capturing them
as.numeric(gsub("([0-9]+).*$", "\\1", years))
or
# pattern is to just remove _years_old
as.numeric(gsub(" years old", "", years))
or
# split by space, get the element in first index
as.numeric(sapply(strsplit(years, " "), "[[", 1))
First of all you should create property with employee details in the Employee
class:
public class Employee
{
public Employee()
{
EmployeeDetails = new EmployeeDetails();
EmployeeDetails.EmpID = 123;
EmployeeDetails.EmpName = "ABC";
}
public EmployeeDetails EmployeeDetails { get; set; }
}
If you don't do that, you will create instance of object in Employee
constructor and you lose reference to it.
In the XAML you should create instance of Employee
class, and after that you can assign it to DataContext
.
Your XAML should look like this:
<Window x:Class="SampleApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:SampleApplication"
>
<Window.Resources>
<local:Employee x:Key="Employee" />
</Window.Resources>
<Grid DataContext="{StaticResource Employee}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
<Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
<TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
<TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
</Grid>
</Window>
Now, after you created property with employee details you should binding by using this property:
Text="{Binding EmployeeDetails.EmpID}"
String withoutQuotes_line1 = line1.replace("\"", "");
have a look here
#bg, #search-bg {_x000D_
background-image: url('https://images.pexels.com/photos/719609/pexels-photo-719609.jpeg?w=940&h=650&auto=compress&cs=tinysrgb');_x000D_
background-repeat: no-repeat;_x000D_
background-size: 1080px auto;_x000D_
}_x000D_
_x000D_
#bg {_x000D_
background-position: center top;_x000D_
padding: 70px 90px 120px 90px;_x000D_
}_x000D_
_x000D_
#search-container {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#search-bg {_x000D_
/* Absolutely position it, but stretch it to all four corners, then put it just behind #search's z-index */_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
bottom: 0px;_x000D_
left: 0px;_x000D_
z-index: 99;_x000D_
_x000D_
/* Pull the background 70px higher to the same place as #bg's */_x000D_
background-position: center -70px;_x000D_
_x000D_
-webkit-filter: blur(10px);_x000D_
filter: url('/media/blur.svg#blur');_x000D_
filter: blur(10px);_x000D_
}_x000D_
_x000D_
#search {_x000D_
/* Put this on top of the blurred layer */_x000D_
position: relative;_x000D_
z-index: 100;_x000D_
padding: 20px;_x000D_
background: rgb(34,34,34); /* for IE */_x000D_
background: rgba(34,34,34,0.75);_x000D_
}_x000D_
_x000D_
@media (max-width: 600px ) {_x000D_
#bg { padding: 10px; }_x000D_
#search-bg { background-position: center -10px; }_x000D_
}_x000D_
_x000D_
#search h2, #search h5, #search h5 a { text-align: center; color: #fefefe; font-weight: normal; }_x000D_
#search h2 { margin-bottom: 50px }_x000D_
#search h5 { margin-top: 70px }
_x000D_
<div id="bg">_x000D_
<div id="search-container">_x000D_
<div id="search-bg"></div>_x000D_
<div id="search">_x000D_
<h2>Awesome</h2>_x000D_
<h5><a href="#">How it works »</a></h5>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
in the "Ouput Window". you can usually do CTRL-ALT-O to make it visible. Or through menus using View->Output.
There's this approach:
[getattr(obj, m) for m in dir(obj) if not m.startswith('__')]
When dealing with a class instance, perhaps it'd be better to return a list with the method references instead of just names¹. If that's your goal, as well as
import
__init__
) from the listIt may be of use. You might also want to assure it's callable(getattr(obj, m))
, since dir
returns all attributes within obj
, not just methods.
In a nutshell, for a class like
class Ghost:
def boo(self, who):
return f'Who you gonna call? {who}'
We could check instance retrieval with
>>> g = Ghost()
>>> methods = [getattr(g, m) for m in dir(g) if not m.startswith('__')]
>>> print(methods)
[<bound method Ghost.boo of <__main__.Ghost object at ...>>]
So you can call it right away:
>>> for method in methods:
... print(method('GHOSTBUSTERS'))
...
Who you gonna call? GHOSTBUSTERS
¹ An use case:
I used this for unit testing. Had a class where all methods performed variations of the same process - which led to lengthy tests, each only a tweak away from the others. DRY was a far away dream.
Thought I should have a single test for all methods, so I made the above iteration.
Although I realized I should instead refactor the code itself to be DRY-compliant anyway... this may still serve a random nitpicky soul in the future.
Just use the modulus
loop through the list and run the following on each item
if(num % 2 == 0)
{
//is even
}
else
{
//is odd
}
Alternatively if you want to know if all are even you can do something like this:
bool allAreEven = lst.All(x => x % 2 == 0);
If you are using Rails 5 and above, the following solution will work.
#delete based on id
user_id = 50
User.find(id: user_id).delete_all
#delete based on condition
threshold_age = 20
User.where(age: threshold_age).delete_all
https://www.rubydoc.info/docs/rails/ActiveRecord%2FNullRelation:delete_all
A regex that does exactly what the standards say is allowed, according to what I've seen about them, is this:
/^(?!(^[.-].*|.*[.-]@|.*\.{2,}.*)|^.{254}.+@)([a-z\xC0-\xFF0-9!#$%&'*+\/=?^_`{|}~.-]+@)(?!.{253}.+$)((?!-.*|.*-\.)([a-z0-9-]{1,63}\.)+[a-z]{2,63}|(([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\.){3}([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9]))$/gim
Demo / Debuggex analysis (interactive)
Split up:
^(?!(^[.-].*|.*[.-]@|.*\.{2,}.*)|^.{254}.+@)
([a-z\xC0-\xFF0-9!#$%&'*+\/=?^_`{|}~.-]+@)
(?!.{253}.+$)
(
(?!-.*|.*-\.)
([a-z0-9-]{1,63}\.)+
[a-z]{2,63}
|
(([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\.){3}
([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])
)$
Analysis:
(?!(^[.-].*|.*[.-]@|.*\.{2,}.*)|^.{254}.+@)
Negative lookahead for either an address starting with a .
, ending with one, having ..
in it, or exceeding the 254 character max length
([a-z\xC0-\xFF0-9!#$%&'*+\/=?^_`{|}~.-]+@)
matching 1 or more of the permitted characters, with the negative look applying to it
(?!.{253}.+$)
Negative lookahead for the domain name part, restricting it to 253 characters in total
(?!-.*|.*-\.)
Negative lookahead for each of the domain names, which are don't allow starting or ending with .
([a-z0-9-]{1,63}\.)+
simple group match for the allowed characters in a domain name, which are limited to 63 characters each
[a-zA-Z]{2,63}
simple group match for the allowed top-level domain, which currently still is restricted to letters only, but does include >4 letter TLDs.
(([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])\.){3}
([01]?[0-9]{2}|2([0-4][0-9]|5[0-5])|[0-9])
the alternative for domain names: this matches the first 3 numbers in an IP address with a .
behind it, and then the fourth number in the IP address without .
behind it.
I had an application that I needed to convert from a JPA entity to DTO, and I thought about it and finally came up using org.springframework.beans.BeanUtils.copyProperties
for copying simple properties and also extending and using org.springframework.binding.convert.service.DefaultConversionService
for converting complex properties.
In detail my service was something like this:
@Service("seedingConverterService")
public class SeedingConverterService extends DefaultConversionService implements ISeedingConverterService {
@PostConstruct
public void init(){
Converter<Feature,FeatureDTO> featureConverter = new Converter<Feature, FeatureDTO>() {
@Override
public FeatureDTO convert(Feature f) {
FeatureDTO dto = new FeatureDTO();
//BeanUtils.copyProperties(f, dto,"configurationModel");
BeanUtils.copyProperties(f, dto);
dto.setConfigurationModelId(f.getConfigurationModel()==null?null:f.getConfigurationModel().getId());
return dto;
}
};
Converter<ConfigurationModel,ConfigurationModelDTO> configurationModelConverter = new Converter<ConfigurationModel,ConfigurationModelDTO>() {
@Override
public ConfigurationModelDTO convert(ConfigurationModel c) {
ConfigurationModelDTO dto = new ConfigurationModelDTO();
//BeanUtils.copyProperties(c, dto, "features");
BeanUtils.copyProperties(c, dto);
dto.setAlgorithmId(c.getAlgorithm()==null?null:c.getAlgorithm().getId());
List<FeatureDTO> l = c.getFeatures().stream().map(f->featureConverter.convert(f)).collect(Collectors.toList());
dto.setFeatures(l);
return dto;
}
};
addConverter(featureConverter);
addConverter(configurationModelConverter);
}
}
Here are some solutions:
https://forums.docker.com/t/how-to-expose-port-on-running-container/3252/12
The solution to mapping port while running the container.
docker run -d --net=host myvnc
that will expose and map the port automatically to your host
You can also use this code in onCreate()
method:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
I have tried this, write your own code for formWindowClosing() event.
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int selectedOption = JOptionPane.showConfirmDialog(null,
"Do you want to exit?",
"FrameToClose",
JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
setVisible(false);
dispose();
} else {
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
}
}
This asks user whether he want to exit the Frame or Application.
Why not call the method that returns default(T) with reflection ? You can use GetDefault of any type with:
public object GetDefault(Type t)
{
return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null);
}
public T GetDefaultGeneric<T>()
{
return default(T);
}
Python slicing notation:
a[start:end:step]
start
and end
, negative values are interpreted as being relative to the end of the sequence.end
indicate the position after the last element to be included.[+0:-0:1]
.start
and end
The notation extends to (numpy) matrices and multidimensional arrays. For example, to slice entire columns you can use:
m[::,0:2:] ## slice the first two columns
Slices hold references, not copies, of the array elements. If you want to make a separate copy an array, you can use deepcopy()
.
CGI essentially passes the request off to any interpreter that is configured with the web server - This could be Perl, Python, PHP, Ruby, C pretty much anything. Perl was the most common back in the day thats why you often see it in reference to CGI.
CGI is not dead. In fact most large hosting companies run PHP as CGI as opposed to mod_php because it offers user level config and some other things while it is slower than mod_php. Ruby and Python are also typically run as CGI. they key difference here is that a server module runs as part of the actual server software - where as with CGI its totally outside the server The server just uses the CGI module to determine how to pass and recieve data to the outside interpreter.
The accepted answer is invalid with the double EXEC (only need the first EXEC):
DECLARE @returnvalue int;
EXEC @returnvalue = SP_SomeProc
PRINT @returnvalue
And you still need to call PRINT (at least in Visual Studio).
This could be useful to others:
Using AccountPicker to get user's email address without any global permissions, and allowing the user to be aware and authorize or cancel the process.
The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.
For example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class DownloadPage {
public static void main(String[] args) throws IOException {
// Make a URL to the web page
URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is =con.getInputStream();
// Once you have the Input Stream, it's just plain old Java IO stuff.
// For this case, since you are interested in getting plain-text web page
// I'll use a reader and output the text content to System.out.
// For binary content, it's better to directly read the bytes from stream and write
// to the target file.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Hope this helps.
I had a button in my layout.xml that was defined as a View as in:
final View myButton = findViewById(R.id.button1);
I was not able to change the text on it until I also defined it as a button:
final View vButton = findViewById(R.id.button1);
final Button bButton = (Button) findViewById(R.id.button1);
When I needed to change the text, I used the bButton.setText("Some Text");
and when I wanted to alter the view, I used the vButton.
Worked great!
SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'
How to run Rmd in command with knitr and rmarkdown by multiple commands and then Upload an HTML file to RPubs
Here is a example: load two libraries and run a R command
R -e 'library("rmarkdown");library("knitr");rmarkdown::render("NormalDevconJuly.Rmd")'
R -e 'library("markdown");rpubsUpload("normalDev","NormalDevconJuly.html")'
@jim's answer is correct -- fuser
is what you want.
Additionally (or alternately), you can use lsof
to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser
can do that with its -k
option. You can have fuser
use other signals with the -s
option -- check the man page for details.)
For example, with a tail -F /etc/passwd
running in one window:
ghoti@pc:~$ lsof | grep passwd
tail 12470 ghoti 3r REG 251,0 2037 51515911 /etc/passwd
Note that you can also use lsof
to find out what processes are using particular sockets. An excellent tool to have in your arsenal.
EASY WAY - Reading a line using line number. Let's say Line number starts from 1 till null .
public class TextFileAssignmentOct {
private void readData(int rowNum, BufferedReader br) throws IOException {
int n=1; //Line number starts from 1
String row;
while((row=br.readLine()) != null) { // Reads every line
if (n == rowNum) { // When Line number matches with which you want to read
System.out.println(row);
}
n++; //This increments Line number
}
}
public static void main(String[] args) throws IOException {
File f = new File("../JavaPractice/FileRead.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
TextFileAssignmentOct txf = new TextFileAssignmentOct();
txf.readData(4, br); //Read a Specific Line using Line number and Passing buffered reader
}
}
Java 11+:
URI uri = URI.create("http://www.google.com");
HttpRequest request = HttpRequest.newBuilder(uri).build();
String content = HttpClient.newHttpClient().send(request, BodyHandlers.ofString()).body();
Sohnee solutions is cleaner, but you can also try
window["bootbox"]
You can add a reference to System.Configuration
in your project and then:
using System.Configuration;
then
string sValue = ConfigurationManager.AppSettings["BatchFile"];
with an app.config
file like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="BatchFile" value="blah.bat" />
</appSettings>
</configuration>
The shortest way to write a selector that accesses that specific div is to simply use
[role=main] {
/* CSS goes here */
}
The previous answers are not wrong, but they rely on you using either a div or using the specific id. With this selector, you'll be able to have all kinds of crazy markup and it would still work and you avoid problems with specificity.
[role=main] {_x000D_
background: rgba(48, 96, 144, 0.2);_x000D_
}_x000D_
div,_x000D_
span {_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div id="content" role="main">_x000D_
<span role="main">Hello</span>_x000D_
</div>
_x000D_
When considering what the computer actually does...
++x: load x from memory, increment, use, store back to memory.
x++: load x from memory, use, increment, store back to memory.
Consider: a = 0 x = f(a++) y = f(++a)
where function f(p) returns p + 1
x will be 1 (or 2)
y will be 2 (or 1)
And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.
Generally, just use x = x + 1. It's way simpler.
As a rather old and rusty C programmer who never quite made it fully to C++ because other things came along and is now hacking along getting to grips with Arduino my view is simple.
#define is a compiler pre processor directive and should be used as such, for conditional compilation etc.. E.g. where low level code needs to define some possible alternative data structures for portability to specif hardware. It can produce inconsistent results depending on the order your modules are compiled and linked. If you need something to be global in scope then define it properly as such.
const and (static const) should always be used to name static values or strings. They are typed and safe and the debugger can work fully with them.
enums have always confused me, so I have managed to avoid them.
To resolve this problem:
That's all.
Using both method you find easy if you wont last seven days you use (currentdaynumber+7-1)%7,(currentdaynumber+7-2)%7.....upto 6
public static String getDayName(int day){
switch(day){
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
}
return "Worng Day";
}
public static String getCurrentDay(){
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.US);
Calendar calendar = Calendar.getInstance();
return dayFormat.format(calendar.getTime());
}
Change the resolution of your operating system running in VMware and hope it will stretch the screen when chosen the correct values
If we do it just like this:
Dim myArr as Variant
myArr = Range("A1:A10")
the new array will be with two dimensions. Which is not always somehow comfortable to work with:
To get away of the two dimensions, when getting a single column to array, we may use the built-in Excel function “Transpose”. With it, the data becomes in one dimension:
If we have the data in a row, a single transpose will not do the job. We need to use the Transpose function twice:
Note: As you see from the screenshots, when generated this way, arrays start with 1, not with 0. Just be a bit careful.
Enable mod_ssl in httpd.conf and restart the apache. You will see the openssl information in error.log as below
[Fri Mar 23 15:13:38.448268 2018] [mpm_worker:notice] [pid 8891:tid 1] AH00292: Apache/2.4.29 (Unix) OpenSSL/1.0.2n configured -- resuming normal operations_x000D_
[Fri Mar 23 15:13:38.448502 2018] [core:notice] [pid 8891:tid 1] AH00094: Command line: '/opt/apps/apache64/2.4.29/bin/httpd'
_x000D_
I am adding my answer, it is just an addon to the above, as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:
var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');
If you're looking to retrieve records within the last 7 days, you can use the snippet below:
SELECT date FROM table_name WHERE DATE(date) >= CURDATE() - INTERVAL 7 DAY;
More answers, along with timings in the answer to this question: What is the most efficient way to cast a list as a data frame?
The quickest way, that doesn't produce a dataframe with lists rather than vectors for columns appears to be (from Martin Morgan's answer):
l <- list(list(col1="a",col2=1),list(col1="b",col2=2))
f = function(x) function(i) unlist(lapply(x, `[[`, i), use.names=FALSE)
as.data.frame(Map(f(l), names(l[[1]])))
Just run graphics.off()
before plotting your data.
This instruction solved my error. So, it's harmless to try it before taking a more complex solution.
This works for large tables:
CREATE Temporary table duplicates AS select max(id) as id, url from links group by url having count(*) > 1;
DELETE l from links l inner join duplicates ld on ld.id = l.id WHERE ld.id IS NOT NULL;
To delete oldest change max(id)
to min(id)
Xml
android:maxLength="10"
Java:
InputFilter[] editFilters = editText.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = new InputFilter.LengthFilter(maxLength);
editText.setFilters(newFilters);
Kotlin:
editText.filters += InputFilter.LengthFilter(maxLength)
There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove
public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
if (empty($associativeArray) || empty($keysToUnset))
return array();
foreach ($associativeArray as $key => $arr) {
if (!is_array($arr)) {
continue;
}
foreach ($keysToUnset as $keyToUnset) {
if (array_key_exists($keyToUnset, $arr)) {
unset($arr[$keyToUnset]);
}
}
$associativeArray[$key] = $arr;
}
return $associativeArray;
}
Call like:
removeKeysFromAssociativeArray($arrValues, $keysToRemove);
This can be done in a much simpler manner now.
$tmpName = $_FILES['csv']['tmp_name'];
$csvAsArray = array_map('str_getcsv', file($tmpName));
This will return you a parsed array of your CSV data. Then you can just loop through it using a foreach statement.
If you're not using SQL Server 2008 (i.e. you only have a DateTime data type), you can use the following (admittedly rough and ready) TSQL to achieve what you want:
DECLARE @DateOnly AS datetime
DECLARE @TimeOnly AS datetime
SET @DateOnly = '07 aug 2009 00:00:00'
SET @TimeOnly = '01 jan 1899 10:11:23'
-- Gives Date Only.
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @DateOnly))
-- Gives Time Only.
SELECT DATEADD(Day, -DATEDIFF(Day, 0, @TimeOnly), @TimeOnly)
-- Concatenates Date and Time parts.
SELECT
CAST(
DATEADD(dd, 0, DATEDIFF(dd, 0, @DateOnly)) + ' ' +
DATEADD(Day, -DATEDIFF(Day, 0, @TimeOnly), @TimeOnly)
as datetime)
It's rough and ready, but it works!
#include <boost/locale.hpp>
namespace lcv = boost::locale::conv;
inline std::wstring fromUTF8(const std::string& s)
{ return lcv::utf_to_utf<wchar_t>(s); }
inline std::string toUTF8(const std::wstring& ws)
{ return lcv::utf_to_utf<char>(ws); }
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
bash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
This should do what you're looking for:
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
Usage:
echo clean('a|"bc!@£de^&$f g');
Will output: abcdef-g
Edit:
Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
This works for me under Specific Page for MVC:
/Home/Index
Update: Currently, I just use a forward slash in the "Specific Page" textbox, and it takes me to the home page as defined in the routing:
/
I don't think the scrollTop is a valid property. If you want to animate scrolling, try the scrollTo plugin for jquery
There's some joking, and misleading comments, even partially incorrect information in the answers here. I'd like to try to improve on them:
First, as some have pointed out, you have a bug in your code that relates to the question:
if ($status = 'clear' AND $pRent == 0)
should be (note the ==
instead of =
in the first part):
if ($status == 'clear' AND $pRent == 0)
which in this case is functionally equivalent to
if ($status == 'clear' && $pRent == 0)
Second, note that these operators (and or && ||
) are short-circuit operators. That means if the answer can be determined with certainty from the first expression, the second one is never evaluated. Again this doesn't matter for your debugged line above, but it is extremely important when you are combining these operators with assignments, because
Third, the real difference between and or
and && ||
is their operator precedence. Specifically the importance is that && ||
have higher precedence than the assignment operators (= += -= *= **= /= .= %= &= |= ^= <<= >>=
) while and or
have lower precendence than the assignment operators. Thus in a statement that combines the use of assignment and logical evaluation it matters which one you choose.
Modified examples from PHP's page on logical operators:
$e = false || true;
will evaluate to true
and assign that value to $e
, because ||
has higher operator precedence than =
, and therefore it essentially evaluates like this:
$e = (false || true);
however
$e = false or true;
will assign false
to $e
(and then perform the or
operation and evaluate true
) because =
has higher operator precedence than or
, essentially evaluating like this:
($e = false) or true;
The fact that this ambiguity even exists makes a lot of programmers just always use && ||
and then everything works clearly as one would expect in a language like C, ie. logical operations first, then assignment.
Some languages like Perl use this kind of construct frequently in a format similar to this:
$connection = database_connect($parameters) or die("Unable to connect to DB.");
This would theoretically assign the database connection to $connection
, or if that failed (and we're assuming here the function would return something that evalues to false
in that case), it will end the script with an error message. Because of short-circuiting, if the database connection succeeds, the die()
is never evaluated.
Some languages that allow for this construct straight out forbid assignments in conditional/logical statements (like Python) to remove the amiguity the other way round.
PHP went with allowing both, so you just have to learn about your two options once and then code how you'd like, but hopefully you'll be consistent one way or another.
Whenever in doubt, just throw in an extra set of parenthesis, which removes all ambiguity. These will always be the same:
$e = (false || true);
$e = (false or true);
Armed with all that knowledge, I prefer using and or
because I feel that it makes the code more readable. I just have a rule not to combine assignments with logical evaluations. But at that point it's just a preference, and consistency matters a lot more here than which side you choose.
You can change any header or anything in Application_EndRequest()
try this
protected void Application_EndRequest()
{
// removing excessive headers. They don't need to see this.
Response.Headers.Remove("header_name");
}
I had the same problem ( I had to sort my equipments by their name ) and i solved like this:
<% @equipments.sort.each do |name, quantity| %>
...
<% end %>
@equipments is a hash that I build on my model and return on my controller. If you call .sort it will sort the hash based on it's key value.
You can use Object.getOwnPropertyNames()
to get all properties that belong to an object, whether enumerable or not. For example:
console.log(Object.getOwnPropertyNames(Math));
//-> ["E", "LN10", "LN2", "LOG2E", "LOG10E", "PI", ...etc ]
You can then use filter()
to obtain only the methods:
console.log(Object.getOwnPropertyNames(Math).filter(function (p) {
return typeof Math[p] === 'function';
}));
//-> ["random", "abs", "acos", "asin", "atan", "ceil", "cos", "exp", ...etc ]
In ES3 browsers (IE 8 and lower), the properties of built-in objects aren't enumerable. Objects like window
and document
aren't built-in, they're defined by the browser and most likely enumerable by design.
From ECMA-262 Edition 3:
Global Object
There is a unique global object (15.1), which is created before control enters any execution context. Initially the global object has the following properties:• Built-in objects such as Math, String, Date, parseInt, etc. These have attributes { DontEnum }.
• Additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself.As control enters execution contexts, and as ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be changed.
I should point out that this means those objects aren't enumerable properties of the Global object. If you look through the rest of the specification document, you will see most of the built-in properties and methods of these objects have the { DontEnum }
attribute set on them.
Update: a fellow SO user, CMS, brought an IE bug regarding { DontEnum }
to my attention.
Instead of checking the DontEnum attribute, [Microsoft] JScript will skip over any property in any object where there is a same-named property in the object's prototype chain that has the attribute DontEnum.
In short, beware when naming your object properties. If there is a built-in prototype property or method with the same name then IE will skip over it when using a for...in
loop.
I just experienced this problem.
The problem was caused by my controller method attempting return type of String (view name) when it exits. When the method would exit, a second response stream would be initiated.
Changing the controller method return type to void resolved the problem.
I hope this helps if anyone else experiences this problem.
ArrayList<String> myArrayList = new ArrayList<String>();
...
String[] myArray = myArrayList.toArray(new String[0]);
Whether it's a "good idea" would really be dependent on your use case.
There are ports of flex and bison for windows here: http://gnuwin32.sourceforge.net/
flex is the free implementation of lex. bison is the free implementation of yacc.
Use a T-SQL IF
:
IF @ABC IS NOT NULL AND @ABC != -1
UPDATE [TABLE_NAME] SET XYZ=@ABC
Take a look at the MSDN docs.
String.prototype.includes
is, as you write, not supported in Internet Explorer (or Opera).
Instead you can use String.prototype.indexOf
. #indexOf
returns the index of the first character of the substring if it is in the string, otherwise it returns -1
. (Much like the Array equivalent)
var myString = 'this is my string';
myString.indexOf('string');
// -> 11
myString.indexOf('hello');
// -> -1
MDN has a polyfill for includes
using indexOf
: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill
EDIT: Opera supports includes
as of version 28.
EDIT 2: Current versions of Edge supports the method. (as of 2019)
If the width of the contents changes, you'll have to use this bit of code to update each column:
private void ResizeGridViewColumn(GridViewColumn column)
{
if (double.IsNaN(column.Width))
{
column.Width = column.ActualWidth;
}
column.Width = double.NaN;
}
You'd have to fire it each time the data for that column updates.
Outside of using pl/pgsql or other pl/* language as suggested, this is the only other possibility I could think of.
begin;
select 5::int as var into temp table myvar;
select *
from somewhere s, myvar v
where s.something = v.var;
commit;
Somebody can explain to me why 'NULL' is not just a string in a comparison instance?
$x = 0;
var_dump($x == 'NULL'); # TRUE !!!WTF!!!
Just remove
<authorization>
<deny users="?"/>
</authorization>
from your web.config file
that did for me
Addition to Mark Byers answer :
Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.
INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367
Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.
The normal way would be the IF statement, though simpler than your example:
=IF(INDEX(a,b,c),INDEX(a,b,c),"")
No need to do gyrations with the formula, since zero values trigger the false condition.
As has been mentioned already, you cannot use the "Back up" and "Restore" features to go from a SQL Server 2012 DB to a SQL Server 2008 DB. A program I wrote, SQL Server Scripter, will however connect to a SQL Server database and script out a database, its schema and data. It can be git cloned from BitBucket, and compiled with Visual Studio 2010 or later (if it's a later version, just open the .csproj
).
First you should use print_r($_FILES)
to debug, and see what it contains. :
your uploads.php
would look like:
//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);
//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];
//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO picture (Filename,Description)
VALUES ('$Filename', '$Description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php
df['MyColumnName'] = df['MyColumnName'].astype('float64')
This is how I solved similar problem:
I hope it can help solve your problem too.
Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.
This worked for me:
<script>
jQuery.noConflict();
// Use jQuery via jQuery() instead of via $()
jQuery(document).ready(function(){
jQuery("div").hide();
});
</script>
Reason: "Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $".
Read full reason here: https://api.jquery.com/jquery.noconflict/
If this solves your issue, it's likely another library is also using $.
I had this issue when I was running migration
Its es5 vs es6 issue
Here is how I solved it
I run
npm install @babel/register
and add
require("@babel/register")
at the top of my .sequelizerc file my
and go ahead to run my sequelize migrate. This is applicable to other things apart from sequelize
babel does the transpiling
On MySQL 5.7 its work for me, I'm using CentOS7.
For taking Dump.
Command :
mysqldump -u user_name -p database_name -R -E > file_name.sql
Exemple :
mysqldump -u root -p mr_sbc_clean -R -E > mr_sbc_clean_dump.sql
For deploying Dump.
Command :
mysql -u user_name -p database_name < file_name.sql
Exemple :
mysql -u root -p mr_sbc_clean_new < mr_sbc_clean_dump.sql
I guess ssh
is the best secured way for this, for example :
ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"
where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.
Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain
if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config
. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.
Some extra docs over the source project main pages :
ssh and ssh-agent
man ssh
http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring
keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/
=AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
=AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
=$A:$H
.Results should be similar to the following.
¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. ""
).
Try applying this style to your div class="input-group"
:
text-align:center;
View it: Fiddle.
You need to load a package (like magrittr
or dplyr
) that defines the function first, then it should work.
install.packages("magrittr") # package installations are only needed the first time you use it
install.packages("dplyr") # alternative installation of the %>%
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr) # alternatively, this also loads %>%
The pipe operator %>%
was introduced to "decrease development time and to improve readability and maintainability of code."
But everybody has to decide for himself if it really fits his workflow and makes things easier.
For more information on magrittr
, click here.
Not using the pipe %>%
, this code would return the same as your code:
words <- colnames(as.matrix(dtm))
words <- words[nchar(words) < 20]
words
EDIT: (I am extending my answer due to a very useful comment that was made by @Molx)
Despite being from
magrittr
, the pipe operator is more commonly used with the packagedplyr
(which requires and loadsmagrittr
), so whenever you see someone using%>%
make sure you shouldn't loaddplyr
instead.
May be I am oversimplifying?
Just add the following code:
Open sFileName For Input as iFileNum
Line Input #iFileNum, dummy1
Line Input #iFileNum, dummy2
........
Sundar
First of all, when your first initial window is loaded, it is cached. Therefore, when creating a new window from the first window, the contents of the new window are not loaded from the server, but are loaded from the cache. Consequently, no onload
event occurs when you create the new window.
However, in this case, an onpageshow
event occurs. It always occurs after the onload
event and even when the page is loaded from cache. Plus, it now supported by all major browsers.
window.popup = window.open($(this).attr('href'), 'Ad', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
$(window.popup).onpageshow = function() {
alert("Popup has loaded a page");
};
The w3school website elaborates more on this:
The onpageshow event is similar to the
onload
event, except that it occurs after the onload event when the page first loads. Also, theonpageshow
event occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache.
Do you have the SSH2 extension available?
Docs: http://www.php.net/manual/en/function.ssh2-exec.php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
I had used following which worked correctly.
$('#fileAttached').attr('value', $('#attachment').val())
ls -i file #output is for me 68551981
debugfs -R 'stat <68551981>' /dev/sda3 # /dev/sda3 is the disk on which the file exists
#results - crtime value
[root@loft9156 ~]# debugfs -R 'stat <68551981>' /dev/sda3
debugfs 1.41.12 (17-May-2010)
Inode: 68551981 Type: regular Mode: 0644 Flags: 0x80000
Generation: 769802755 Version: 0x00000000:00000001
User: 0 Group: 0 Size: 38973440
File ACL: 0 Directory ACL: 0
Links: 1 Blockcount: 76128
Fragment: Address: 0 Number: 0 Size: 0
ctime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
atime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013
mtime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
**crtime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013**
Size of extra inode fields: 28
EXTENTS:
(0-511): 352633728-352634239, (512-1023): 352634368-352634879, (1024-2047): 288392192-288393215, (2048-4095): 355803136-355805183, (4096-6143): 357941248-357943295, (6144
-9514): 357961728-357965098
We have seen this same behavior in the past. It turned out that, for some crazy reason, if a NullPointerException occurred at the same place in the code multiple times, after a while using Log.error(String, Throwable)
would stop including full stack traces.
Try looking further back in your log. You may find the culprit.
EDIT: this bug sounds relevant, but it was fixed so long ago it's probably not the cause.
just cut the string using split (the easy way):
var myString = "http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235"
var mySplitResult = myString.split("?");
alert(mySplitResult[0]);
The solution from the blog Prevent desktop lock or screensaver with PowerShell is working for me. Here is the relevant script, which simply sends a single period to the shell:
param($minutes = 60)
$myshell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
Start-Sleep -Seconds 60
$myshell.sendkeys(".")
}
and an alternative from the comments, which moves the mouse a single pixel:
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + 1) , $Pos.Y)
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) - 1) , $Pos.Y)
Simplest is to class-ify all of the divs:
div.rounded {
background: #CFFEB6 url('tr.gif') no-repeat top right;
}
div.rounded div.br {
background: url('br.gif') no-repeat bottom right;
}
div.rounded div.br div.bl {
background: url('bl.gif') no-repeat bottom left;
}
div.rounded div.br div.bl div.inner {
padding: 10px;
}
.button {
border: 1px solid #999;
background:#eeeeee url('');
text-align:center;
}
.button:hover {
background-color:#c4e2f2;
}
And then use:
<div class='round'><div class='br'><div class='bl'><div class='inner'>
<div class='button'><a href='#'>Test</a></div>
</div></div></div></div>
It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char *
and char []
) are not the same thing.
char a[SIZE]
says that the value at the location of a
is an array of length SIZE
char *a;
says that the value at the location of a
is a pointer to a char
. This can be combined with pointer arithmetic to behave like an array (eg, a[10]
is 10 entries past wherever a
points)In memory, it looks like this (example taken from the FAQ):
char a[] = "hello"; // array
+---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
+---+---+---+---+---+---+
char *p = "world"; // pointer
+-----+ +---+---+---+---+---+---+
p: | *======> | w | o | r | l | d |\0 |
+-----+ +---+---+---+---+---+---+
It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.
One major practical difference is that the compiler knows how long an array is. Using the examples above:
char a[] = "hello";
char *p = "world";
sizeof(a); // 6 - one byte for each character in the string,
// one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
// probably 4 or 8 on most machines (depending on whether it's a
// 32 or 64 bit machine)
Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:
You will need to initialise memory wherever the arrays used to be. Eg, char a[10];
will become char *a = malloc(10 * sizeof(char));
, followed by a check that a != NULL
. Note that you don't actually need to say sizeof(char)
in this case, because sizeof(char)
is defined to be 1. I left it in for completeness.
Anywhere you previously had sizeof(a)
for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen()
, which counts up to the '\0'
).
You will need a make a corresponding call to free()
for each call to malloc()
. This tells the computer you are done using the memory you asked for with malloc()
. If your pointer is a
, just write free(a);
at a point in the code where you know you no longer need whatever a
points to.
As another answer pointed out, if you want to get the address of the start of an array, you can use:
char* p = &a[0]
You can read this as "char pointer p
becomes the address of element [0]
of a
".
You put your template in the wrong place. From the Flask docs:
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates
This is a late answer but if anyone reading this question is using razor, what you should remember is that razor encodes everything by default, but by using MvcHtmlString
in your html helpers you can tell razor that it doesn't need to encode it.
If you want razor to not encode a string use
@Html.Raw("<span>hi</span>")
Decompiling Raw(), shows us that it's wrapping the string in a HtmlString
public IHtmlString Raw(string value) {
return new HtmlString(value);
}
"HtmlString only exists in ASP.NET 4.
MvcHtmlString was a compatibility shim added to MVC 2 to support both .NET 3.5 and .NET 4. Now that MVC 3 is .NET 4 only, it's a fairly trivial subclass of HtmlString presumably for MVC 2->3 for source compatibility." source
Your current location might not be available immediately, after the map fragment is initialized.
After set
googleMap.setMyLocationEnabled(true);
you have to wait until you see the blue dot shown on your MapView. Then
Location myLocation = googleMap.getMyLocation();
myLocation won't be null.
I think you better use the LocationClient instead, and implement your own LocationListener.onLocationChanged(Location l)
Receiving Location Updates will show you how to get current location from LocationClient
Shipping the app with a database file is a good idea for me. The advantage is that you don't need to do a complex initialization, which sometimes costs lots of time, if your data set is huge.
Step 1: Prepare database file
Have your database file ready. It can be either a .db file or a .sqlite file. If you use a .sqlite file, all you need to do is to change file extension names. The steps are the same.
In this example, I prepared a file called testDB.db. It has one table and some sample data in it like this
Step 2: Import the file into your project
Create the assets folder if you haven't had one. Then copy and paste the database file into this folder
Step 3: Copy the file to the app's data folder
You need to copy the database file to the app's data folder in order to do further interaction with it. This is a one time action (initialization) to copy the database file. If you call this code multiple times, the database file in data folder will be overwritten by the one in assets folder. This overwrite process is useful when you want to update the database in future during the app update.
Note that during app update, this database file will not be changed in the app's data folder. Only uninstall will delete it.
The database file needs to be copied to /databases
folder. Open Device File Explorer. Enter data/data/<YourAppName>/
location. This is the app's default data folder mentioned above. And by default, the database file will be place in another folder called databases under this directory
Now, the copy file process is pretty much like the what Java is doing. Use the following code to do the copy paste. This is the initiation code. It can also be used to update(by overwriting) the database file in future.
//get context by calling "this" in activity or getActivity() in fragment
//call this if API level is lower than 17 String appDataPath = "/data/data/" + context.getPackageName() + "/databases/"
String appDataPath = context.getApplicationInfo().dataDir;
File dbFolder = new File(appDataPath + "/databases");//Make sure the /databases folder exists
dbFolder.mkdir();//This can be called multiple times.
File dbFilePath = new File(appDataPath + "/databases/testDB.db");
try {
InputStream inputStream = context.getAssets().open("testDB.db");
OutputStream outputStream = new FileOutputStream(dbFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer))>0)
{
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e){
//handle
}
Then refresh the folder to verify the copy process
Step 4: Create database open helper
Create a subclass for SQLiteOpenHelper
, with connect, close, path, etc. I named it DatabaseOpenHelper
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "testDB.db";
public static final String DB_SUB_PATH = "/databases/" + DB_NAME;
private static String APP_DATA_PATH = "";
private SQLiteDatabase dataBase;
private final Context context;
public DatabaseOpenHelper(Context context){
super(context, DB_NAME, null, 1);
APP_DATA_PATH = context.getApplicationInfo().dataDir;
this.context = context;
}
public boolean openDataBase() throws SQLException{
String mPath = APP_DATA_PATH + DB_SUB_PATH;
//Note that this method assumes that the db file is already copied in place
dataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.OPEN_READWRITE);
return dataBase != null;
}
@Override
public synchronized void close(){
if(dataBase != null) {dataBase.close();}
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Step 5: Create top level class to interact with the database
This will be the class that read & write your database file. Also there is a sample query to print out the value in the database.
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class Database {
private final Context context;
private SQLiteDatabase database;
private DatabaseOpenHelper dbHelper;
public Database(Context context){
this.context = context;
dbHelper = new DatabaseOpenHelper(context);
}
public Database open() throws SQLException
{
dbHelper.openDataBase();
dbHelper.close();
database = dbHelper.getReadableDatabase();
return this;
}
public void close()
{
dbHelper.close();
}
public void test(){
try{
String query ="SELECT value FROM test1";
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
String value = cursor.getString(0);
Log.d("db", value);
}while (cursor.moveToNext());
}
cursor.close();
} catch (SQLException e) {
//handle
}
}
}
Step 6: Test running
Test the code by running the following lines of codes.
Database db = new Database(context);
db.open();
db.test();
db.close();
Hit the run button and cheer!
Like this
add the Unix (epoch) datetime to the base date in seconds
this will get it for now (2010-05-25 07:56:23.000)
SELECT dateadd(s,1274756183,'19700101 05:00:00:000')
If you want to go reverse, take a look at this http://wiki.lessthandot.com/index.php/Epoch_Date
The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format
<TextBox Text="{Binding Value, StringFormat={}{0:#,0.0}}"
You need to wrap <input type = “file”>
in to <form>
tags and then you can reset input by resetting your form:
onClick="this.form.reset()"
Add/remove files to get things the way you want:
git rm classdir
git add sourcedir
Then amend the commit:
git commit --amend
The previous, erroneous commit will be edited to reflect the new index state - in other words, it'll be like you never made the mistake in the first place
Note that you should only do this if you haven't pushed yet. If you have pushed, then you'll just have to commit a fix normally.
In order to sort Strings alphabetically you will need to use a Collator
, like:
LinkedList<String> list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return Collator.getInstance().compare(o1, o2);
}
});
Because if you just call Collections.sort(list)
you will have trouble with strings that contain uppercase characters.
For instance in the code I pasted, after the sorting the list will be: [aAb, abc, Bcd]
but if you just call Collections.sort(list);
you will get: [Bcd, aAb, abc]
Note: When using a Collator
you can specify the locale Collator.getInstance(Locale.ENGLISH)
this is usually pretty handy.
One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.
One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).
Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.
-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
ID INT IDENTITY(1, 1) NOT NULL,
CallTime DATETIME NOT NULL DEFAULT GETDATE(),
CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
ID INT IDENTITY(1, 1) NOT NULL,
CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
Subject VARCHAR(250) NOT NULL,
Notes VARCHAR(8000) NOT NULL,
Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
PhoneCallID INT NOT NULL,
TicketID INT NOT NULL
)
@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS
<style type="text/css">
#nav-ask{ display:none; }
</style>
or if you already have a "hideMe" CSS Class:
<script type="text/javascript">
if(document.getElementById && document.createTextNode)
{
if(document.getElementById('nav-ask'))
{
document.getElementById('nav-ask').className='hideMe';
}
}
</script>
This is solved for me when I update maven and check the option "Force update of Snapshots/Releases" in Eclipse. this clears all errors. So right click on project -> Maven -> update project, then check the above option -> Ok. Hope this helps you.
Annoyingly enough, if you want to use the default model binders, it looks like you will have to use numerical index values like a form POST.
See the following excerpt from this article http://msdn.microsoft.com/en-us/magazine/hh781022.aspx:
Though it’s somewhat counterintuitive, JSON requests have the same requirements—they, too, must adhere to the form post naming syntax. Take, for example, the JSON payload for the previous UnitPrice collection. The pure JSON array syntax for this data would be represented as:
[ { "Code": "USD", "Amount": 100.00 }, { "Code": "EUR", "Amount": 73.64 } ]
However, the default value providers and model binders require the data to be represented as a JSON form post:
{ "UnitPrice[0].Code": "USD", "UnitPrice[0].Amount": 100.00, "UnitPrice[1].Code": "EUR", "UnitPrice[1].Amount": 73.64 }
The complex object collection scenario is perhaps one of the most widely problematic scenarios that developers run into because the syntax isn’t necessarily evident to all developers. However, once you learn the relatively simple syntax for posting complex collections, these scenarios become much easier to deal with.
In 2020 using r115 it works very good with this:
const renderer = new THREE.WebGLRenderer({ alpha: true });
const scene = new THREE.Scene();
scene.background = null;
An excellent answer given by msigman. I just want to add that in windows 10 you can find IIS Express System Tray (32 bit)
process under Visual Studio
process:
I've faced the same problem with Visual Studio 2015 Community Edition Update 1. The problem in my case was, the installer somehow could not install Visual C++ Redistributable x86 version. When I checked Add Remove Programs only x64 version was installed.
If that's the case for you, you can get the missing redistributable package from here; or you can find the version appropriate to you through a google search.
I created a jQuery plugin that uses Bootstrap's tooltip instead of the browser's build-in tooltip. Please note that this has not been tested with older browser.
JSFiddle: https://jsfiddle.net/0bhsoavy/4/
$.fn.tooltipOnOverflow = function(options) {
$(this).on("mouseenter", function() {
if (this.offsetWidth < this.scrollWidth) {
options = options || { placement: "auto"}
options.title = $(this).text();
$(this).tooltip(options);
$(this).tooltip("show");
} else {
if ($(this).data("bs.tooltip")) {
$tooltip.tooltip("hide");
$tooltip.removeData("bs.tooltip");
}
}
});
};
You can try using Microsoft's Sign Tool
You download it as part of the Windows SDK for Windows Server 2008 and .NET 3.5. Once downloaded you can use it from the command line like so:
signtool sign /a MyFile.exe
This signs a single executable, using the "best certificate" available. (If you have no certificate, it will show a SignTool error message.)
Or you can try:
signtool signwizard
This will launch a wizard that will walk you through signing your application. (This option is not available after Windows SDK 7.0.)
If you'd like to get a hold of certificate that you can use to test your process of signing the executable you can use the .NET tool Makecert.
Certificate Creation Tool (Makecert.exe)
Once you've created your own certificate and have used it to sign your executable, you'll need to manually add it as a Trusted Root CA for your machine in order for UAC to tell the user running it that it's from a trusted source. Important. Installing a certificate as ROOT CA will endanger your users privacy. Look what happened with DELL. You can find more information for accomplishing this both in code and through Windows in:
Stack Overflow question Install certificates in to the Windows Local user certificate store in C#
Installing a Self-Signed Certificate as a Trusted Root CA in Windows Vista
Hopefully that provides some more information for anyone attempting to do this!
Creating new DOM elements is a core feature of the jQuery()
method, see:
Sometimes clear will not work. Use float: none
as an override
I was successful using tidy
command line utility. On linux I installed it quickly with apt-get install tidy
. Then the command:
tidy -q -asxml --numeric-entities yes source.html >file.xml
gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.
This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)
I got this working on Android Studio 2.1. I have a module called "Native_Ads" which is shared across multiple projects.
First, I created a directory in my Native_ads module with the name 'aars' and then put the aar file in there.
Directory structure:
libs/
aars/ <-- newly created
src/
build.gradle
etc
Top level Gradle file:
allprojects {
repositories {
jcenter()
// For module with aar file in it
flatDir {
dirs project(':Native_Ads').file('aars')
}
}
}
App module's build.gradle file: - no changes
Settings.gradle file (to include the module):
include ':app'
include 'Native_Ads'
project(':Native_Ads').projectDir = new File(rootProject.projectDir, '../path/to/Native_Ads')
Gradle file for the Native_Ads module:
repositories {
jcenter()
flatDir {
dirs 'aars'
}
}
dependencies {
compile(name:'aar_file_name_without_aar_extension', ext:'aar')
}
That's it. Clean and build.
I was always of the assumption that the only reason this was possible was so there was a logical place to put a doc-string or other such stuff. I know if I used it for any production code it'd confuse most who read it.
Just in order to provide one more possible solution: In my case, I removed "central" from .m2/jdom/jdom/1.0 settings, and did everything else, without results.
So I discovered my settings.xml in ./m2 folder was stuck by a failed process. As I didn't found the process in the system task manager, I restarted the computer and it worked.
My understanding after reading the link offered by G.Grothendieck is that %>% is an operator that pipes functions. This helps readability and productivity as it's easier to follow the flow of multiple functions through these pipes than going backwards when multiple function are nested.
The <section>
tag defines sections in a document, such as chapters, headers, footers, or any other sections of the document.
whereas:
The <div>
tag defines a division or a section in an HTML document.
The <div>
tag is used to group block-elements to format them with CSS.
bash has a builtin
pushd SOME_PATH
run_stuff
...
...
popd
you can use html entity as •
After changing the configuration files don't forget to Restart All Services
.
I wasted three hours of my time on it.
In addition to the answers posted here, make sure you read this article:
String is immutable in java. you cannot modify/change, an existing string literal/object.
String s="Hello"; s=s+"hi";
Here the previous reference s is replaced by the new refernce s pointing to value "HelloHi".
However, for bringing mutability we have StringBuilder and StringBuffer.
StringBuilder s=new StringBuilder(); s.append("Hi");
this appends the new value "Hi" to the same refernce s. //
None of these answers fit my specific situation, which was that I wanted to run one specific cron job, just once, and run it immediately.
I'm on a Ubuntu server, and I use cPanel to setup my cron jobs.
I simply wrote down my current settings, and then edited them to be one minute from now. When I fixed another bug, I just edited it again to one minute from now. And when I was all done, I just reset the settings back to how they were before.
Example: It's 4:34pm right now, so I put 35 16 * * *, for it to run at 16:35.
It worked like a charm, and the most I ever had to wait was a little less than one minute.
I thought this was a better option than some of the other answers because I didn't want to run all of my weekly crons, and I didn't want the job to run every minute. It takes me a few minutes to fix whatever the issues were before I'm ready to test it again. Hopefully this helps someone.
This is probably one of the fastest way to remove permanently the duplicates from an array 10x times faster than the most functions here.& 78x faster in safari
function toUnique(a,b,c){//array,placeholder,placeholder
b=a.length;
while(c=--b)while(c--)a[b]!==a[c]||a.splice(c,1)
}
var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];
toUnique(array);
console.log(array);
if you can't read the code above ask, read a javascript book or here are some explainations about shorter code. https://stackoverflow.com/a/21353032/2450730
EDIT
As stated in the comments this function does return an array with uniques, the question however asks to find the duplicates. in that case a simple modification to this function allows to push the duplicates into an array, then using the previous function toUnique
removes the duplicates of the duplicates.
function theDuplicates(a,b,c,d){//array,placeholder,placeholder
b=a.length,d=[];
while(c=--b)while(c--)a[b]!==a[c]||d.push(a.splice(c,1))
}
var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];
toUnique(theDuplicates(array));
To resolve this issue you have to do two things :
You will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates.
Change few settings of Internet Explorer browser on that machine (where you desire to run automation).
1 . Setting Registry Key / Entry :
To set registry key or entry, you need to open "Registry Editor".
To open "Registry Editor" press windows button key + r alphabet key which will open "Run Window" and then type "regedit" and press enter.
Or Press Windows button key and enter "regedit" at start menu and press enter. Now depending upon your OS type whether 32/64 bit follow the corresponding steps.
Windows 32 bit : go to this location - "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl" and check for "FEATURE_BFCACHE" key.
Windows 64 bit : go to this location - HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl and check for "FEATURE_BFCACHE" key. Please note that the FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present.
Important: Inside this key, create a DWORD value named iexplore.exe with the value of 0.
2 . Change Settings of Internet Explorer Browser :
Click on setting button and select "Internet options".
On "Internet options" window go to "Security" tab
Now select "Internet" option and unchecked the "Enable Protected Mode" check box and change the "Security level" to low.
Now select "Local Intranet" Option and change the "Security level" to low.
Now select "Trusted Sites" Option and change the "Security level" to low.
Since index positioning in Python is 0-based, there won't actually be an element in index
at the location corresponding to len(DF)
. You need that to be last_row = len(DF) - 1
:
In [49]: dfrm
Out[49]:
A B C
0 0.120064 0.785538 0.465853
1 0.431655 0.436866 0.640136
2 0.445904 0.311565 0.934073
3 0.981609 0.695210 0.911697
4 0.008632 0.629269 0.226454
5 0.577577 0.467475 0.510031
6 0.580909 0.232846 0.271254
7 0.696596 0.362825 0.556433
8 0.738912 0.932779 0.029723
9 0.834706 0.002989 0.333436
[10 rows x 3 columns]
In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]:
A B C
0 0.120064 0.785538 0.465853
1 0.431655 0.436866 0.640136
2 0.445904 0.311565 0.934073
3 0.981609 0.695210 0.911697
4 0.008632 0.629269 0.226454
5 0.577577 0.467475 0.510031
6 0.580909 0.232846 0.271254
7 0.696596 0.362825 0.556433
8 0.738912 0.932779 0.029723
[9 rows x 3 columns]
However, it's much simpler to just write DF[:-1]
.
200 (cache) means Firefox is simply using the locally cached version. This is the fastest because no request to the Web server is made.
304 means Firefox is sending a "If-Modified-Since" conditional request to the Web server. If the file has not been updated since the date sent by the browser, the Web server returns a 304 response which essentially tells Firefox to use its cached version. It is not as fast as 200 (cache) because the request is still sent to the Web server, but the server doesn't have to send the contents of the file.
To your last question, I don't know why the two JavaScript files in the same directory are returning different results.
If you are using the Postgres Mac app (by Heroku) and Bundler, you can add the pg_config directly inside the app, to your bundle.
bundle config build.pg --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config
...then run bundle again.
Note: check the version first using the following.
ls /Applications/Postgres.app/Contents/Versions/
The logic in the "one-liner" works fine. From personal experience, what has helped me is to assign the statements to variables (in their "True" form) and then use logical operators for the result:
A = year % 4 == 0
B = year % 100 == 0
C = year % 400 == 0
I used '==' in the B statement instead of "!=" and applied 'not' logical operator in the calculation:
leap = A and (not B or C)
This comes in handy with a larger set of conditions, and to simplify the boolean operation where applicable before writing a whole bunch of if statements.
To attach JDK source so that you refer to Java Source Code for code look-up which helps in learning the library implementation and sometimes in debugging, all you have to do is:
In your Eclipse Java Project > JRE Reference Library locate rt.jar. Right click and go to Properties:
Select "Java Source Attachment" on the right and to the left select "External Location" and click on "External File" Button and locate "src.zip" file in your $JAVA_HOME path in my case for my windows machine src.zip location is: C:/Program Files/Java/jdk1.7.0_45/src.zip.
You are done now! Just Ctrl + click on any Java library Class in your project code to look-up the source code for the java class.
This is how to assign a value to a variable:
SELECT @EmpID = Id
FROM dbo.Employee
However, the above query is returning more than one value. You'll need to add a WHERE
clause in order to return a single Id
value.
Here's the short answer: a struct is a record structure: each element in the struct allocates new space. So, a struct like
struct foobarbazquux_t {
int foo;
long bar;
double baz;
long double quux;
}
allocates at least (sizeof(int)+sizeof(long)+sizeof(double)+sizeof(long double))
bytes in memory for each instance. ("At least" because architecture alignment constraints may force the compiler to pad the struct.)
On the other hand,
union foobarbazquux_u {
int foo;
long bar;
double baz;
long double quux;
}
allocates one chunk of memory and gives it four aliases. So sizeof(union foobarbazquux_u) = max((sizeof(int),sizeof(long),sizeof(double),sizeof(long double))
, again with the possibility of some addition for alignments.
The key lies in when you create the project in eclipse.
First step, you create the Java project in eclipse. Right click on the project and choose Team > Share>Git.
In the Configure Git Repository dialog, ensure that you select the option to create the Repository in the parent folder of the project.. Then you can push to github.
N.B: Eclipse will give you a warning about putting git repositories in your workspace. So when you create your project, set your project directory outside the default workspace.
Also removing the submodule and then running git submodule init
and git submodule update
will obviously do the trick, but may not always be appropriate or possible.
I too had this error, on Windows Server 2008 IIS 7, I had no visual studio installed so a reinstall / repair of .NET 4.0 did the trick.
This does it. Note that with an odd number of elements the one in the middle won't be included.
test = [1, 23, 4, 6, 7, 8, 5]
for i in range(len(test)/2):
print (test[i], test[-1-i])
Output:
(1, 5)
(23, 8)
(4, 7)
WORKDIR /scripts
COPY bootstrap.sh .
RUN ./bootstrap.sh
In May 2017 Google launched the official Google Maps URLs documentation. The Google Maps URLs introduces universal cross-platform syntax that you can use in your applications.
Have a look at the following document:
https://developers.google.com/maps/documentation/urls/guide
You can use URLs in search, directions, map and street view modes.
For example, to show the marker at specified position you can use the following URL:
https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324
For further details please read aforementioned documentation.
You can also file feature requests for this API in Google issue tracker.
Hope this helps!
For Sql Azure the following query works :
ALTER TABLE [TableName] ADD DEFAULT 'DefaultValue' FOR ColumnName
GO
If you want to retrieve the key's value if it exists, you can also use
try:
value = a[key]
except KeyError:
# Key is not present
pass
If you want to retrieve a default value when the key does not exist, use
value = a.get(key, default_value)
.
If you want to set the default value at the same time in case the key does not exist, use
value = a.setdefault(key, default_value)
.
Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1
(true
) or 0
(false
) depending on whether the arguments are equal or unequal, the spaceship operator will return 1
, 0
, or -1
depending on the value of the left argument relative to the right argument.
a <=> b :=
if a < b then return -1
if a = b then return 0
if a > b then return 1
if a and b are not comparable then return nil
It's useful for sorting an array.
The Algorithm for given flow chart :
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Step :01
Step :02 [Variable initialization]
Step :03[Condition Check]
Step:04
You can certainly validate the file for a particular charset by decoding it with a CharsetDecoder
and watching out for "malformed-input" or "unmappable-character" errors. Of course, this only tells you if a charset is wrong; it doesn't tell you if it is correct. For that, you need a basis of comparison to evaluate the decoded results, e.g. do you know beforehand if the characters are restricted to some subset, or whether the text adheres to some strict format? The bottom line is that charset detection is guesswork without any guarantees.
Just for those who have already created the table with the header. Here is the alter command for the same. This is useful in case you already have the table and want the first row to be ignored without dropping and recreating. It also helps with people to familiarize with ALTER as a option with TBLPROPERTIES.
ALTER TABLE tablename SET TBLPROPERTIES ("skip.header.line.count"="1");
The following also works:
select dump(a,1016), a from (
SELECT REGEXP_REPLACE (
CONVERT (
'3735844533120%$03 ',
'US7ASCII',
'WE8ISO8859P1'),
'[^!@/\.,;:<>#$%&()_=[:alnum:][:blank:]]') a
FROM DUAL);
This is too simple
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MyProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
getCapturesProfilePicFromCamera();
} else if (items[item].equals("Choose from Library")) {
getProfilePicFromGallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
Try This Code. here we have two longitude and latitude values and selected_location.distanceTo(near_locations) function returns the distance between those places in meters.
Location selected_location = new Location("locationA");
selected_location.setLatitude(17.372102);
selected_location.setLongitude(78.484196);
Location near_locations = new Location("locationB");
near_locations.setLatitude(17.375775);
near_locations.setLongitude(78.469218);
double distance = selected_location.distanceTo(near_locations);
here "distance" is distance between locationA & locationB (in Meters
)
I use git gc after I do a big checkout, and have a lot of new object. it can save space. E.g. if you checkout a big SVN project using git-svn, and do a git gc, you typically save a lot of space
Use this typesafe pattern with poison pills:
public sealed interface BaseMessage {
final class ValidMessage<T> implements BaseMessage {
@Nonnull
private final T value;
public ValidMessage(@Nonnull T value) {
this.value = value;
}
@Nonnull
public T getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ValidMessage<?> that = (ValidMessage<?>) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return "ValidMessage{value=%s}".formatted(value);
}
}
final class PoisonedMessage implements BaseMessage {
public static final PoisonedMessage INSTANCE = new PoisonedMessage();
private PoisonedMessage() {
}
@Override
public String toString() {
return "PoisonedMessage{}";
}
}
}
public class Producer implements Callable<Void> {
@Nonnull
private final BlockingQueue<BaseMessage> messages;
Producer(@Nonnull BlockingQueue<BaseMessage> messages) {
this.messages = messages;
}
@Override
public Void call() throws Exception {
messages.put(new BaseMessage.ValidMessage<>(1));
messages.put(new BaseMessage.ValidMessage<>(2));
messages.put(new BaseMessage.ValidMessage<>(3));
messages.put(BaseMessage.PoisonedMessage.INSTANCE);
return null;
}
}
public class Consumer implements Callable<Void> {
@Nonnull
private final BlockingQueue<BaseMessage> messages;
private final int maxPoisons;
public Consumer(@Nonnull BlockingQueue<BaseMessage> messages, int maxPoisons) {
this.messages = messages;
this.maxPoisons = maxPoisons;
}
@Override
public Void call() throws Exception {
int poisonsReceived = 0;
while (poisonsReceived < maxPoisons && !Thread.currentThread().isInterrupted()) {
BaseMessage message = messages.take();
if (message instanceof BaseMessage.ValidMessage<?> vm) {
Integer value = (Integer) vm.getValue();
System.out.println(value);
} else if (message instanceof BaseMessage.PoisonedMessage) {
++poisonsReceived;
} else {
throw new IllegalArgumentException("Invalid BaseMessage type: " + message);
}
}
return null;
}
}
var strdate = new Date('Tue Feb 07 2017 12:51:48 GMT+0200 (Türkiye Standart Saati)');_x000D_
var date = moment(strdate).format('DD.MM.YYYY');_x000D_
$("#result").text(date); //07.02.2017
_x000D_
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>_x000D_
_x000D_
<div id="result"></div>
_x000D_
WebApiConfig.Register(GlobalConfiguration.Configuration);
Should be first in App_start event. I have tried it at last position in APP_start event, but that did not work.
You should use like this:
body { background: url("img/debut_dark.png") repeat 0 0; } body { background: url("../img/debut_dark.png") repeat 0 0; } body { background-image: url("../img/debut_dark.png") repeat 0 0; }
or try Inspecting CSS Rules using Firefox Firebug tool.
Another reason to use object
over iframe is that object
sub resources (when an <object>
performs HTTP
requests) are considered as passive/display
in terms of Mixed content
, which means it's more secure when you must have Mixed content
.
Mixed content means that when you have https
but your resource is from http
.
Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content