The code pasted by Rivers is great. Thanks a lot! I'm new here and can't comment, I'd just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as I've lost a lot of time to figure it out.
You need to add the parameters both to the URL and to the signature creating process. Creating a signature is the article that helped me. Here is my code:
$oauth = array(
'screen_name' => 'DwightHoward',
'count' => 2,
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$options = array(
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
);
You're right in thinking that, in order to share an image in this way without going down the Twitter Cards route, you need to to have tweeted the image already. As you say, it's also important that you grab the image link that's of the form pic.twitter.com/NuDSx1ZKwy
This step-by-step guide is worth checking out for anyone looking to implement a 'tweet this' link or button: http://onlinejournalismblog.com/2015/02/11/how-to-make-a-tweetable-image-in-your-blog-post/.
import json
with open("twitterdata.json", "w") as twitter_data_file:
json.dump(output, twitter_data_file, indent=4, sort_keys=True)
You don't need json.dumps()
if you don't want to parse the string later, just simply use json.dump()
. It's faster too.
To clarify. What is important to know is that:
Here is a working snippet of code, where we do a little bit of date manipulation to ensure Mongo (here i am using mongoose module and want results for rows whose date attribute is less than (before) the date given as myDate param) can handle it correctly:
var inputDate = new Date(myDate.toISOString());
MyModel.find({
'date': { $lte: inputDate }
})
Go to https://dev.twitter.com/apps to list all your apps. Click on the desired app to get its consumer and secret key. If you didnt yet created any app then follow https://dev.twitter.com/apps/new to create new one.
The ACTION_SEND
will only give you options for sending using GMail, YahooMail... etc(Any application installed on your phone, that can perform ACTION_SEND
). If you want to share on Facebook or Twitter you will need to place custom buttons for each and use their own SDK such as Facebook SDK or Twitter4J .
FOR SQLALCHEMY AND PYTHON
The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:
e = create_engine(
"mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
All modern DBAPIs should support the utf8mb4 charset.
Just like in this question (npm global path prefix) all you need is to set proper npm prefix
.
UNIX:
$ npm config set prefix /usr/local
$ npm install -g bower
$ which bower
>> /usr/local/bin/bower
Windows ans NVM:
$ npm config set prefix /c/Users/xxxxxxx/AppData/Roaming/nvm/v8.9.2
$ npm install -g bower
Then bower
should be located just in your $PATH
.
there are many causes such as
To examine the problem in detail, you can use Wireshark.
or you can just re-request or re-connect again.
datetime has fields hour
and minute
. So to get the hours and minutes, you would use t1.hour
and t1.minute
.
However, when you subtract two datetimes, the result is a timedelta, which only has the days
and seconds
fields. So you'll need to divide and multiply as necessary to get the numbers you need.
Not all twitter API users are created equal - some are more equal than others.
https://dev.twitter.com/docs/streaming-api/methods
For thine not that equal they suggest creative using of other techniques. You may get more luck by using search api calls with time / id limitation
Either decorate your root entity with the XmlRoot attribute which will be used at compile time.
[XmlRoot(Namespace = "www.contoso.com", ElementName = "MyGroupName", DataType = "string", IsNullable=true)]
Or specify the root attribute when de serializing at runtime.
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "user";
// xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;
XmlSerializer xs = new XmlSerializer(typeof(User),xRoot);
UPDATE for v1.1:
Rather than giving q="search_string"
give it q="hashtag"
in URL encoded form to return results with HASHTAG ONLY. So your query would become:
GET https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames
%23
is URL encoded form of #
. Try the link out in your browser and it should work.
You can optimize the query by adding since_id
and max_id
parameters detailed here. Hope this helps !
Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call
Updated
Twitter Search doc link: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
I found a faster way of embedding:
First of all: I'm the author of the The Single Page Interface Manifesto cited by raganwald
As raganwald has explained very well, the most important aspect of the Single Page Interface (SPI) approach used in FaceBook and Twitter is the use of hash #
in URLs
The character !
is added only for Google purposes, this notation is a Google "standard" for crawling web sites intensive on AJAX (in the extreme Single Page Interface web sites). When Google's crawler finds an URL with #!
it knows that an alternative conventional URL exists providing the same page "state" but in this case on load time.
In spite of #!
combination is very interesting for SEO, is only supported by Google (as far I know), with some JavaScript tricks you can build SPI web sites SEO compatible for any web crawler (Yahoo, Bing...).
The SPI Manifesto and demos do not use Google's format of !
in hashes, this notation could be easily added and SPI crawling could be even easier (UPDATE: now ! notation is used and remains compatible with other search engines).
Take a look to this tutorial, is an example of a simple ItsNat SPI site but you can pick some ideas for other frameworks, this example is SEO compatible for any web crawler.
The hard problem is to generate any (or selected) "AJAX page state" as plain HTML for SEO, in ItsNat is very easy and automatic, the same site is in the same time SPI or page based for SEO (or when JavaScript is disabled for accessibility). With other web frameworks you can ever follow the double site approach, one site is SPI based and another page based for SEO, for instance Twitter uses this "double site" technique.
I had the same problem and none of the other answers worked. My problem was a weird one where IE9 wasn't able to connect to any https sites, therefore since I was using the online maxcdn bootstrap files like,
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css
none of that css and js was being applied. Going into the Advanced tab of Internet Explorer options I verified that not having "use TLS 1.0" checked caused the problem with https sites and files, and once checked my bootstrap page was formatted as expected.
As others have noted use the proper doctype below (maybe a valid html4 doctype will work, but if you're starting anew might as well use html5.)
The respond js and html5 shim (if using that) are for IE8. IE9 doesn't need that. The code below uses the standard method of targeting ie8 and below.
--Art
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- content -->
</body>
</html>
There is a much simpler solution for that.
Actually treating the items of JArray
as JObject
works.
Here is an example:
Let's say we have such array of JSON objects:
JArray jArray = JArray.Parse(@"[
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
}]");
To get access each item we just do the following:
foreach (JObject item in jArray)
{
string name = item.GetValue("name").ToString();
string url = item.GetValue("url").ToString();
// ...
}
If you add it manual on html site, just replace:
&
With
&
Standard html code for &
You need to send customerKey and customerSecret to Zend_Service_Twitter
$twitter = new Zend_Service_Twitter(array(
'consumerKey' => $this->consumer_key,
'consumerSecret' => $this->consumer_secret,
'username' => $user->screenName,
'accessToken' => unserialize($user->token)
));
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
you can simply do:
textAreaContent=textAreaContent.replace(/\n/g,"<br>");
Also you can use Android Multitool. You can make minor changes in the app like hiding GUI elements or modifying small part of Logic and rebuild the apk. Its easy to use and decompile/recompile apk and jar files. Here is the Link you can checkout.
Cheers
UPDATE mytable SET spares = CONCAT(spares, ',', '818') WHERE id = 1
not working for me.
spares is NULL
by default but its varchar
if you are using docker you have to do the following steps:
copy the file from hdfs to namenode (hadoop fs -get output/part-r-00000 /out_text). "/out_text" will be stored on the namenode.
copy the file from namenode to local disk by (docker cp namenode:/out_text output.txt)
output.txt will be there on your current working directory
Try This
Input:
<!DOCTYPE html>
<html>
<body>
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
<p>Converting < and > into entities are often used to prevent browsers from using it as an HTML element. <br />This can be especially useful to prevent code from running when users have access to display input on your homepage.</p>
</body>
</html>
Output:
This is some <b>bold</b> text.
Converting < and > into entities are often used to prevent browsers from using it as an HTML element. This can be especially useful to prevent code from running when users have access to display input on your homepage.
more.exe
exists on Windows, ports of less
are easily found (and the PowerShell Community Extensions, PSCX, includes one).
PowerShell doesn't really provide any alternative to separate programs for either, but for structured data Out-Grid
can be helpful.
Head
and Tail
can both be emulated with Select-Object
using the -First
and -Last
parameters respectively.
Sed
functions are all available but structured rather differently. The filtering options are available in Where-Object
(or via Foreach-Object
and some state for ranges). Other, transforming, operations can be done with Select-Object
and Foreach-Object
.
However as PowerShell passes (.NET) objects – with all their typed structure, eg. dates remain DateTime
instances – rather than just strings, which each command needs to parse itself, much of sed
and other such programs are redundant.
Here's the complete procedure to auto-indent a file with Netbeans 8.
First step is to go to Tools -> Options
and click on Editor button and Formatting tab as it is shown on the following image.
When you have set your formatting options, click the Apply button and OK. Note that my example is with C++ language, but this also apply for Java as well.
The second step is to CTRL + A on the file where you want to apply your new formatting setting. Then, ALT + SHIFT + F or click on the menu Source -> Format
.
Hope this will help.
I suggest to not only store a boolean flag, but the complete version code. This way you can also query at the beginning if it is the first start in a new version. You can use this information to display a "Whats new" dialog, for example.
The following code should work from any android class that "is a context" (activities, services, ...). If you prefer to have it in a separate (POJO) class, you could consider using a "static context", as described here for example.
/**
* Distinguishes different kinds of app starts: <li>
* <ul>
* First start ever ({@link #FIRST_TIME})
* </ul>
* <ul>
* First start in this version ({@link #FIRST_TIME_VERSION})
* </ul>
* <ul>
* Normal app start ({@link #NORMAL})
* </ul>
*
* @author schnatterer
*
*/
public enum AppStart {
FIRST_TIME, FIRST_TIME_VERSION, NORMAL;
}
/**
* The app version code (not the version name!) that was used on the last
* start of the app.
*/
private static final String LAST_APP_VERSION = "last_app_version";
/**
* Finds out started for the first time (ever or in the current version).<br/>
* <br/>
* Note: This method is <b>not idempotent</b> only the first call will
* determine the proper result. Any subsequent calls will only return
* {@link AppStart#NORMAL} until the app is started again. So you might want
* to consider caching the result!
*
* @return the type of app start
*/
public AppStart checkAppStart() {
PackageInfo pInfo;
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
AppStart appStart = AppStart.NORMAL;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
int lastVersionCode = sharedPreferences
.getInt(LAST_APP_VERSION, -1);
int currentVersionCode = pInfo.versionCode;
appStart = checkAppStart(currentVersionCode, lastVersionCode);
// Update version in preferences
sharedPreferences.edit()
.putInt(LAST_APP_VERSION, currentVersionCode).commit();
} catch (NameNotFoundException e) {
Log.w(Constants.LOG,
"Unable to determine current app version from pacakge manager. Defenisvely assuming normal app start.");
}
return appStart;
}
public AppStart checkAppStart(int currentVersionCode, int lastVersionCode) {
if (lastVersionCode == -1) {
return AppStart.FIRST_TIME;
} else if (lastVersionCode < currentVersionCode) {
return AppStart.FIRST_TIME_VERSION;
} else if (lastVersionCode > currentVersionCode) {
Log.w(Constants.LOG, "Current version code (" + currentVersionCode
+ ") is less then the one recognized on last startup ("
+ lastVersionCode
+ "). Defenisvely assuming normal app start.");
return AppStart.NORMAL;
} else {
return AppStart.NORMAL;
}
}
It could be used from an activity like this:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
switch (checkAppStart()) {
case NORMAL:
// We don't want to get on the user's nerves
break;
case FIRST_TIME_VERSION:
// TODO show what's new
break;
case FIRST_TIME:
// TODO show a tutorial
break;
default:
break;
}
// ...
}
// ...
}
The basic logic can be verified using this JUnit test:
public void testCheckAppStart() {
// First start
int oldVersion = -1;
int newVersion = 1;
assertEquals("Unexpected result", AppStart.FIRST_TIME,
service.checkAppStart(newVersion, oldVersion));
// First start this version
oldVersion = 1;
newVersion = 2;
assertEquals("Unexpected result", AppStart.FIRST_TIME_VERSION,
service.checkAppStart(newVersion, oldVersion));
// Normal start
oldVersion = 2;
newVersion = 2;
assertEquals("Unexpected result", AppStart.NORMAL,
service.checkAppStart(newVersion, oldVersion));
}
With a bit more effort you could probably test the android related stuff (PackageManager and SharedPreferences) as well. Anyone interested in writing the test? :)
Note that the above code will only work properly if you don't mess around with your android:versionCode
in AndroidManifest.xml!
Also try if in the eclipse paths there is some duplicated
Luna - http://download.eclipse.org/releases/luna
Luna - http://download.eclipse.org/releases/luna/1234567...
Try both of them, one may work.
In my case, with 2 eclispes installed, in one of them the path
Luna - http://download.eclipse.org/releases/luna
works, in the other one, i must select:
Luna - http://download.eclipse.org/releases/luna/123456...
In both the internal browser can access to internet. Both are Luna (but one is RCM, the other one i don't remember).
In my case, it's because I deleted the chrome update folder. After chrome reinstall, it's working fine.
Your submission will cancel the redirect or vice versa.
I do not see the reason for the redirect in the first place since why do you have an order form that does nothing.
That said, here is how to do it. Firstly NEVER put code on the submit button but do it in the onsubmit, secondly return false to stop the submission
NOTE This code will IGNORE the action and ONLY execute the script due to the return false/preventDefault
function redirect() {
window.location.replace("login.php");
return false;
}
using
<form name="form1" id="form1" method="post" onsubmit="return redirect()">
<input type="submit" class="button4" name="order" id="order" value="Place Order" >
</form>
Or unobtrusively:
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
window.location.replace("login.php");
return false;
}
}
using
<form id="form1" method="post">
<input type="submit" class="button4" value="Place Order" >
</form>
jQuery:
$("#form1").on("submit",function(e) {
e.preventDefault(); // cancel submission
window.location.replace("login.php");
});
Example:
$("#form1").on("submit", function(e) {_x000D_
e.preventDefault(); // cancel submission_x000D_
alert("this could redirect to login.php"); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<form id="form1" method="post" action="javascript:alert('Action!!!')">_x000D_
<input type="submit" class="button4" value="Place Order">_x000D_
</form>
_x000D_
these functions will solve the problem, you need to implement the DrawThumbnails
function and have a global variable to store the images. I love to get this to work with a class object that has the ThumbnailImageArray
as a member variable, but am struggling!
called as in addThumbnailImages(10);
var ThumbnailImageArray = [];
function addThumbnailImages(MaxNumberOfImages)
{
var imgs = [];
for (var i=1; i<MaxNumberOfImages; i++)
{
imgs.push(i+".jpeg");
}
preloadimages(imgs).done(function (images){
var c=0;
for(var i=0; i<images.length; i++)
{
if(images[i].width >0)
{
if(c != i)
images[c] = images[i];
c++;
}
}
images.length = c;
DrawThumbnails();
});
}
function preloadimages(arr)
{
var loadedimages=0
var postaction=function(){}
var arr=(typeof arr!="object")? [arr] : arr
function imageloadpost()
{
loadedimages++;
if (loadedimages==arr.length)
{
postaction(ThumbnailImageArray); //call postaction and pass in newimages array as parameter
}
};
for (var i=0; i<arr.length; i++)
{
ThumbnailImageArray[i]=new Image();
ThumbnailImageArray[i].src=arr[i];
ThumbnailImageArray[i].onload=function(){ imageloadpost();};
ThumbnailImageArray[i].onerror=function(){ imageloadpost();};
}
//return blank object with done() method
//remember user defined callback functions to be called when images load
return { done:function(f){ postaction=f || postaction } };
}
It's in an additional download. Use this menu item:
Xcode > Open Developer Tool > More Developer Tools...
and get "Hardware IO Tools for Xcode".
For Xcode 8+, get "Additional Tools for Xcode [version]".
Double-click on a .prefPane
file to install. If you already have an older .prefPane
installed, you'll need to remove it from /Library/PreferencePanes
.
MarvinS.-
Try:
$.ajax({
url: uri+'?js',
success: function(data) {
var imgAttr = $("img", data).attr('src');
var htmlCode = $(data).html();
$('#imgSrc').html(imgAttr);
$('#fullHtmlOutput').html(htmlCode);
}
});
This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.
If all the above methods are not working then change implementation 'com.google.firebase:firebase-core:12.0.0'
to implementation 'com.google.firebase:firebase-core:10.0.0'
in your app level build.gradle file.
This would surely work.
The throws Exception
declaration is an automated way of keeping track of methods that might throw an exception for anticipated but unavoidable reasons. The declaration is typically specific about the type or types of exceptions that may be thrown such as throws IOException
or throws IOException, MyException
.
We all have or will eventually write code that stops unexpectedly and reports an exception due to something we did not anticipate before running the program, like division by zero or index out of bounds. Since the errors were not expected by the method, they could not be "caught" and handled with a try catch clause. Any unsuspecting users of the method would also not know of this possibility and their programs would also stop.
When the programmer knows certain types of errors may occur but would like to handle these exceptions outside of the method, the method can "throw" one or more types of exceptions to the calling method instead of handling them. If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw. Since programs can have many layers of methods written by many different programs, it becomes difficult (impossible) to keep track of which methods might throw exceptions.
Even though Java has the ability to declare exceptions, you can still write a new method with unhandled and undeclared exceptions, and Java will compile it and you can run it and hope for the best. What Java won't let you do is compile your new method if it uses a method that has been declared as throwing exception(s), unless you either handle the declared exception(s) in your method or declare your method as throwing the same exception(s) or if there are multiple exceptions, you can handle some and throw the rest.
When a programmer declares that the method throws a specific type of exception, it is just an automated way of warning other programmers using the method that an exception is possible. The programmer can then decide to handled the exception or pass on the warning by declaring the calling method as also throwing the same exception. Since the compiler has been warned the exception is possible in this new method, it can automatically check if future callers of the new method handle the exception or declare it and enforcing one or the other to happen.
The nice thing about this type of solution is that when the compiler reports Error: Unhandled exception type java.io.IOException
it gives the file and line number of the method that was declared to throw the exception. You can then choose to simply pass the buck and declare your method also "throws IOException". This can be done all the way up to main method where it would then cause the program to stop and report the exception to the user. However, it is better to catch the exception and deal with it in a nice way such as explaining to the user what has happened and how to fix it. When a method does catch and handle the exception, it no longer has to declare the exception. The buck stops there so to speak.
You don't need to even have the count in the returned columns if you don't need to know the actual number of duplicates. e.g.
SELECT column_name
FROM table
GROUP BY column_name
HAVING COUNT(*) > 1
The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.
http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html
Just tried in Eclipse, the variable in interface is default to be final, so you can't change it. Compared with parent class, the variables are definitely changeable. Why? From my point, variable in class is an attribute which will be inherited by children, and children can change it according to their actual need. On the contrary, interface only define behavior, not attribute. The only reason to put in variables in interface is to use them as consts which related to that interface. Though, this is not a good practice according to following excerpt:
"Placing constants in an interface was a popular technique in the early days of Java, but now many consider it a distasteful use of interfaces, since interfaces should deal with the services provided by an object, not its data. As well, the constants used by a class are typically an implementation detail, but placing them in an interface promotes them to the public API of the class."
I also tried either put static or not makes no difference at all. The code is as below:
public interface Addable {
static int count = 6;
public int add(int i);
}
public class Impl implements Addable {
@Override
public int add(int i) {
return i+count;
}
}
public class Test {
public static void main(String... args) {
Impl impl = new Impl();
System.out.println(impl.add(4));
}
}
I found a solution to this. It's bloody witchcraft, but it works.
When you install the client, open Control Panel > Network Connections.
You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).
Right Click it, click Enable.
The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.
In Excel 2013 simply select multiple sheets and do a "Save As" and select PDF as the file type. The multiple pages will open in PDF when you click save.
You can use foreach here just fine.
foreach ($rows as $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
I think you are used to accessing the data with numerical indicies (such as $row[0]
), but this is not necessary. We can use associative arrays to get the data we're after.
A simple way to set spinner based on value is
mySpinner.setSelection(getIndex(mySpinner, myValue));
//private method of your class
private int getIndex(Spinner spinner, String myString){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
return i;
}
}
return 0;
}
Way to complex code are already there, this is just much plainer.
I generally try to avoid the Convert
class (meaning: I don't use it) because I find it very confusing: the code gives too few hints on what exactly happens here since Convert
allows a lot of semantically very different conversions to occur with the same code. This makes it hard to control for the programmer what exactly is happening.
My advice, therefore, is never to use this class. It's not really necessary either (except for binary formatting of a number, because the normal ToString
method of number classes doesn't offer an appropriate method to do this).
No, LINQ doesn't support a manner of mass updating. The only shorter way would be to use a ForEach
extension method - Why there is no ForEach extension method on IEnumerable?
This may or may not help you address your problem, OP, but to get the timezone of the current server relative to UTC (UT1, technically), do:
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
The above works by extracting the UT1-relative offset in minutes, and then converting it to hours using the factor of 3600 secs/hour.
Example:
SET SESSION timezone TO 'Asia/Kabul';
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
-- output: 4.5 (as of the writing of this post)
(docs).
x->y can mean 2 things. If x is a pointer, then it means member y of object pointed to by x. If x is an object with operator->() overloaded, then it means x.operator->().
If you have installed openssl
, you can use:
echo -n "foobar" | openssl dgst -sha256
For other algorithms you can replace -sha256
with -md4
, -md5
, -ripemd160
, -sha
, -sha1
, -sha224
, -sha384
, -sha512
or -whirlpool
.
Assuming MySQL supports it, you can easily do this with a standard SQL subquery:
select
(count(*) from league_girl l1 where l2.score > l1.score and l1.id <> l2.id) as position,
username,
score
from league_girl l2
order by score;
For large amounts of displayed results, this will be a bit slow and you will want to switch to a self join instead.
Another alternative is to link libedit for proper line editing (arrow keys, etc.) and optional history support. I wanted this for a project I'm starting and put together a basic example for how I set it up.
Usage from swift
let prompt: Prompt = Prompt(argv0: C_ARGV[0])
while (true) {
if let line = prompt.gets() {
print("You typed \(line)")
}
}
ObjC wrapper to expose libedit
#import <histedit.h>
char* prompt(EditLine *e) {
return "> ";
}
@implementation Prompt
EditLine* _el;
History* _hist;
HistEvent _ev;
- (instancetype) initWithArgv0:(const char*)argv0 {
if (self = [super init]) {
// Setup the editor
_el = el_init(argv0, stdin, stdout, stderr);
el_set(_el, EL_PROMPT, &prompt);
el_set(_el, EL_EDITOR, "emacs");
// With support for history
_hist = history_init();
history(_hist, &_ev, H_SETSIZE, 800);
el_set(_el, EL_HIST, history, _hist);
}
return self;
}
- (void) dealloc {
if (_hist != NULL) {
history_end(_hist);
_hist = NULL;
}
if (_el != NULL) {
el_end(_el);
_el = NULL;
}
}
- (NSString*) gets {
// line includes the trailing newline
int count;
const char* line = el_gets(_el, &count);
if (count > 0) {
history(_hist, &_ev, H_ENTER, line);
return [NSString stringWithCString:line encoding:NSUTF8StringEncoding];
}
return nil;
}
@end
I was looking for a solution to this problem myself with no luck, so I had to roll my own which I would like to share here with you. (Please excuse my bad English) (It's a little crazy to answer another Czech guy in English :-) )
The first thing I tried was to use a good old PopupWindow
. It's quite easy - one only has to listen to the OnMarkerClickListener
and then show a custom PopupWindow
above the marker. Some other guys here on StackOverflow suggested this solution and it actually looks quite good at first glance. But the problem with this solution shows up when you start to move the map around. You have to move the PopupWindow
somehow yourself which is possible (by listening to some onTouch events) but IMHO you can't make it look good enough, especially on some slow devices. If you do it the simple way it "jumps" around from one spot to another. You could also use some animations to polish those jumps but this way the PopupWindow
will always be "a step behind" where it should be on the map which I just don't like.
At this point, I was thinking about some other solution. I realized that I actually don't really need that much freedom - to show my custom views with all the possibilities that come with it (like animated progress bars etc.). I think there is a good reason why even the google engineers don't do it this way in the Google Maps app. All I need is a button or two on the InfoWindow that will show a pressed state and trigger some actions when clicked. So I came up with another solution which splits up into two parts:
First part:
The first part is to be able to catch the clicks on the buttons to trigger some action. My idea is as follows:
MapFragment
(or MapView
) inside a custom ViewGroup (mine is called MapWrapperLayout)MapWrapperLayout
's dispatchTouchEvent and (if the InfoWindow is currently shown) first route the MotionEvents to the previously created InfoWindow. If it doesn't consume the MotionEvents (like because you didn't click on any clickable area inside InfoWindow etc.) then (and only then) let the events go down to the MapWrapperLayout's superclass so it will eventually be delivered to the map.Here is the MapWrapperLayout's source code:
package com.circlegate.tt.cg.an.lib.map;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Marker;
import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class MapWrapperLayout extends RelativeLayout {
/**
* Reference to a GoogleMap object
*/
private GoogleMap map;
/**
* Vertical offset in pixels between the bottom edge of our InfoWindow
* and the marker position (by default it's bottom edge too).
* It's a good idea to use custom markers and also the InfoWindow frame,
* because we probably can't rely on the sizes of the default marker and frame.
*/
private int bottomOffsetPixels;
/**
* A currently selected marker
*/
private Marker marker;
/**
* Our custom view which is returned from either the InfoWindowAdapter.getInfoContents
* or InfoWindowAdapter.getInfoWindow
*/
private View infoWindow;
public MapWrapperLayout(Context context) {
super(context);
}
public MapWrapperLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MapWrapperLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Must be called before we can route the touch events
*/
public void init(GoogleMap map, int bottomOffsetPixels) {
this.map = map;
this.bottomOffsetPixels = bottomOffsetPixels;
}
/**
* Best to be called from either the InfoWindowAdapter.getInfoContents
* or InfoWindowAdapter.getInfoWindow.
*/
public void setMarkerWithInfoWindow(Marker marker, View infoWindow) {
this.marker = marker;
this.infoWindow = infoWindow;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean ret = false;
// Make sure that the infoWindow is shown and we have all the needed references
if (marker != null && marker.isInfoWindowShown() && map != null && infoWindow != null) {
// Get a marker position on the screen
Point point = map.getProjection().toScreenLocation(marker.getPosition());
// Make a copy of the MotionEvent and adjust it's location
// so it is relative to the infoWindow left top corner
MotionEvent copyEv = MotionEvent.obtain(ev);
copyEv.offsetLocation(
-point.x + (infoWindow.getWidth() / 2),
-point.y + infoWindow.getHeight() + bottomOffsetPixels);
// Dispatch the adjusted MotionEvent to the infoWindow
ret = infoWindow.dispatchTouchEvent(copyEv);
}
// If the infoWindow consumed the touch event, then just return true.
// Otherwise pass this event to the super class and return it's result
return ret || super.dispatchTouchEvent(ev);
}
}
All this will make the views inside the InfoView "live" again - the OnClickListeners will start triggering etc.
Second part: The remaining problem is, that obviously, you can't see any UI changes of your InfoWindow on screen. To do that you have to manually call Marker.showInfoWindow. Now, if you perform some permanent change in your InfoWindow (like changing the label of your button to something else), this is good enough.
But showing a button pressed state or something of that nature is more complicated. The first problem is, that (at least) I wasn't able to make the InfoWindow show normal button's pressed state. Even if I pressed the button for a long time, it just remained unpressed on the screen. I believe this is something that is handled by the map framework itself which probably makes sure not to show any transient state in the info windows. But I could be wrong, I didn't try to find this out.
What I did is another nasty hack - I attached an OnTouchListener
to the button and manually switched it's background when the button was pressed or released to two custom drawables - one with a button in a normal state and the other one in a pressed state. This is not very nice, but it works :). Now I was able to see the button switching between normal to pressed states on the screen.
There is still one last glitch - if you click the button too fast, it doesn't show the pressed state - it just remains in its normal state (although the click itself is fired so the button "works"). At least this is how it shows up on my Galaxy Nexus. So the last thing I did is that I delayed the button in it's pressed state a little. This is also quite ugly and I'm not sure how would it work on some older, slow devices but I suspect that even the map framework itself does something like this. You can try it yourself - when you click the whole InfoWindow, it remains in a pressed state a little longer, then normal buttons do (again - at least on my phone). And this is actually how it works even on the original Google Maps app.
Anyway, I wrote myself a custom class which handles the buttons state changes and all the other things I mentioned, so here is the code:
package com.circlegate.tt.cg.an.lib.map;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import com.google.android.gms.maps.model.Marker;
public abstract class OnInfoWindowElemTouchListener implements OnTouchListener {
private final View view;
private final Drawable bgDrawableNormal;
private final Drawable bgDrawablePressed;
private final Handler handler = new Handler();
private Marker marker;
private boolean pressed = false;
public OnInfoWindowElemTouchListener(View view, Drawable bgDrawableNormal, Drawable bgDrawablePressed) {
this.view = view;
this.bgDrawableNormal = bgDrawableNormal;
this.bgDrawablePressed = bgDrawablePressed;
}
public void setMarker(Marker marker) {
this.marker = marker;
}
@Override
public boolean onTouch(View vv, MotionEvent event) {
if (0 <= event.getX() && event.getX() <= view.getWidth() &&
0 <= event.getY() && event.getY() <= view.getHeight())
{
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: startPress(); break;
// We need to delay releasing of the view a little so it shows the pressed state on the screen
case MotionEvent.ACTION_UP: handler.postDelayed(confirmClickRunnable, 150); break;
case MotionEvent.ACTION_CANCEL: endPress(); break;
default: break;
}
}
else {
// If the touch goes outside of the view's area
// (like when moving finger out of the pressed button)
// just release the press
endPress();
}
return false;
}
private void startPress() {
if (!pressed) {
pressed = true;
handler.removeCallbacks(confirmClickRunnable);
view.setBackground(bgDrawablePressed);
if (marker != null)
marker.showInfoWindow();
}
}
private boolean endPress() {
if (pressed) {
this.pressed = false;
handler.removeCallbacks(confirmClickRunnable);
view.setBackground(bgDrawableNormal);
if (marker != null)
marker.showInfoWindow();
return true;
}
else
return false;
}
private final Runnable confirmClickRunnable = new Runnable() {
public void run() {
if (endPress()) {
onClickConfirmed(view, marker);
}
}
};
/**
* This is called after a successful click
*/
protected abstract void onClickConfirmed(View v, Marker marker);
}
Here is a custom InfoWindow layout file that I used:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginRight="10dp" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Title" />
<TextView
android:id="@+id/snippet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="snippet" />
</LinearLayout>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Test activity layout file (MapFragment
being inside the MapWrapperLayout
):
<com.circlegate.tt.cg.an.lib.map.MapWrapperLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map_relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</com.circlegate.tt.cg.an.lib.map.MapWrapperLayout>
And finally source code of a test activity, which glues all this together:
package com.circlegate.testapp;
import com.circlegate.tt.cg.an.lib.map.MapWrapperLayout;
import com.circlegate.tt.cg.an.lib.map.OnInfoWindowElemTouchListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton;
private OnInfoWindowElemTouchListener infoButtonListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
final GoogleMap map = mapFragment.getMap();
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.info_window, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button)infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
getResources().getDrawable(R.drawable.btn_default_pressed_holo_light))
{
@Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
// Let's add a couple of markers
map.addMarker(new MarkerOptions()
.title("Prague")
.snippet("Czech Republic")
.position(new LatLng(50.08, 14.43)));
map.addMarker(new MarkerOptions()
.title("Paris")
.snippet("France")
.position(new LatLng(48.86,2.33)));
map.addMarker(new MarkerOptions()
.title("London")
.snippet("United Kingdom")
.position(new LatLng(51.51,-0.1)));
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
}
That's it. So far I only tested this on my Galaxy Nexus (4.2.1) and Nexus 7 (also 4.2.1), I will try it on some Gingerbread phone when I have a chance. A limitation I found so far is that you can't drag the map from where is your button on the screen and move the map around. It could probably be overcome somehow but for now, I can live with that.
I know this is an ugly hack but I just didn't find anything better and I need this design pattern so badly that this would really be a reason to go back to the map v1 framework (which btw. I would really really like to avoid for a new app with fragments etc.). I just don't understand why Google doesn't offer developers some official way to have a button on InfoWindows. It's such a common design pattern, moreover this pattern is used even in the official Google Maps app :). I understand the reasons why they can't just make your views "live" in the InfoWindows - this would probably kill performance when moving and scrolling map around. But there should be some way how to achieve this effect without using views.
This one worked, double quotes when $user and $password are outside single quotes. Single quotes when inside a single quote statement.
mysql --user="$user" --password="$password" --database="$user" --execute='DROP DATABASE '$user'; CREATE DATABASE '$user';'
Here's how i'd do it
<select id="urlSelect" onchange="window.location = jQuery('#urlSelect option:selected').val();">
<option value="http://www.yadayadayada.com">Great Site</option>
<option value="http://www.stackoverflow.com">Better Site</option>
</select>
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
You have to pass the CultureInfo to get the result with slash(/)
DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
As postman chrome app has deprecated so, Postman Native app is available to support native plateforms. You can install Postman on Linux/Ubuntu via the Snap store using the command in terminal.
$ snap install postman
After successful installation you can find this in your applications list.
Node : http://www.w3schools.com/js/js_htmldom_nodes.asp
The Node object represents a single node in the document tree. A node can be an element node, an attribute node, a text node, or any other of the node types explained in the Node Types chapter.
Element : http://www.w3schools.com/js/js_htmldom_elements.asp
The Element object represents an element in an XML document. Elements may contain attributes, other elements, or text. If an element contains text, the text is represented in a text-node.
duplicate :
I combined some beautiful answers here to make it possible to easily support more Expression operators.
This is based on the answer of @Dejan but now it's quite easy to add the OR as well. I chose not to make the Combine
function public, but you could do that to be even more flexible.
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.AndAlso);
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.Or);
public static Expression<Func<T, bool>> Combine<T>(Expression<Func<T, bool>> leftExpression, Expression<Func<T, bool>> rightExpression, Func<Expression, Expression, BinaryExpression> combineOperator)
{
var leftParameter = leftExpression.Parameters[0];
var rightParameter = rightExpression.Parameters[0];
var visitor = new ReplaceParameterVisitor(rightParameter, leftParameter);
var leftBody = leftExpression.Body;
var rightBody = visitor.Visit(rightExpression.Body);
return Expression.Lambda<Func<T, bool>>(combineOperator(leftBody, rightBody), leftParameter);
}
private class ReplaceParameterVisitor : ExpressionVisitor
{
private readonly ParameterExpression _oldParameter;
private readonly ParameterExpression _newParameter;
public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
{
_oldParameter = oldParameter;
_newParameter = newParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return ReferenceEquals(node, _oldParameter) ? _newParameter : base.VisitParameter(node);
}
}
}
Usage is not changed and still like this:
Expression<Func<Result, bool>> noFilterExpression = item => filters == null;
Expression<Func<Result, bool>> laptopFilterExpression = item => item.x == ...
Expression<Func<Result, bool>> dateFilterExpression = item => item.y == ...
var combinedFilterExpression = noFilterExpression.Or(laptopFilterExpression.AndAlso(dateFilterExpression));
efQuery.Where(combinedFilterExpression);
(This is an example based on my actual code, but read is as pseudo-code)
To install version 7+ of Babel run:
npm install -g @babel/cli
npm install -g @babel/core
It looks like you might not have defined a start
script in your package.json
file or your project does not contain a server.js
file.
If there is a server.js file in the root of your package, then npm will default the start command to node server.js.
https://docs.npmjs.com/misc/scripts#default-values
You could either change the name of your application script to server.js
or add the following to your package.json
"scripts": {
"start": "node your-script.js"
}
Or ... you could just run node your-script.js
directly
When I run maven test, java.lang.OutOfMemoryError happens. I google it for solutions and have tried to export MAVEN_OPTS=-Xmx1024m, but it did not work.
Setting the Xmx
options using MAVEN_OPTS
does work, it does configure the JVM used to start Maven. That being said, the maven-surefire-plugin forks a new JVM by default, and your MAVEN_OPTS
are thus not passed.
To configure the sizing of the JVM used by the maven-surefire-plugin, you would either have to:
forkMode
to never
(which is be a not so good idea because Maven won't be isolated from the test) ~or~ argLine
parameter (the right way):In the later case, something like this:
<configuration>
<argLine>-Xmx1024m</argLine>
</configuration>
But I have to say that I tend to agree with Stephen here, there is very likely something wrong with one of your test and I'm not sure that giving more memory is the right solution to "solve" (hide?) your problem.
For future reference, the above code does not work with Python 3. For Python 3, the D.keys()
needs to be converted to a list.
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
There isn't one, at least, not unless you are using a "developer" tool of some kind in your browser, e.g. Firebug in Firefox or the Developer tools in Safari. Then you can usually use console.log
.
If I'm doing something in, say, an iOS device, I might add a <div id="debug" />
and then log to it.
Just loop through all the <strong>
tags and use next_sibling
to get what you want. Like this:
for strong_tag in soup.find_all('strong'):
print(strong_tag.text, strong_tag.next_sibling)
Demo:
from bs4 import BeautifulSoup
html = '''
<p>
<strong class="offender">YOB:</strong> 1987<br />
<strong class="offender">RACE:</strong> WHITE<br />
<strong class="offender">GENDER:</strong> FEMALE<br />
<strong class="offender">HEIGHT:</strong> 5'05''<br />
<strong class="offender">WEIGHT:</strong> 118<br />
<strong class="offender">EYE COLOR:</strong> GREEN<br />
<strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
'''
soup = BeautifulSoup(html)
for strong_tag in soup.find_all('strong'):
print(strong_tag.text, strong_tag.next_sibling)
This gives you:
YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN
The @RequestParam String action
suggests there is a parameter present within the request with the name action which is absent in your form. You must either:
<input name="action" />
false
within the @RequestParam
e.g. @RequestParam(required=false)
EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday
I found this a while back when learning python
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
# create figure window
gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns
ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]
ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)
fig.add_subplot(ax) #add 'ax' to figure
you can make different sizes in one figure as well, use slices in that case:
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns
consult the docs for more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)
Put all the files (html and resources)in a directory (for my "manual"). Next, drag and drop the directory to XCode, over "Supporting Files". You should check the options "Copy Items if needed" and "Create folder references". Next, write a simple code:
NSURL *url = [[NSBundle mainBundle] URLForResource:@"manual/index" withExtension:@"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];
Attention to @"manual/index"
, manual is the name of my directory!!
It's all!!!! Sorry for my bad english...
=======================================================================
Hola desde Costa Rica. Ponga los archivos (html y demás recursos) en un directorio (en mi caso lo llamé manual), luego, arrastre y suelte en XCode, sobre "Supporting Files". Usted debe seleccionar las opciones "Copy Items if needed" y "Create folder references".
NSURL *url = [[NSBundle mainBundle] URLForResource:@"manual/index" withExtension:@"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];
Presta atención a @"manual/index"
, manual es el nombre de mi directorio!!
print('\007')
Plays the bell sound on Linux. Plays the error sound on Windows 10.
Complete java converter code for all primitive types to/from arrays http://www.daniweb.com/code/snippet216874.html
dtypes is a Pandas Series. That means it contains index & values attributes. If you only need the column names:
headers = df.dtypes.index
it will return a list containing the column names of "df" dataframe.
There is already a command in the ssh suite to do this automatically for you. I.e log into a remote host and add the public key to that computers authorized_keys file.
ssh-copy-id -i /path/to/key/file [email protected]
If the key you are installing is ~/.ssh/id_rsa
then you can even drop the -i
flag completely.
Much better than manually doing it!
You should use sendfile apis given by popular servers like apache
or nginx
in production. Many years i was using sendfile api of these servers for protecting files. Then created a simple middleware based django app for this purpose suitable for both development & production purpose.You can access the source code here.
UPDATE: in new version python
provider uses django FileResponse
if available and also adds support for many server implementations from lighthttp, caddy to hiawatha
Usage
pip install django-fileprovider
fileprovider
app to INSTALLED_APPS
settings,fileprovider.middleware.FileProviderMiddleware
to MIDDLEWARE_CLASSES
settingsFILEPROVIDER_NAME
settings to nginx
or apache
in production, by default it is python
for development purpose.in your classbased or function views set response header X-File
value to absolute path to the file. For example,
def hello(request):
// code to check or protect the file from unauthorized access
response = HttpResponse()
response['X-File'] = '/absolute/path/to/file'
return response
django-fileprovider
impemented in a way that your code will need only minimum modification.
Nginx configuration
To protect file from direct access you can set the configuration as
location /files/ {
internal;
root /home/sideffect0/secret_files/;
}
Here nginx
sets a location url /files/
only access internaly, if you are using above configuration you can set X-File as,
response['X-File'] = '/files/filename.extension'
By doing this with nginx configuration, the file will be protected & also you can control the file from django views
I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with
block, and then it stopped happening.
public <E> List<E> collectionToList(Collection<E> collection)
{
return (collection instanceof List) ? (List<E>) collection : new ArrayList<E>(collection);
}
Use the above method for converting the collection to list
This C# code is to fetch all items from a dynamodb table using BatchGet or CreateBatchGet
string tablename = "AnyTableName"; //table whose data you want to fetch
var BatchRead = ABCContext.Context.CreateBatchGet<ABCTable>(
new DynamoDBOperationConfig
{
OverrideTableName = tablename;
});
foreach(string Id in IdList) // in case you are taking string from input
{
Guid objGuid = Guid.Parse(Id); //parsing string to guid
BatchRead.AddKey(objGuid);
}
await BatchRead.ExecuteAsync();
var result = BatchRead.Results;
// ABCTable is the table modal which is used to create in dynamodb & data you want to fetch
You have to add Imports System.Runtime.InteropServices
to the top of your source file.
Alternatively, you can fully qualify attribute name:
<System.Runtime.InteropService.DllImport("user32.dll", _
SetLastError:=True, CharSet:=CharSet.Auto)> _
A simple (but not very fast) method to calculate the square root of X:
squareroot(x)
if x<0 then Error
a = 1
b = x
while (abs(a-b)>ErrorMargin)
a = (a+b)/2
b = x/a
endwhile
return a;
Example: squareroot(70000)
a b
1 70000
35001 2
17502 4
8753 8
4381 16
2199 32
1116 63
590 119
355 197
276 254
265 264
As you can see it defines an upper and a lower boundary for the square root and narrows the boundary until its size is acceptable.
There are more efficient methods but this one illustrates the process and is easy to understand.
Just beware to set the Errormargin to 1 if using integers else you have an endless loop.
Just omit the [Required] attribute from the string somefield
property. This will make it create a NULL
able column in the db.
To make int types allow NULLs in the database, they must be declared as nullable ints in the model:
// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }
// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }
TestFlight seems to be able to extract the UDID once the user signs up:
I have used an emulator for API Level 23, which does not take keyboard input for installed apk. So I have created new emulator for API Level 29, and then it works. Following is the step to install new emulator.
Regarding the width and height:
var img = document.getElementById('imageId');
var width = img.clientWidth;
var height = img.clientHeight;
Regarding the filesize you can use performance
var size = performance.getEntriesByName(url)[0];
console.log(size.transferSize); // or decodedBodySize might differ if compression is used on server side
As stated by Levon, this is not mandatory as stated in the docs: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
This is probably either an habit from other languages that don't guarantee primitive data types default values.
For posterity....I figured out how to get what I needed. Here it is in case it might be useful to somebody else.
$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
$aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
$alist += $aline
}
$alist | Out-File D:\Temp\ADUsers.csv
Whenever I find myself at your place, I use the following command line:
git log -S "<words/phrases i am trying to find>" --all --oneline --graph
Explanation:
git log
- Need I write more here; it shows the logs in chronological order.-S "<words/phrases i am trying to find>"
- It shows all those Git commits where any file (added/modified/deleted) has the words/phrases I am trying to find without '<>' symbols.--all
- To enforce and search across all the branches.--oneline
- It compresses the Git log in one line.--graph
- It creates the graph of chronologically ordered commits.when using varchar values SQL Server needs an additional 2 bytes per row to store some info about that column whereas if you use char it doesn't need that so unless you
Actually, there are four forms of this operator:
<>
!=
^=
and even
¬= -- worked on some obscure platforms in the dark ages
which are the same, but treated differently when a verbatim match is required (stored outlines or cached queries).
Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).
I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:
sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF
Nobody seems to have mentioned the -t option but that the easiest:
pip install -t <direct directory> <package>
Would something like
(pattern.*?(pattern))*
work for you?
Edit:
The problem with this is that it uses the non-greedy operator *?
, which can require an awful lot of backtracking along the string instead of just looking at each letter once. What this means for you is that this could be slow for large gaps.
using dynamic variable in C# is the simplest.
Newtonsoft.Json.Linq has class JValue that can be used. Below is a sample code which displays Question id and text from the JSON string you have.
string jsonString = "[{\"Question\":{\"QuestionId\":49,\"QuestionText\":\"Whats your name?\",\"TypeId\":1,\"TypeName\":\"MCQ\",\"Model\":{\"options\":[{\"text\":\"Rahul\",\"selectedMarks\":\"0\"},{\"text\":\"Pratik\",\"selectedMarks\":\"9\"},{\"text\":\"Rohit\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":true,\"selectedOption\":\"1\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"02\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"\",\"S8\":\"\",\"S9\":\"Pratik\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"},{\"Question\":{\"QuestionId\":51,\"QuestionText\":\"Are you smart?\",\"TypeId\":3,\"TypeName\":\"True-False\",\"Model\":{\"options\":[{\"text\":\"True\",\"selectedMarks\":\"7\"},{\"text\":\"False\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":false,\"selectedOption\":\"3\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"01\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"True\",\"S8\":\"\",\"S9\":\"\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"}]";
dynamic myObject = JValue.Parse(jsonString);
foreach (dynamic questions in myObject)
{
Console.WriteLine(questions.Question.QuestionId + "." + questions.Question.QuestionText.ToString());
}
Console.Read();
For larger form instead of writing css classed for every field you could to this
class UserRegistration(forms.ModelForm):
# list charfields
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2')
def __init__(self, *args, **kwargs):
super(UserRegistration, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs['class'] = 'form-control'
To remove all child elements from your div:
$('#mysweetdiv').empty();
.removeData()
and the corresponding .data()
function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:
var $li = $('<li>Joe</li>').data('id', 25);
Look at my version :)
- (void)keyboardWasShown:(NSNotification *)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGRect bkgndRect = cellSelected.superview.frame;
bkgndRect.size.height += kbSize.height;
[cellSelected.superview setFrame:bkgndRect];
[tableView setContentOffset:CGPointMake(0.0, cellSelected.frame.origin.y-kbSize.height) animated:YES];
}
- (void)keyboardWasHidden:(NSNotification *)aNotification
{
[tableView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
}
First, we must make a distinction between layers and tiers. Layers are the way to logically break code into components and tiers are the physical nodes to place the components on. This question explains it better: What's the difference between "Layers" and "Tiers"?
A two layer architecture is usually just a presentation layer and data store layer. These can be on 1 tier (1 machine) or 2 tiers (2 machines) to achieve better performance by distributing the work load.
A three layer architecture usually puts something between the presentation and data store layers such as a business logic layer or service layer. Again, you can put this into 1,2, or 3 tiers depending on how much money you have for hardware and how much load you expect.
Putting multiple machines in a tier will help with the robustness of the system by providing redundancy.
Below is a good example of a layered architecture:
(source: microsoft.com)
A good reference for all of this can be found here on MSDN: http://msdn.microsoft.com/en-us/library/ms978678.aspx
There are lots of explanation of Jmeter Summary, I have been using this tool from quite some time for generating performance testing report with relevant data. The explanation available on below link is right from the field experience:
Jmeter:Understanding Summary Report
This is one of the most useful report generated by Jmeter to undertstand the load test result.
# Label: Name of HTTP sample request send to server
# Samples : This Captures the total number of samples pushed to server. Suppose you put a Loop Controller to run it 5 times this particular request and then 2 iteration(Called Loop Count in Thread Group)is set and load test is run for 100 users, then the count that will be displayed here .... 1*5*2 * 100 =1000. Total = total number of samples send to server during entire run.
# Average : It's an average response time for a particular http request. This response time is in millisecond, and an average for 5 loops in two iteration for 100 users. Total = Average of total average of samples, means add all averages for all samples and divide by number of samples
# Min : Minmum time spend by sample requests send for this label. The total equals to the minimum time across all samples.
# Max : Maximum tie spend by sample requests send for this label The total equals to the maxmimum time across all samples.
# Std. Dev. : Knowing the standard deviation of your data set tells you how densely the data points are clustered around the mean. The smaller the standard deviation, the more consistent the data. Standard deviation should be less than or equal to half of the average time for a label. If it is more than that, then it means that something is wrong. you need to figure out the problem and fix it. https://en.wikipedia.org/wiki/Standard_deviation Total is euqals to highest deviation across all samples.
# Error: Total percentage of erros found for a particular sample request. 0.0% shows that all requests completed successfully. Total equals to percentage of errors samples in all samples (Total Samples)
# Throughput: Hits/sec, or total number of request per unit of time(sec, mins, hr) send to server during test.
endTime = lastSampleStartTime + lastSampleLoadTime startTime = firstSampleStartTime converstion = unit time conversion value Throughput = Numrequests / ((endTime - startTime)*conversion)
# KB/sec : Its mesuring throughput rate in Kilobytes per second.
# Avg. Bytes: Avegare of total bytes of data downloaded from server. Totals is average bytes across all samples.
Kotlin Users,
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
}
})
Update 2020 for ViewPager2
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrollStateChanged(state: Int) {
println(state)
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
println(position)
}
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
println(position)
}
})
For a semantic web approach, you could run a sparql query against WordNet in RDF format. Basically just use urllib module to issue GET request and return results in JSON format, parse using python 'json' module. If it's not English word you'll get no results.
As another idea, you could query Wiktionary's API.
Try: localhost:8080/phpmyadmin/
In visual studio 2012, When I published the solution mistakenly with 'debug' option I got this exception. With 'release' option it never occurred. Hope it helps.
An alternative solution would be to use some sort of regex
:
for example:
String s = "apple car 04:48 05:18 05:46 06:16 06:46 07:16 07:46 16:46 17:16 17:46 18:16 18:46 19:16";
String results= s.replaceAll("[0-9]", "").replaceAll(" :", ""); //first removing all the numbers then remove space followed by :
System.out.println(results); // output 9
System.out.println(results.length());// output "apple car"
Set LoginBehavior if you have installed facebook app in your phone
loginButton.setLoginBehavior(LoginBehavior.WEB_ONLY);
This is the function that I use for this calculation:
public static int binlog( int bits ) // returns 0 for bits=0
{
int log = 0;
if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
if( bits >= 256 ) { bits >>>= 8; log += 8; }
if( bits >= 16 ) { bits >>>= 4; log += 4; }
if( bits >= 4 ) { bits >>>= 2; log += 2; }
return log + ( bits >>> 1 );
}
It is slightly faster than Integer.numberOfLeadingZeros() (20-30%) and almost 10 times faster (jdk 1.6 x64) than a Math.log() based implementation like this one:
private static final double log2div = 1.000000000001 / Math.log( 2 );
public static int log2fp0( int bits )
{
if( bits == 0 )
return 0; // or throw exception
return (int) ( Math.log( bits & 0xffffffffL ) * log2div );
}
Both functions return the same results for all possible input values.
Update:
The Java 1.7 server JIT is able to replace a few static math functions with alternative implementations based on CPU intrinsics. One of those functions is Integer.numberOfLeadingZeros(). So with a 1.7 or newer server VM, a implementation like the one in the question is actually slightly faster than the binlog
above. Unfortunatly the client JIT doesn't seem to have this optimization.
public static int log2nlz( int bits )
{
if( bits == 0 )
return 0; // or throw exception
return 31 - Integer.numberOfLeadingZeros( bits );
}
This implementation also returns the same results for all 2^32 possible input values as the the other two implementations I posted above.
Here are the actual runtimes on my PC (Sandy Bridge i7):
JDK 1.7 32 Bits client VM:
binlog: 11.5s
log2nlz: 16.5s
log2fp: 118.1s
log(x)/log(2): 165.0s
JDK 1.7 x64 server VM:
binlog: 5.8s
log2nlz: 5.1s
log2fp: 89.5s
log(x)/log(2): 108.1s
This is the test code:
int sum = 0, x = 0;
long time = System.nanoTime();
do sum += log2nlz( x ); while( ++x != 0 );
time = System.nanoTime() - time;
System.out.println( "time=" + time / 1000000L / 1000.0 + "s -> " + sum );
You should use the ClearContents method if you want to clear the content but preserve the formatting.
Worksheets("Sheet1").Range("A1:G37").ClearContents
Yes, it is absolutely no problem. You could even have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.
In fact, i have such a setup myself.
Simply remove "DEFINER=your user name
@localhost
" and run the SQL from phpmyadminwill works fine.
Another way:
x=$'Some\nstring'
readarray -t y <<<"$x"
Or, if you don't have bash 4, the bash 3.2 equivalent:
IFS=$'\n' read -rd '' -a y <<<"$x"
You can also do it the way you were initially trying to use:
y=(${x//$'\n'/ })
This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'
. To make it work, you need to restrict the word separator before parsing it:
IFS=$'\n' y=(${x//$'\n'/ })
...and then, since you are changing the separator, you don't need to convert the \n
to space
anymore, so you can simplify it to:
IFS=$'\n' y=($x)
This approach will function unless $x
contains a matching globbing pattern (such as "*
") - in which case it will be replaced by the matched file name(s). The read
/readarray
methods require newer bash versions, but work in all cases.
You can use the slice operator like this:
l = [1,2,3,4,5]
l2 = l[::2] # get subsequent 2nd item
I have 2 solutions to resolve your problem
ngDoCheck
to detect object
data changed or not object
to a new memory address by object = Object.create(object)
from parent component.As another option, you can do look ups like:
class UserAdmin(admin.ModelAdmin):
list_display = (..., 'get_author')
def get_author(self, obj):
return obj.book.author
get_author.short_description = 'Author'
get_author.admin_order_field = 'book__author'
Here are the steps:
--> Follow the path: {tomcat directory>/conf -->Find this line:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
change portnumber from "8080" to "80".
--> Save the file.
--> Restart the server :)
I would argue that both
let str = String(format:"%d, %f, %ld", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE)
and
let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE)"
are both acceptable since the user asked about formatting and both cases fit what they are asking for:
I need to create a string with format which can convert int, long, double etc. types into string.
Obviously the former allows finer control over the formatting than the latter, but that does not mean the latter is not an acceptable answer.
If you just want to clobber all of the instances of a substring out of a string without using regex you can using:
var replacestring = "A B B C D"
const oldstring = "B";
const newstring = "E";
while (replacestring.indexOf(oldstring) > -1) {
replacestring = replacestring.replace(oldstring, newstring);
}
//result: "A E E C D"
Yes, it is absolutely possible to get the cookie from domain1.com by domain2.com. I had the same problem for a social plugin of my social network, and after a day of research I found the solution.
First, on the server side you need to have the following headers:
header("Access-Control-Allow-Origin: http://origin.domain:port");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type, *");
Within the PHP-file you can use $_COOKIE[name]
Second, on the client side:
Within your ajax request you need to include 2 parameters
crossDomain: true
xhrFields: { withCredentials: true }
Example:
type: "get",
url: link,
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
}
I've had success putting text within span tags and then setting vertical-align: middle on that span. Don't know how cross-browser compliant this is though, I've only tested it in webkit browsers.
Use MyEnum enumValue = MyEnum.values()[x];
matcher.find()
does not find all matches, only the next match.
long matches = matcher.results().count();
You'll have to do the following. (Starting from Java 9, there is a nicer solution)
int count = 0;
while (matcher.find())
count++;
Btw, matcher.groupCount()
is something completely different.
Complete example:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
String hello = "HelloxxxHelloxxxHello";
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher(hello);
int count = 0;
while (matcher.find())
count++;
System.out.println(count); // prints 3
}
}
When counting matches of aa
in aaaa
the above snippet will give you 2.
aaaa
aa
aa
To get 3 matches, i.e. this behavior:
aaaa
aa
aa
aa
You have to search for a match at index <start of last match> + 1
as follows:
String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);
int count = 0;
int i = 0;
while (matcher.find(i)) {
count++;
i = matcher.start() + 1;
}
System.out.println(count); // prints 3
This much code works down for me when using angular 4 as the client side and PHP as the server side.
header("Access-Control-Allow-Origin: *");
Kotlin Style way to do this more simple (example):
isVisible = false
Complete example:
if (some_data_array.details == null){
holder.view.some_data_array.isVisible = false}
You can use NSDate's method - (id)dateByAddingTimeInterval:(NSTimeInterval)seconds
where seconds
would be 60 * 60 * 24 = 86400
You can use reduce
which works in all browser except IE8 and lower.
["20","40","80","400"].reduce(function(a, b) {
return parseInt(a, 10) + parseInt(b, 10);
})
Normally that error occurs when a }
was missed somewhere in the code, for example:
void mi_start_curr_serv(void){
#if 0
//stmt
#endif
would fail with this error due to the missing }
at the end of the function. The code you posted doesn't have this error, so it is likely coming from some other part of your source.
ObservableCollection<FacebookUser_WallFeed> result = new ObservableCollection<FacebookUser_WallFeed>(FacebookHelper.facebookWallFeeds);
Have you installed any product of SQL in your system machine ? You can download and install "ODBC Driver 13(or any version) for SQL Server" and try to run if you havent alerady done.
Sometimes it can be dangerous to convert charsets, specially on databases with huge amounts of data. I think the best option is to use the "binary" operator:
e.g : WHERE binary table1.column1 = binary table2.column1
First open a console then cd to where you've downloaded your file like some-package.whl and use
pip install some-package.whl
Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. I have multiple Python installations, and needed to use the pip associated with Python 3 to install a version 3 wheel.
If pip is not installed, and you are using Windows: How to install pip on Windows?
Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable
using(var context = new ItemEntities())
{
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate);
}
That approach is fine, but if you wanted it straight into a List Object:
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate).ToList();
All you have to do is append a .ToList() call to the end of the Query.
Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.
Here's one way. You have to get the individual components from the date object (day, month & year) and then build and format the string however you wish.
n = new Date();_x000D_
y = n.getFullYear();_x000D_
m = n.getMonth() + 1;_x000D_
d = n.getDate();_x000D_
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
_x000D_
<p id="date"></p>
_x000D_
Most easiest way
I can see the question is answered , I'm giving this answer for the ones who is having this question in future
Its not good practise to code inline css , and also ID for all inner div's , always try to use class for styling .Using inline css is a very bad practise if you are trying to be a professional web designer.
here in your question I have given a wrapper class for the parent div and all the inside div's are child div's in css you can call inner div's using nth-child selector.
I want to point few things here
1 - Do not use inline css ( it is very bad practise )
2 - Try to use classes instead of id's because if you give an id you can use it only once, but if you use a class you can use it many times and also you can style of them using that class so you write less code.
codepen link for my answer
https://codepen.io/feizel/pen/JELGyB
_x000D_
_x000D_
.wrapper{width:100%;}_x000D_
.box{float:left; height:100px;}_x000D_
.box:nth-child(1){_x000D_
width:25%;_x000D_
background-color:red; _x000D_
_x000D_
}_x000D_
.box:nth-child(2){_x000D_
width:50%;_x000D_
background-color:green; _x000D_
}_x000D_
.box:nth-child(3){_x000D_
width:25%;_x000D_
background-color:yellow; _x000D_
}
_x000D_
_x000D_
<div class="wrapper">_x000D_
<div class="box">_x000D_
Left Side Menu_x000D_
</div>_x000D_
<div class="box">_x000D_
Random Content_x000D_
</div>_x000D_
<div class="box">_x000D_
Right Side Menu_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
I got the same error in this case:
var result = Db.SystemLog
.Where(log =>
eventTypeValues.Contains(log.EventType)
&& (
search.Contains(log.Id.ToString())
|| log.Message.Contains(search)
|| log.PayLoad.Contains(search)
|| log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)
)
)
.OrderByDescending(log => log.Id)
.Select(r => r);
After spending way too much time debugging, I figured out that error appeared in the logic expression.
The first line search.Contains(log.Id.ToString())
does work fine, but the last line that deals with a DateTime object made it fail miserably:
|| log.Timestamp.ToString(CultureInfo.CurrentUICulture).Contains(search)
Remove the problematic line and problem solved.
I do not fully understand why, but it seems as ToString() is a LINQ expression for strings, but not for Entities. LINQ for Entities deals with database queries like SQL, and SQL has no notion of ToString(). As such, we can not throw ToString() into a .Where() clause.
But how then does the first line work? Instead of ToString(), SQL have CAST
and CONVERT
, so my best guess so far is that linq for entities uses that in some simple cases. DateTime objects are not always found to be so simple...
TRY THIS ONE
mysql_connect('localhost','dbuser','dbpass');
$query = "SELECT username FROM Users WHERE username='".$username."'";
mysql_select_db('dbname');
$result=mysql_query($query);
if (mysql_num_rows($query) != 0)
{
echo "Username already exists";
}
else
{
...
}
If you just want to convert a relative path with optional parameters I created an extension method for IHttpContextAccessor
public static string AbsoluteUrl(this IHttpContextAccessor httpContextAccessor, string relativeUrl, object parameters = null)
{
var request = httpContextAccessor.HttpContext.Request;
var url = new Uri(new Uri($"{request.Scheme}://{request.Host.Value}"), relativeUrl).ToString();
if (parameters != null)
{
url = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(url, ToDictionary(parameters));
}
return url;
}
private static Dictionary<string, string> ToDictionary(object obj)
{
var json = JsonConvert.SerializeObject(obj);
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
You can then call the method from your service/view using the injected IHttpContextAccessor
var callbackUrl = _httpContextAccessor.AbsoluteUrl("/Identity/Account/ConfirmEmail", new { userId = applicationUser.Id, code });
Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?
A common mistake is also not to leave a space after and before the square brackets.
Setting export SSL_CERT_FILE=/path/file.crt
should do the job.
There are two different Gradle applications in your system.
the system-wide Gradle
This application is invoked by gradle (arguments)
.
the gradle-wrapper
The gradle-wrapper is specific to every project and can only be invoked inside the project's directory, using the command ./gradlew (arguments)
.
Your system-wide gradle version is 5.1.1 (as the OP explained in the comments, running the command gradle --version
returned version 5.1.1).
However, the failure is the result of a call to the gradle-wrapper (./gradlew
). Could you check your project's gradle wrapper version? To do that, execute ./gradlew --version
inside your project's folder, in the directory where the gradlew and gradlew.bat files are.
Update 1:
As running ./gradlew --version
failed, you can manually check your wrapper's version by opening the file:
(project's root folder)/gradle/wrapper/gradle-wrapper.properties
with a simple text editor. The "distributionUrl" inside should tell us what the wrapper's version is.
Update 2:
As per the OP's updated question, the gradle-wrapper's version is 4.1RC1.
Gradle added support for JDK 11 in Gradle 5.0. Hence since 4.1RC does not support running on JDK 11 this is definitely a problem.
The obvious way, would be to update your project's gradle-wrapper to version 5.0.
However, before updating, try running gradle app:installDebug
. This will use your system-wide installed Gradle whose version is 5.1.1 and supports running on Java 11. If this works, then your buildscript (file build.gradle) is not affected by any breaking changes between v.4.1RC1 and v.5.1.1 and you can then update your wrapper by executing from the command line inside your project's folder: gradle wrapper --gradle-version=5.1.1
[*].
If gradle app:installDebug
fails to execute correctly, then maybe you need to upgrade your Gradle buildscript. For updating from v.4.1RC1 to 5.1.1, the Gradle project provides a guide (1, 2) with breaking changes and deprecated features between minor releases, so that you can update gradually to the latest version.
Alternatively, if for some reason you can't or don't want to upgrade your Gradle buildscript, you can always choose to downgrade your Java version to one that Gradle 4.1RC1 supports running on.
[*] As correctly pointed out in the answer by @lupchiazoem, use gradle wrapper --gradle-version=5.1.1
(and not ./gradlew
as I had originally posted there by mistake). The reason is Gradle runs on Java. You can update your gradle-wrapper using any working Gradle distribution, either your system-wide installed Gradle or the gradle-wrapper itself. However, in this case your wrapper is not compatible with your installed Java version, so you do have to use the system-wide Gradle (aka gradle
and not ./gradlew
).
I solved this problem by creating separate asp.net ajax solution and copy and paste all ajax configuration from web.config to working project.
here are the must configuration you should set in web.config
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</configSections>
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</system.webServer>
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
You can also get the value by element's name attribute.
var message = $("#formId textarea[name=message]").val();
Is Arr
a base type of Obj
? Does the Obj class exist? Your code would work only if Arr is a base type of Obj. You can try this instead:
Obj[] myArray = objects.Select(o =>
{
var someLocalVar = o.someVar;
return new Obj()
{
Var1 = someLocalVar,
Var2 = o.var2
};
}).ToArray();
With the latter example you omit the struct keyword when using the structure. So everywhere in your code, you can write :
myStruct a;
instead of
struct myStruct a;
This save some typing, and might be more readable, but this is a matter of taste
The spec can be read as "ISO-8859-1" or "undefined". Your choice. It's known that many servers use ISO-8859-1 (like it or not) and will fail when you send something else.
For more information and a proposal to fix the situation, see http://greenbytes.de/tech/webdav/draft-reschke-basicauth-enc-latest.html
This works for me, even when run inside an included PHP file, and you want the filename of the current php file running:
$currentPage= $_SERVER["SCRIPT_NAME"];
$currentPage = substr($currentPage, 1);
echo $currentPage;
Result:
index.php
You can also use printf to pipe the input to your script.
var=val
printf "yes\nno\nmaybe\n$var\n" | ./your_script.sh
You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:
gcd_alg:
subl %ecx, %eax /* a = a - c */
cmpl $0, %eax /* if a == 0 */
je gcd_done /* jump to end */
cmpl %ecx, %eax /* if a < c */
jl gcd_preswap /* swap and start over */
jmp gcd_alg /* keep subtracting */
Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.
As for clearing the screen, that depends on the system you're using.
Try to use protocol relative links.
Your link is http://example.com/script.js, use:
<script src="//example.com/script.js" type="text/javascript"></script>
In this way, you can leave the scheme free (do not indicate the protocol in the links) and trust that the browser uses the protocol of the embedded Web page. If your users visit the HTTP version of your Web page, the script will be loaded over http:// and if your users visit the HTTPS version of your Web site, the script will be loaded over https://.
Seen in: https://developer.mozilla.org/es/docs/Seguridad/MixedContent/arreglar_web_con_contenido_mixto
Although the answer of Shane is really good, for one of my project I needed to remove the ouput messages, warnings and install packages automagically. I have finally managed to get this script:
InstalledPackage <- function(package)
{
available <- suppressMessages(suppressWarnings(sapply(package, require, quietly = TRUE, character.only = TRUE, warn.conflicts = FALSE)))
missing <- package[!available]
if (length(missing) > 0) return(FALSE)
return(TRUE)
}
CRANChoosen <- function()
{
return(getOption("repos")["CRAN"] != "@CRAN@")
}
UsePackage <- function(package, defaultCRANmirror = "http://cran.at.r-project.org")
{
if(!InstalledPackage(package))
{
if(!CRANChoosen())
{
chooseCRANmirror()
if(!CRANChoosen())
{
options(repos = c(CRAN = defaultCRANmirror))
}
}
suppressMessages(suppressWarnings(install.packages(package)))
if(!InstalledPackage(package)) return(FALSE)
}
return(TRUE)
}
Use:
libraries <- c("ReadImages", "ggplot2")
for(library in libraries)
{
if(!UsePackage(library))
{
stop("Error!", library)
}
}
Full sync has few tasks:
git reset HEAD --hard
git clean -f
git pull origin master
Or else, what I prefer is that, I may create a new branch with the latest from the remote using:
git checkout origin/master -b <new branch name>
origin is my remote repository reference, and master is my considered branch name. These may different from yours.
There it is : ternary operator got added to angular parser in 1.1.5! see the changelog
Here is a fiddle showing new ternary operator used in ng-class directive.
ng-class="boolForTernary ? 'blue' : 'red'"
You can also use GUAVA
and path escaper:
UrlEscapers.urlFragmentEscaper().escape(relativePath)
You have to define the compare first. There are 3 ways to do that:
It's easy to use class/struct because easy to declare just write this line of code above your executing code
struct compare{
public:
bool operator()(Node& a,Node& b) // overloading both operators
{
return a.w < b.w: // if you want increasing order;(i.e increasing for minPQ)
return a.w > b.w // if you want reverse of default order;(i.e decreasing for minPQ)
}
};
Calling code:
priority_queue<Node,vector<Node>,compare> pq;
Note, until now posted solutions only work for png and jpg!
If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack!
![alt text](test.gif "Title")
The IFormatProvider
interface is normally implemented for you by a CultureInfo
class, e.g.:
CultureInfo.CurrentCulture
CultureInfo.CurrentUICulture
CultureInfo.InvariantCulture
CultureInfo.CreateSpecificCulture("de-CA") //German (Canada)
The interface is a gateway for a function to get a set of culture-specific data from a culture. The two commonly available culture objects that an IFormatProvider
can be queried for are:
The way it would normally work is you ask the IFormatProvider
to give you a DateTimeFormatInfo
object:
DateTimeFormatInfo format;
format = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo));
if (format != null)
DoStuffWithDatesOrTimes(format);
There's also inside knowledge that any IFormatProvider
interface is likely being implemented by a class that descends from CultureInfo
, or descends from DateTimeFormatInfo
, so you could cast the interface directly:
CultureInfo info = provider as CultureInfo;
if (info != null)
format = info.DateTimeInfo;
else
{
DateTimeFormatInfo dtfi = provider as DateTimeFormatInfo;
if (dtfi != null)
format = dtfi;
else
format = (DateTimeFormatInfo)provider.GetFormat(typeof(DateTimeFormatInfo));
}
if (format != null)
DoStuffWithDatesOrTimes(format);
All that hard work has already been written for you:
To get a DateTimeFormatInfo
from an IFormatProvider
:
DateTimeFormatInfo format = DateTimeFormatInfo.GetInstance(provider);
To get a NumberFormatInfo
from an IFormatProvider
:
NumberFormatInfo format = NumberFormatInfo.GetInstance(provider);
The value of IFormatProvider
is that you create your own culture objects. As long as they implement IFormatProvider
, and return objects they're asked for, you can bypass the built-in cultures.
You can also use IFormatProvider
for a way of passing arbitrary culture objects - through the IFormatProvider
. E.g. the name of god in different cultures
This lets your custom LordsNameFormatInfo
class ride along inside an IFormatProvider
, and you can preserve the idiom.
In reality you will never need to call GetFormat
method of IFormatProvider
yourself.
Whenever you need an IFormatProvider
you can pass a CultureInfo
object:
DateTime.Now.ToString(CultureInfo.CurrentCulture);
endTime.ToString(CultureInfo.InvariantCulture);
transactionID.toString(CultureInfo.CreateSpecificCulture("qps-ploc"));
Note: Any code is released into the public domain. No attribution required.
Same thing, Just start the table name with #
or ##
:
CREATE TABLE #TemporaryTable -- Local temporary table - starts with single #
(
Col1 int,
Col2 varchar(10)
....
);
CREATE TABLE ##GlobalTemporaryTable -- Global temporary table - note it starts with ##.
(
Col1 int,
Col2 varchar(10)
....
);
Temporary table names start with #
or ##
- The first is a local temporary table and the last is a global temporary table.
Here is one of many articles describing the differences between them.
You don't need to create a binding datasource. If you want to apply sorting for all of your columns, here is a more generic solution of mine;
private int _previousIndex;
private bool _sortDirection;
private void gridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == _previousIndex)
_sortDirection ^= true; // toggle direction
gridView.DataSource = SortData(
(List<MainGridViewModel>)gridReview.DataSource, gridReview.Columns[e.ColumnIndex].Name, _sortDirection);
_previousIndex = e.ColumnIndex;
}
public List<MainGridViewModel> SortData(List<MainGridViewModel> list, string column, bool ascending)
{
return ascending ?
list.OrderBy(_ => _.GetType().GetProperty(column).GetValue(_)).ToList() :
list.OrderByDescending(_ => _.GetType().GetProperty(column).GetValue(_)).ToList();
}
Make sure you subscribe your data grid to the event ColumnHeaderMouseClick
. When the user clicks on the column it will sort by descending. If the same column header is clicked again, sorting will be applied by ascending.
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
e.stopPropagation();_x000D_
e.preventDefault();_x000D_
$('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
$('#right').show("slide", { direction: "right" }, 500);_x000D_
});_x000D_
});_x000D_
$("#right").on('click', function (e) {_x000D_
e.stopPropagation();_x000D_
e.preventDefault();_x000D_
$('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
$('#left').show("slide", { direction: "left" }, 500);_x000D_
});_x000D_
});_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
e.stopPropagation();
e.preventDefault();
$('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
$('#fsEditWindow').show("slide", { direction: "left" }, 500);
});
});
It will work like charm take a look at the demo.
I could solve this problem by changing "Maven home directory" from "Bundled (Maven 3) to "/usr/local/Cellar/maven/3.2.5/libexec" in the maven settings of IntelliJ (14.1.2).
Currently evaluation in the console is performed in the context of the main frame in the page and it adheres to the same cross-origin policy as the main frame itself. This means that you cannot access elements in the iframe unless the main frame can. You can still set breakpoints in and debug your code using Scripts panel though.
Update: This is no longer true. See Metagrapher's answer.
Unnamed namespace limits access of class,variable,function and objects to the file in which it is defined. Unnamed namespace functionality is similar to static
keyword in C/C++.
static
keyword limits access of global variable and function to the file in which they are defined.
There is difference between unnamed namespace and static
keyword because of which unnamed namespace has advantage over static. static
keyword can be used with variable, function and objects but not with user defined class.
For example:
static int x; // Correct
But,
static class xyz {/*Body of class*/} //Wrong
static structure {/*Body of structure*/} //Wrong
But same can be possible with unnamed namespace. For example,
namespace {
class xyz {/*Body of class*/}
static structure {/*Body of structure*/}
} //Correct
This page provides great understanding about the constructor
and destructor
attribute implementation and the sections within within ELF that allow them to work. After digesting the information provided here, I compiled a bit of additional information and (borrowing the section example from Michael Ambrus above) created an example to illustrate the concepts and help my learning. Those results are provided below along with the example source.
As explained in this thread, the constructor
and destructor
attributes create entries in the .ctors
and .dtors
section of the object file. You can place references to functions in either section in one of three ways. (1) using either the section
attribute; (2) constructor
and destructor
attributes or (3) with an inline-assembly call (as referenced the link in Ambrus' answer).
The use of constructor
and destructor
attributes allow you to additionally assign a priority to the constructor/destructor to control its order of execution before main()
is called or after it returns. The lower the priority value given, the higher the execution priority (lower priorities execute before higher priorities before main() -- and subsequent to higher priorities after main() ). The priority values you give must be greater than100
as the compiler reserves priority values between 0-100 for implementation. Aconstructor
or destructor
specified with priority executes before a constructor
or destructor
specified without priority.
With the 'section' attribute or with inline-assembly, you can also place function references in the .init
and .fini
ELF code section that will execute before any constructor and after any destructor, respectively. Any functions called by the function reference placed in the .init
section, will execute before the function reference itself (as usual).
I have tried to illustrate each of those in the example below:
#include <stdio.h>
#include <stdlib.h>
/* test function utilizing attribute 'section' ".ctors"/".dtors"
to create constuctors/destructors without assigned priority.
(provided by Michael Ambrus in earlier answer)
*/
#define SECTION( S ) __attribute__ ((section ( S )))
void test (void) {
printf("\n\ttest() utilizing -- (.section .ctors/.dtors) w/o priority\n");
}
void (*funcptr1)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;
/* functions constructX, destructX use attributes 'constructor' and
'destructor' to create prioritized entries in the .ctors, .dtors
ELF sections, respectively.
NOTE: priorities 0-100 are reserved
*/
void construct1 () __attribute__ ((constructor (101)));
void construct2 () __attribute__ ((constructor (102)));
void destruct1 () __attribute__ ((destructor (101)));
void destruct2 () __attribute__ ((destructor (102)));
/* init_some_function() - called by elf_init()
*/
int init_some_function () {
printf ("\n init_some_function() called by elf_init()\n");
return 1;
}
/* elf_init uses inline-assembly to place itself in the ELF .init section.
*/
int elf_init (void)
{
__asm__ (".section .init \n call elf_init \n .section .text\n");
if(!init_some_function ())
{
exit (1);
}
printf ("\n elf_init() -- (.section .init)\n");
return 1;
}
/*
function definitions for constructX and destructX
*/
void construct1 () {
printf ("\n construct1() constructor -- (.section .ctors) priority 101\n");
}
void construct2 () {
printf ("\n construct2() constructor -- (.section .ctors) priority 102\n");
}
void destruct1 () {
printf ("\n destruct1() destructor -- (.section .dtors) priority 101\n\n");
}
void destruct2 () {
printf ("\n destruct2() destructor -- (.section .dtors) priority 102\n");
}
/* main makes no function call to any of the functions declared above
*/
int
main (int argc, char *argv[]) {
printf ("\n\t [ main body of program ]\n");
return 0;
}
output:
init_some_function() called by elf_init()
elf_init() -- (.section .init)
construct1() constructor -- (.section .ctors) priority 101
construct2() constructor -- (.section .ctors) priority 102
test() utilizing -- (.section .ctors/.dtors) w/o priority
test() utilizing -- (.section .ctors/.dtors) w/o priority
[ main body of program ]
test() utilizing -- (.section .ctors/.dtors) w/o priority
destruct2() destructor -- (.section .dtors) priority 102
destruct1() destructor -- (.section .dtors) priority 101
The example helped cement the constructor/destructor behavior, hopefully it will be useful to others as well.
If you installed as a rpm or deb, then service jenkins restart
will work also.
If you are reading this because you are getting error while updating from the "Install new Software" menu, then you need to do this
please note: add the suffix file:/// to the location
ex. file:///C:/Users/harry/Downloads/eclox/
Maybe not the best solution but this gets the work done :)
public static String getLastDayOfMonth(int year, int month) throws Exception{
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(year+"-"+(month<10?("0"+month):month)+"-01");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
return sdf.format(lastDayOfMonth);
}
public static void main(String[] args) throws Exception{
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 1));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 3));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 4));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 5));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 6));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 7));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 8));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 9));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 10));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 11));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 12));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 1));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 3));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2010, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2011, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2012, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2013, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2014, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2015, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2016, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2019, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2020, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2021, 2));
}
output:
Last Day of Month: 2017-01-31
Last Day of Month: 2017-02-28
Last Day of Month: 2017-03-31
Last Day of Month: 2017-04-30
Last Day of Month: 2017-05-31
Last Day of Month: 2017-06-30
Last Day of Month: 2017-07-31
Last Day of Month: 2017-08-31
Last Day of Month: 2017-09-30
Last Day of Month: 2017-10-31
Last Day of Month: 2017-11-30
Last Day of Month: 2017-12-31
Last Day of Month: 2018-01-31
Last Day of Month: 2018-02-28
Last Day of Month: 2018-03-31
Last Day of Month: 2010-02-28
Last Day of Month: 2011-02-28
Last Day of Month: 2012-02-29
Last Day of Month: 2013-02-28
Last Day of Month: 2014-02-28
Last Day of Month: 2015-02-28
Last Day of Month: 2016-02-29
Last Day of Month: 2017-02-28
Last Day of Month: 2018-02-28
Last Day of Month: 2019-02-28
Last Day of Month: 2020-02-29
Last Day of Month: 2021-02-28
As to me, i need to caffe to my python path. I can add it's path to the file
/home/xy/.bashrc
by add
export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH
.
to my /home/xy/.bashrc
file.
But when I use pycharm, the path is still not in.
So I can add path to PYTHONPATH
variable, by run -> edit Configuration.
If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.
Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.
If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.
There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd
on Mac and ifconfig
works differently.
The following table is useful for knowing the various unix shells.
sh The original Bourne shell Present on every unix system
ksh Original Korn shell Richer shell programming environment than sh
csh Original C-shell C-like syntax; early versions buggy
tcsh Enhanced C-shell User-friendly and less buggy csh implementation
bash GNU Bourne-again shell Enhanced and free sh implementation
zsh Z shell Enhanced, user-friendly ksh-like shell
You may also find these guides helpful:
http://homepage.mac.com/rgriff/files/TerminalBasics.pdf
http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html
On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile
on OSX) file with aliases, some examples below.
I now placed all my aliases in a separate .bash_aliases file and include it with:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
in the .bashrc or .bash_profile file.
Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto
. The first time I did this (without knowing) I redefined ls
to be invalid which was a bit alarming until I removed --auto-color
!
You may also find https://unix.stackexchange.com/q/127799/10043 useful
# ~/.bash_aliases
# ls variants
#alias l='ls -CF'
alias la='ls -A'
alias l='ls -alFtr'
alias lsd='ls -d .*'
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i'
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed'
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status'
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'
//This function allows remove even array from array
var removeFromArr = function(arr, elem) {
var i, len = arr.length, new_arr = [],
sort_fn = function (a, b) { return a - b; };
for (i = 0; i < len; i += 1) {
if (typeof elem === 'object' && typeof arr[i] === 'object') {
if (arr[i].toString() === elem.toString()) {
continue;
} else {
if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
continue;
}
}
}
if (arr[i] !== elem) {
new_arr.push(arr[i]);
}
}
return new_arr;
}
Example of using
var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]
var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]
You can use regular grep like this:
tail -f admin.log | grep -v "Nopaging the limit is\|keyword to remove is"
Check out Andrew Davey's snazzy Vogue project - http://aboutcode.net/vogue/
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
For me, I got this same error in VS 2015 and just installed the VS 2015 update 1, though from another answer, VS is actually up to Update 3, now (after which, they got the error and had to install .NET Core). Had issues when it hit certain packages, like the Windows SDK ones, and had to point the installer back at the paths in my original CD, and for some, even that didn't work and had to skip them and re-download from an internet-connected computer, transfer them over, and run them later manually (computer was not connected to the internet to be able to download updated versions of the packages), but after doing all that and doing a reboot, the error was gone and my project loaded fine.
The RestTemplate getForObject()
method does not support setting headers. The solution is to use the exchange()
method.
So instead of restTemplate.getForObject(url, String.class, param)
(which has no headers), use
HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.GET, entity, String.class, param);
Finally, use response.getBody()
to get your result.
This question is similar to this question.
There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject]
or [JsonProperty]
.
There are predefined naming strategies like CamelCaseNamingStrategy
, but you can implement your own ones.
The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization
I'm getting the following error when compiling Adam Rosenfield's code on Windows. It turns out few things are missing from the code.
Error (Before)
C:\C\Codes>gcc time.c -o time
time.c:3:12: error: initializer element is not constant
time_t t = time(NULL);
^
time.c:4:16: error: initializer element is not constant
struct tm tm = *localtime(&t);
^
time.c:6:8: error: expected declaration specifiers or '...' before string constant
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:36: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:55: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:70: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:82: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:94: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
time.c:6:105: error: expected declaration specifiers or '...' before 'tm'
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
^
C:\C\Codes>
Solution
C:\C\Codes>more time.c
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}
C:\C\Codes>
Compiling
C:\C\Codes>gcc time.c -o time
C:\C\Codes>
Final Output
C:\C\Codes>time
now: 2018-3-11 15:46:36
C:\C\Codes>
I hope this will helps others too
Like this:
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.width();
var imgLength = images.length;
$(this).find(".scrolling").width( width * imgLength * 1.2 );
});
The $(this)
refers to the current .target
which will be looped through. Within this .target
I'm looking for the .scrolling img
and get the width. And then keep on going...
Images with different widths
If you want to calculate the width of all images (when they have different widths) you can do it like this:
// Get the total width of a collection.
$.fn.getTotalWidth = function(){
var width = 0;
this.each(function(){
width += $(this).width();
});
return width;
}
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.getTotalWidth();
$(this).find(".scrolling").width( width * 1.2 );
});
I usually use this form:
{{#if FriendStatus.IsFriend}}
...
{{else}} {{#if FriendStatus.FriendRequested}}
...
{{else}}
...
{{/if}}{{/if}}
open your browser,check whether Tomcat homepage is visible by below command.
http://ipaddress:portnumber
also check this
We can't because it's expected/required by our customers.
You could use CSS for this and create classes for the elements. So you'd have something like this
p.detail { color:#4C4C4C;font-weight:bold;font-family:Calibri;font-size:20 }
span.name { color:#FF0000;font-weight:bold;font-family:Tahoma;font-size:20 }
Then your HTML would read:
<p class="detail">My Name is: <span class="name">Tintinecute</span> </p>
It's a lot neater then inline stylesheets, is easier to maintain and provides greater reuse.
Here's the complete HTML to demonstrate what I mean:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<style type="text/css">
p.detail { color:#4C4C4C;font-weight:bold;font-family:Calibri;font-size:20 }
span.name { color:#FF0000;font-weight:bold;font-family:Tahoma;font-size:20 }
</style>
</head>
<body>
<p class="detail">My Name is: <span class="name">Tintinecute</span> </p>
</body>
</html>
You'll see that I have the stylesheet classes in a style tag in the header, and then I only apply those classes in the code such as <p class="detail"> ... </p>
. Go through the w3schools tutorial, it will only take a couple of hours and will really turn you around when it comes to styling your HTML elements. If you cut and paste that into an HTML document you can edit the styles and see what effect they have when you open the file in a browser. Experimenting like this is a great way to learn.
You can use SysInternals NTFSInfo by Mark Russinovich from the command line and it converts fsutil fsinfo ntfsinfo into more readable information, especially MFT Table info.
var arr = [1, 2];_x000D_
arr.splice(0, 2, arr[1], arr[0]);_x000D_
console.log(arr); //[2, 1]
_x000D_
Create an EditorTemplate for a specific set of Views (bound by one Controller):
In this example I have a template for a Date, but you can change it to whatever you want.
Here is the code in the Data.cshtml:
@model Nullable<DateTime>
@Html.TextBox("", @Model != null ? String.Format("{0:d}", ((System.DateTime)Model).ToShortDateString()) : "", new { @class = "datefield", type = "date", disabled = "disabled" @readonly = "readonly" })
and in the model:
[DataType(DataType.Date)]
public DateTime? BlahDate { get; set; }
For those wanting to use a Class.
Create a Class with all the parameters you want
Create a list with the class as parameter
class MyClass_x000D_
{_x000D_
public string S1;_x000D_
public string S2;_x000D_
}_x000D_
_x000D_
List<MyClass> MyList= new List<MyClass>();
_x000D_
window.format = function(b, a) {
if (!b || isNaN(+a)) return a;
var a = b.charAt(0) == "-" ? -a : +a,
j = a < 0 ? a = -a : 0,
e = b.match(/[^\d\-\+#]/g),
h = e && e[e.length - 1] || ".",
e = e && e[1] && e[0] || ",",
b = b.split(h),
a = a.toFixed(b[1] && b[1].length),
a = +a + "",
d = b[1] && b[1].lastIndexOf("0"),
c = a.split(".");
if (!c[1] || c[1] && c[1].length <= d) a = (+a).toFixed(d + 1);
d = b[0].split(e);
b[0] = d.join("");
var f = b[0] && b[0].indexOf("0");
if (f > -1)
for (; c[0].length < b[0].length - f;) c[0] = "0" + c[0];
else +c[0] == 0 && (c[0] = "");
a = a.split(".");
a[0] = c[0];
if (c = d[1] && d[d.length -
1].length) {
for (var d = a[0], f = "", k = d.length % c, g = 0, i = d.length; g < i; g++) f += d.charAt(g), !((g - k + 1) % c) && g < i - c && (f += e);
a[0] = f
}
a[1] = b[1] && a[1] ? h + a[1] : "";
return (j ? "-" : "") + a[0] + a[1]
};
var str="1234567890";
var formatstr=format( "##,###.", str);
alert(formatstr);
This will split the string in reverse order with comma separated after 3 char's. If you want you can change the position.
While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.
It is important to keep two or three different exceptions straight in our head in this case:
java.lang.ClassNotFoundException
This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError
This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.
This is ugly but avoids allocations:
private static string GetFolderName(string path)
{
var end = -1;
for (var i = path.Length; --i >= 0;)
{
var ch = path[i];
if (ch == System.IO.Path.DirectorySeparatorChar ||
ch == System.IO.Path.AltDirectorySeparatorChar ||
ch == System.IO.Path.VolumeSeparatorChar)
{
if (end > 0)
{
return path.Substring(i + 1, end - i - 1);
}
end = i;
}
}
if (end > 0)
{
return path.Substring(0, end);
}
return path;
}
Assuming these were datetime columns (if they're not apply to_datetime
) you can just subtract them:
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])
In [11]: df.dtypes # if already datetime64 you don't need to use to_datetime
Out[11]:
A datetime64[ns]
B datetime64[ns]
dtype: object
In [12]: df['A'] - df['B']
Out[12]:
one -58 days
two -26 days
dtype: timedelta64[ns]
In [13]: df['C'] = df['A'] - df['B']
In [14]: df
Out[14]:
A B C
one 2014-01-01 2014-02-28 -58 days
two 2014-02-03 2014-03-01 -26 days
Note: ensure you're using a new of pandas (e.g. 0.13.1), this may not work in older versions.
For someone whom the above solution didn't worked.
For gradle,
File -> Project Structure
Click on Project Under Project Settings
Update Project Language level as Modules, private methods in interfaces etc.
Click OK and Import Gradle Settings
Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples
${parameter-default}, ${parameter:-default}
If parameter not set, use default. After the call, parameter is still not set.
Both forms are almost equivalent. The extra :
makes a difference only when parameter has been declared, but is null.
unset EGGS
echo 1 ${EGGS-spam} # 1 spam
echo 2 ${EGGS:-spam} # 2 spam
EGGS=
echo 3 ${EGGS-spam} # 3
echo 4 ${EGGS:-spam} # 4 spam
EGGS=cheese
echo 5 ${EGGS-spam} # 5 cheese
echo 6 ${EGGS:-spam} # 6 cheese
${parameter=default}, ${parameter:=default}
If parameter not set, set parameter value to default.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null
# sets variable without needing to reassign
# colons suppress attempting to run the string
unset EGGS
: ${EGGS=spam}
echo 1 $EGGS # 1 spam
unset EGGS
: ${EGGS:=spam}
echo 2 $EGGS # 2 spam
EGGS=
: ${EGGS=spam}
echo 3 $EGGS # 3 (set, but blank -> leaves alone)
EGGS=
: ${EGGS:=spam}
echo 4 $EGGS # 4 spam
EGGS=cheese
: ${EGGS:=spam}
echo 5 $EGGS # 5 cheese
EGGS=cheese
: ${EGGS=spam}
echo 6 $EGGS # 6 cheese
${parameter+alt_value}, ${parameter:+alt_value}
If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null
unset EGGS
echo 1 ${EGGS+spam} # 1
echo 2 ${EGGS:+spam} # 2
EGGS=
echo 3 ${EGGS+spam} # 3 spam
echo 4 ${EGGS:+spam} # 4
EGGS=cheese
echo 5 ${EGGS+spam} # 5 spam
echo 6 ${EGGS:+spam} # 6 spam
Go to "Run" and execute this:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
NOTE: run as administrator.
I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)
case "$1" in
0|1) xinput set-prop 12 "Device Enabled" $1 ;;
*) echo "This script requires a 1 or 0 as first parameter." ;;
esac
x = {:ca => "Canada", :us => "United States"}
x[:de] = "Germany"
p x
Send a POST request from A. Post requests are on the serverside only and can't be accessed by the client.
You can send a POST request from a.com
to b.com
using CURL (recommended, serverside) or a hidden method="POST"
form (clientside). If you go for the latter, you might want to obfuscate your JavaScript so that the user won't be able to understand the algorithm and interfere with it.
Make a gateway on b.com
to set cookies:
<?php
if (isset($_POST['data']) {
setcookie('a', $_POST['data']);
header("Location: b.com/landingpage");
}
?>
If you want to bring security a step further, implement a function on both sides (a.com
and b.com
) to encrypt (on a.com
) and decrypt (on b.com
) data using a cryptographic cypher.
If you're trying to do something that must be absolutely secure (e.g. transfer a login session) try oAuth or take some inspiration from https://api.cloudianos.com/docs#v2/auth
In case my experience of this problem gives someone a Eureka! moment.. I'll add the following:
I was also getting this problem, when using an xsd file that I had generated using IntelliJ's "Generate xsd from Instance document" menu option.
When I accepted all the defaults of this tool, it generated an xsd file that when used with jaxb, generated java files with no @XmlRootElement
. At runtime when I tried to marshal I got the same exception as discussed in this question.
I went back to the IntellJ tool, and saw the default option in the "Desgin Type" drop down (which of course I didn't understand.. and still don't if I'm honest) was:
Desgin Type:
"local elements/Global complex types"
I changed this to
"local elements/types"
, now it generated a (substantially) different xsd, that produced the @XmlRootElement
when used with jaxb. Can't say I understand the in's and out's of it, but it worked for me.
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
Here is an example I used to connect node.js to my Postgres database.
The interface in node.js that I used can be found here https://github.com/brianc/node-postgres
var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";
var client = new pg.Client(conString);
client.connect();
//queries are queued and executed one after another once the connection becomes available
var x = 1000;
while (x > 0) {
client.query("INSERT INTO junk(name, a_number) values('Ted',12)");
client.query("INSERT INTO junk(name, a_number) values($1, $2)", ['John', x]);
x = x - 1;
}
var query = client.query("SELECT * FROM junk");
//fired after last row is emitted
query.on('row', function(row) {
console.log(row);
});
query.on('end', function() {
client.end();
});
//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
client.query({
name: 'insert beatle',
text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
values: ['George', 70, new Date(1946, 02, 14)]
});
//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
name: 'insert beatle',
values: ['Paul', 63, new Date(1945, 04, 03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['john']);
//can stream row results back 1 at a time
query.on('row', function(row) {
console.log(row);
console.log("Beatle name: %s", row.name); //Beatle name: John
console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
console.log("Beatle height: %d' %d\"", Math.floor(row.height / 12), row.height % 12); //integers are returned as javascript ints
});
//fired after last row is emitted
query.on('end', function() {
client.end();
});
UPDATE:- THE query.on
function is now deprecated and hence the above code will not work as intended. As a solution for this look at:- query.on is not a function
The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:
(EndDate.Date - StartDate.Date).Days
Again assuming StartDate
and EndDate
are of type DateTime
.
SSMSBoost add-in (currently free)
+tons of other features. (I am the developer of the add-in)
if (@!in_array($classified->category,$arr)){
$arr[] = $classified->category;
?>
<?php } endwhile; wp_reset_query(); ?>
first time check value in array and found same value ignore it
I had multiple dataframes with different floating point, so thx to Allans idea made dynamic length.
pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)
The minus of this is that if You have last 0 in float, it will cut it. So it will be not 0.000070, but 0.00007.
Getting Full File Paths From a Directory and All Its Subdirectories
import os
def get_filepaths(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
"""
file_paths = [] # List which will store all of the full filepaths.
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
return file_paths # Self-explanatory.
# Run the above function and store its results in a variable.
full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")
print full_file_paths
which will print the list:
['/Users/johnny/Desktop/TEST/file1.txt', '/Users/johnny/Desktop/TEST/file2.txt', '/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat']
If you'd like, you can open and read the contents, or focus only on files with the extension ".dat" like in the code below:
for f in full_file_paths:
if f.endswith(".dat"):
print f
/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat
The windows handle limit for your application is 10,000 handles. You're getting the error because your program is creating too many handles. You'll need to find the memory leak. As other users have suggested, use a Memory Profiler. I use the .Net Memory Profiler as well. Also, make sure you're calling the dispose method on controls if you're removing them from a form before the form closes (otherwise the controls won't dispose). You'll also have to make sure that there are no events registered with the control. I myself have the same issue, and despite what I already know, I still have some memory leaks that continue to elude me..
Not PIL, but imageio.imread
might still be interesting:
import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So the pixel at position (x, y)
is
color = tuple(im[y][x])
r, g, b = color
scipy.misc.imread
is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)
Tried in Hive and got the below output
table1
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
4,yepie,newyork,USA
table2
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
5,chapie,Los angels,USA
Inner Join
SELECT * FROM table1 INNER JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
Left Join
SELECT * FROM table1 LEFT JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
4 yepie newyork USA NULL NULL NULL NULL
Left Semi Join
SELECT * FROM table1 LEFT SEMI JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india
2 stu salem india
3 mia bangalore india
note: Only records in left table are displayed whereas for Left Join both the table records displayed
First of all need to understand what is CSV and how to write it.
(Most of answers (all of them at the moment) do not use this requirements, that's why they all is wrong!)
/r/n
) is next "table" row.\t
or ,
./r/n
symbols inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)Some time ago I had wrote simple class for CSV read/write based on standard Microsoft.VisualBasic.FileIO
library. Using this simple class you will be able to work with CSV like with 2 dimensions array.
Simple example of using my library:
Csv csv = new Csv("\t");//delimiter symbol
csv.FileOpen("c:\\file1.csv");
var row1Cell6Value = csv.Rows[0][5];
csv.AddRow("asdf","asdffffff","5")
csv.FileSave("c:\\file2.csv");
You can find my class by the following link and investigate how it's written: https://github.com/ukushu/DataExporter
This library code is really fast in work and source code is really short.
PS: In the same time this solution will not work for unity.
PS2: Another solution is to work with library "LINQ-to-CSV". It must also work well. But it's will be bigger.
A bit late here, but none of the above seemed to work. Try this, using printf, inserts spaces between each. I chose to not have newline at the end.
awk '{for(i=3;i<=NF;++i) printf("%s ", $i) }'
For me below solution worked.
Jenkins --> Manage Jenkins --> Manage Nodes --> master -> configure --> Node properties --> Restrict Jobs execution at node - is enabled and given access to specific users. I have given access myself and then job started to run.
If Restrict Jobs execution at node is enabled scheduled tasks cannot run.
If you're asking about alphabetical order the syntax is:
SELECT * FROM table ORDER BY column
the best example I can give without knowing your table and field names:
SELECT * FROM employees ORDER BY name
If you are using localhost in your url and testing your application in emulator , simply you can replace system's ip address for localhost in the URL.or you can use 10.0.2.2 instead of localhost.
http://localhost/webservice.php to http://10.218.28.19/webservice.php
Where 10.218.28.19 -> System's IP Address.
or
http://localhost/webservice.php to http://10.0.2.2/webservice.php
Alright this is very late however I've discovered that if you add a List View under your edit text then the keyboard will move all layouts under that edittext without moving the ListView
<EditText
android:id="@+id/et"
android:layout_height="match_parent"
android:layout_width="match_parent"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"//can make as 1dp
android:layout_below="@+id/et" // set to below editext
android:id="@+id/view"
>
**<any layout**
This is the only solution that worked for me.
Just add an OR in the conditions
Model.find(:all, :conditions => ["column = ? OR other_column = ?",value, other_value])
This will give you sequence of anonymous objects, containing date string and two properties with average price:
var query = from p in PriceLogList
group p by p.LogDateTime.ToString("MMM yyyy") into g
select new {
LogDate = g.Key,
AvgGoldPrice = (int)g.Average(x => x.GoldPrice),
AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
};
If you need to get list of PriceLog objects:
var query = from p in PriceLogList
group p by p.LogDateTime.ToString("MMM yyyy") into g
select new PriceLog {
LogDateTime = DateTime.Parse(g.Key),
GoldPrice = (int)g.Average(x => x.GoldPrice),
SilverPrice = (int)g.Average(x => x.SilverPrice)
};
In terms of WCF, we can communicate with the server and client through messages. For transferring messages, and from a security prospective, we need to make a data/message in a serialized format.
For serializing data we use [datacontract] and [datamember] attributes.
In your case if you are using datacontract
WCF uses DataContractSerializer
else WCF uses XmlSerializer
which is the default serialization technique.
Let me explain in detail:
basically WCF supports 3 types of serialization:
XmlSerializer :- Default order is Same as class
DataContractSerializer/NetDataContractSerializer :- Default order is Alphabetical
XmlSerializer :- XML Schema is Extensive
DataContractSerializer/NetDataContractSerializer :- XML Schema is Constrained
XmlSerializer :- Versioning support not possible
DataContractSerializer/NetDataContractSerializer :- Versioning support is possible
XmlSerializer :- Compatibility with ASMX
DataContractSerializer/NetDataContractSerializer :- Compatibility with .NET Remoting
XmlSerializer :- Attribute not required in XmlSerializer
DataContractSerializer/NetDataContractSerializer :- Attribute required in this serializing
so what you use depends on your requirements...
I know this is a really old question however no answers provide the proper reasoning for why this can never be done. While you can "do" what you are looking for you cannot do it in a valid way. In order to have a valid img tag it must have the src and alt attributes.
So any of the answers giving a way to do this with an img tag that does not use the src attribute are promoting use of invalid code.
In short: what you are looking for cannot be done legally within the structure of the syntax.
Source: W3 Validator
The best solution for your problem is to utilize a Pool
. Using Queue
s and having a separate "queue feeding" functionality is probably overkill.
Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool
. I believe it's the easiest way to go, with minimal changes to original code:
import multiprocessing
import time
data = (
['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)
def mp_worker((inputs, the_time)):
print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
time.sleep(int(the_time))
print " Process %s\tDONE" % inputs
def mp_handler():
p = multiprocessing.Pool(2)
p.map(mp_worker, data)
if __name__ == '__main__':
mp_handler()
Note that mp_worker()
function now accepts a single argument (a tuple of the two previous arguments) because the map()
function chunks up your input data into sublists, each sublist given as a single argument to your worker function.
Output:
Processs a Waiting 2 seconds
Processs b Waiting 4 seconds
Process a DONE
Processs c Waiting 6 seconds
Process b DONE
Processs d Waiting 8 seconds
Process c DONE
Processs e Waiting 1 seconds
Process e DONE
Processs f Waiting 3 seconds
Process d DONE
Processs g Waiting 5 seconds
Process f DONE
Processs h Waiting 7 seconds
Process g DONE
Process h DONE
Edit as per @Thales comment below:
If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:
A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...
then change the handler function to launch pools (of 2 processes) for each pair of data:
def mp_handler():
subdata = zip(data[0::2], data[1::2])
for task1, task2 in subdata:
p = multiprocessing.Pool(2)
p.map(mp_worker, (task1, task2))
Now your output is:
Processs a Waiting 2 seconds
Processs b Waiting 4 seconds
Process a DONE
Process b DONE
Processs c Waiting 6 seconds
Processs d Waiting 8 seconds
Process c DONE
Process d DONE
Processs e Waiting 1 seconds
Processs f Waiting 3 seconds
Process e DONE
Process f DONE
Processs g Waiting 5 seconds
Processs h Waiting 7 seconds
Process g DONE
Process h DONE
use of bundle send data from one activity to another activity with the help of intent object; Bundle hold the data that can be any type.
Now I tell that how to create bundle passing data between two activity.
Step 1: On First activity
Bundle b=new Bundle();
b.putString("mkv",anystring);
Intent in=new Intent(getApplicationContext(),secondActivity.class);
in.putExtras(b);
startActivity(in);
Step 2: On Second Activity
Intent in=getIntent();
Bundle b=in.getExtras();
String s=b.getString("mkv");
I think this is useful for you...........
Create a configuration file and put your entries there.
SERVER_PORT=10000
THREAD_POOL_COUNT=3
ROOT_DIR=/home/
You can load this file using Properties.load(fileName)
and retrieved values you get(key)
;
Much easier with numpy:
>>> arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> arr
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> arr.T
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
>>> theArray = np.array([['a','b','c'],['d','e','f'],['g','h','i']])
>>> theArray
array([['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']],
dtype='|S1')
>>> theArray.T
array([['a', 'd', 'g'],
['b', 'e', 'h'],
['c', 'f', 'i']],
dtype='|S1')
We can implement by 3 Methods:
Note:
"automatic-scroll" => The particular element
"scrollable-div" => The scrollable area div
Method 1:
document.querySelector('.automatic-scroll').scrollIntoView({
behavior: 'smooth'
});
Method 2:
location.href = "#automatic-scroll";
Method 3:
$('#scrollable-div').animate({
scrollTop: $('#automatic-scroll').offset().top - $('#scrollable-div').offset().top +
$('#scrollable-div').scrollTop()
})
Important notice: method 1 & method 2 will be useful if the scrollable area height is "auto". Method 3 is useful if we using the scrollable area height like "calc(100vh - 200px)".
This will work for your case:
sonar.exclusions=**/src/java/dig/ ** , **/src/java/test/dig/ **