This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;
ArrayList<String> recordings = new ArrayList<String>();
this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.
Remove your Gemfile.lock.
Move to bash if you are using zsh.
sudo bash
gem update --system
Now run command bundle to create a new Gemfile.lock file.
Move back to your zsh sudo exec zsh
now run your rake commands.
If you don't want to make the button a separate image, you can use the <area>
tag. This is done by using html similar to this:
<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">
<map name="mapname">
<area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>
Note 1: The coords=" "
attribute must be formatted in this way: coords="x1,y1,x2,y2"
where:
x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate
Note 2: The usemap="#mapname"
attribute must include the #
.
EDIT:
I looked at your code and added in the <map>
and <area>
tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.
<div class="flexslider">
<ul class="slides" runat="server" id="Ul">
<li class="flex-active-slide" style="background: url("images/slider-bg-1.jpg") no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
<div class="container">
<div class="sixteen columns contain"></div>
<img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
<map name="imgmap">
<area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
</map>
<!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
</div>
</li>
</ul>
</div>
<!-- <ul class="flex-direction-nav">
<li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
<li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->
Notes:
coord="48,341,294,275"
is in reference to your screenshot you posted.src="./test.png"
is the location and name of the screenshot you posted on my computer.href="http://www.example.com/"
is an example link.Here's an example using an extension. This assumes the view has the same width and height.
Need to use a layout change listener to get the view size.
Then you can just call this on a view like this myView.setRoundedBackground(Color.WHITE)
fun View.setRoundedBackground(@ColorInt color: Int) {
addOnLayoutChangeListener(object: View.OnLayoutChangeListener {
override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
val shape = GradientDrawable()
shape.cornerRadius = measuredHeight / 2f
shape.setColor(color)
background = shape
removeOnLayoutChangeListener(this)
}
})
}
I had this same problem and it seemed to be related to using the same database connection for concurrent tasks. There might be some alternative solutions (maybe better), but I solved it by setting MaxConcurrentExecutables
to 1.
By.cssSelector(".ban")
or By.cssSelector(".hot")
or By.cssSelector(".ban.hot")
should all select it unless there is another element that has those classes.
In CSS, .name
means find an element that has a class with name
. .foo.bar.baz
means to find an element that has all of those classes (in the same element).
However, each of those selectors will select only the first element that matches it on the page. If you need something more specific, please post the HTML of the other elements that have those classes.
Ultimately no. You can query for listings with a search string from an RSS feed such as this:
http://YOURCITY.craigslist.org/search/sss?format=rss&query=SearchString
As far as posting, craiglist has not opened their API. However, this SO Question may shed some light and a possible solution - although not a very reliable one.
Craigslist Automated Posting API?
Write a note to craigslist asking them to open their API,
This worked for me. Repeatedly calls a function updating the graph every time.
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def plot_cont(fun, xmax):
y = []
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def update(i):
yi = fun()
y.append(yi)
x = range(len(y))
ax.clear()
ax.plot(x, y)
print i, ': ', yi
a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False)
plt.show()
"fun" is a function that returns an integer. FuncAnimation will repeatedly call "update", it will do that "xmax" times.
Have a look at the HttpURLConnection
class API documentation, especially setInstanceFollowRedirects()
.
To expand on Byron's answer, I believe you need to edit the file java.security
in the %JRE_HOME%\lib\security
directory to effect this change.
Here is the relevant section:
#
# The Java-level namelookup cache policy for successful lookups:
#
# any negative value: caching forever
# any positive value: the number of seconds to cache an address for
# zero: do not cache
#
# default value is forever (FOREVER). For security reasons, this
# caching is made forever when a security manager is set. When a security
# manager is not set, the default behavior is to cache for 30 seconds.
#
# NOTE: setting this to anything other than the default value can have
# serious security implications. Do not set it unless
# you are sure you are not exposed to DNS spoofing attack.
#
#networkaddress.cache.ttl=-1
Documentation on the java.security
file here.
You can try this code into your activity
private void startWebView(WebView webView,String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Call this method using this way:
startWebView(web_view,"Your Url");
Sometimes if URL is dead it will redirected and it will come to onLoadResource() before onPageFinished method. For this reason progress bar will not dismis. To solve this issue see my this Answer.
Thanks :)
Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):
# Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.
FROM ubuntu
MAINTAINER Kimbro Staken
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
RUN apt-get update
RUN apt-get -y install apt-utils
RUN apt-get -y install mongodb-10gen
#RUN echo "" >> /etc/mongodb.conf
CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"]
This solved it for me
AppRegistry.registerComponent('main', () => App);
So my index.js
file
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('main', () => App);
And my package.json
file:
"dependencies": {
"react": "^16.13.1",
"react-dom": "~16.9.0",
"react-native": "~0.61.5"
},
You can find out by measuring memory usage size after calling garbage collector multiple times:
Runtime runtime = Runtime.getRuntime();
while(true) {
...
if(System.currentTimeMillis() % 4000 == 0){
System.gc();
float usage = (float) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
System.out.println("Used memory: " + usage + "Mb");
}
}
If the output numbers were equal, there is no memory leak in your application, but if you saw difference between the numbers of memory usage (increasing numbers), there is memory leak in your project. For example:
Used memory: 14.603279Mb
Used memory: 14.737213Mb
Used memory: 14.772224Mb
Used memory: 14.802681Mb
Used memory: 14.840599Mb
Used memory: 14.900841Mb
Used memory: 14.942261Mb
Used memory: 14.976143Mb
Note that sometimes it takes some time to release memory by some actions like streams and sockets. You should not judge by first outputs, You should test it in a specific amount of time.
Update:
Separate the event and property bindings:
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
You could also use
<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">
and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.
Old answer, before they fixed a bug in beta.1:
Create a local template variable and attach a (change)
event:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
See also How can I get new selection in "select" in Angular 2?
When using this approach you have to make sure that none of your values contains something that would be illegal XML – user1151923
I always use the XML method. Make sure you use VALID XML. I have two functions to convert between valid XML and Text. (I tend to strip out the carriage returns as I don't usually need them.
CREATE FUNCTION dbo.udf_ConvertTextToXML (@Text varchar(MAX))
RETURNS varchar(MAX)
AS
BEGIN
SET @Text = REPLACE(@Text,CHAR(10),'')
SET @Text = REPLACE(@Text,CHAR(13),'')
SET @Text = REPLACE(@Text,'<','<')
SET @Text = REPLACE(@Text,'&','&')
SET @Text = REPLACE(@Text,'>','>')
SET @Text = REPLACE(@Text,'''',''')
SET @Text = REPLACE(@Text,'"','"')
RETURN @Text
END
CREATE FUNCTION dbo.udf_ConvertTextFromXML (@Text VARCHAR(MAX))
RETURNS VARCHAR(max)
AS
BEGIN
SET @Text = REPLACE(@Text,'<','<')
SET @Text = REPLACE(@Text,'&','&')
SET @Text = REPLACE(@Text,'>','>')
SET @Text = REPLACE(@Text,''','''')
SET @Text = REPLACE(@Text,'"','"')
RETURN @Text
END
I hope I understand your question, but the ng-model
directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant
. This means that changing item.selectedVariant
in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant
has a value of 0
, that item should get selected.
If variants
is an array of objects, item.selectedVariant
must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:
xhr.send(null);
if (xhr.status == 204)
Reload();
else
dropdown.innerHTML = xhr.responseText;
Here is the Reload() function:
function Reload() {
var oForm = document.createElement("form");
document.body.appendChild(oForm);
oForm.submit();
}
You can use this library, makes it seamless to send push notifications using Firebase Service from a C# backend download here
I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.
Wrap up content like below,
var params = {
"IDs": IDs,
"ID2s": IDs2,
"id": 1
};
In my case I had already json'd the arrays and passed the result to the function
var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());
Then call the XMLHttpRequest POST and stringify the object
var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
var blob = new Blob([this.response], { type: "application/octet-stream" });
saveAs(blob, "filename.zip");
}
};
ajax.send(JSON.stringify(params));
Then have a model like this
public class MyModel
{
public int[] IDs { get; set; }
public int[] ID2s { get; set; }
public int id { get; set; }
}
Then pass in Action like
public async Task<IActionResult> MyAction([FromBody] MyModel model)
Use this add-on if your returning a file
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.
Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.
If you are comparing schemas on the same database then try:
select * from dba_objects
where schema_name = 'ASCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects
where schema_name = 'BSCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
and switch around the orders of ASCHEMA and BSCHEMA.
If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas
Not difficult, check this.
<button @click="disabled = !disabled">Toggle Enable</button>
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="disabled">
Declare global variables:
var mapOptions;
var map;
var infowindow;
var marker;
var contentString;
var image;
In intialize
use the map's addEvent
method:
google.maps.event.addListener(map, 'click', function() {
if (infowindow) {
infowindow.close();
}
});
Sure you can; it's called a dictionary:
d = {}
for x in range(1, 10):
d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
'string2': 'Hello',
'string3': 'Hello',
'string4': 'Hello',
'string5': 'Hello',
'string6': 'Hello',
'string7': 'Hello',
'string8': 'Hello',
'string9': 'Hello'}
I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!
To get the id of the parent div:
$(buttonSelector).parents('div:eq(0)').attr('id');
Also, you can refactor your code quite a bit:
$('button').click( function() {
var correct = Number($(this).attr('rel'));
validate(Number($(this).siblings('input').val()), correct);
$(this).parents('div:eq(0)').html(feedback);
});
Now there is no need for a button-class
explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.
You should have a look at the jQuery docs, particularly selectors and traversing:
Please don't call any StartForgroundServices inside onCreate() method, you have to call StartForground services in onStartCommand() after make the worker thread otherwise you will get ANR always , so please don't write complex login in main thread of onStartCommand();
public class Services extends Service {
private static final String ANDROID_CHANNEL_ID = "com.xxxx.Location.Channel";
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("SmartTracker Running")
.setAutoCancel(true);
Notification notification = builder.build();
startForeground(0, notification);
Log.e("home_button","home button");
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText("SmartTracker is Running...")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
Notification notification = builder.build();
startForeground(0, notification);
Log.e("home_button_value","home_button_value");
}
return super.onStartCommand(intent, flags, startId);
}
}
EDIT: Caution! startForeground function can't take 0 as first argument, it will raise an exception! this example contains wrong function call, change 0 to your own const which couldnt be 0 or be greater than Max(Int32)
For anyone who have the same problem of "Can't connect to MySQL server on 'localhost' (10061) " or "Can't connect to MySQL server on '127.0.0.1' (10061) ". You can install "MySQL Installer" and this is the link http://dev.mysql.com/downloads/windows/installer/5.6.html and this is a tutoriel for more help https://www.youtube.com/watch?v=AqQc3YqfelE
it works for me and i wish to work for you too.
Inspired by @JasonBaker's benchmarks, here's a simple one comparing 10 "abcdefghijklmnopqrstuvxyz"
strings, showing that .join()
is faster; even with this tiny increase in variables:
>>> x = timeit.Timer(stmt='"abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz"')
>>> x.timeit()
0.9828147209324385
>>> x = timeit.Timer(stmt='"".join(["abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz"])')
>>> x.timeit()
0.6114138159765048
If you don't want to bother with the keystore file, then just remove the package altogether for all users.
Connect your device with Mac/PC and run adb uninstall <package>
Worked for me.
Use the following to delete all the tables in a linux environment.
hive -e 'show tables' | xargs -I '{}' hive -e 'drop table {}'
You want:
if (document.getElementById('customx').value === ""){
//do something
}
The value
property will give you a string value and you need to compare that against an empty string.
group by fV.tier_id, f.form_template_id
When running in debug mode you can use the little arrow button in the debug area (Shift+Cmd+Y) in Xcode to specify a location. There are some presets or you can also add a GPX file.
You can generate GPX files here manually: http://www.bikehike.co.uk/mapview.php (from answer: https://stackoverflow.com/a/17478860/881197)
Another approach, since Excel 2016, is to use Power Query.
Howto:
Data
> From a table or a range
,Remove duplicates
,Close and load
, choose where you want the result, and you're done, like this.Refresh
.Benefits :
Drawbacks :
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
CREATE OR REPLACE PACKAGE BODY TEST AS
FUNCTION GET_UPS(
TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
STARTING_DATE_IN DATE,
ENDING_DATE_IN DATE
)RETURN MEASURE_TABLE IS
T MEASURE_TABLE;
BEGIN
**SELECT MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
PERIOD,VALUE ) BULK COLLECT INTO T
FROM ...**
;
RETURN T;
END GET_UPS;
END TEST;
Simple way of doing this.
private String repeatString(String s,int count){
StringBuilder r = new StringBuilder();
for (int i = 0; i < count; i++) {
r.append(s);
}
return r.toString();
}
Yes, it's possible. for example checkout:
<div class="singleMatch" ng-if="match.date | date:'ddMMyyyy' === main.date && match.team1.code === main.team1code && match.team2.code === main.team2code">
//Do something here
</div>
On EF6.2, you can use HasIndex()
to add indexes for migration through fluent API.
https://github.com/aspnet/EntityFramework6/issues/274
Example
modelBuilder
.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();
On EF6.1 onwards, you can use IndexAnnotation()
to add indexes for migration in your fluent API.
http://msdn.microsoft.com/en-us/data/jj591617.aspx#PropertyIndex
You must add reference to:
using System.Data.Entity.Infrastructure.Annotations;
Basic Example
Here is a simple usage, adding an index on the User.FirstName
property
modelBuilder
.Entity<User>()
.Property(t => t.FirstName)
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
Practical Example:
Here is a more realistic example. It adds a unique index on multiple properties: User.FirstName
and User.LastName
, with an index name "IX_FirstNameLastName"
modelBuilder
.Entity<User>()
.Property(t => t.FirstName)
.IsRequired()
.HasMaxLength(60)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("IX_FirstNameLastName", 1) { IsUnique = true }));
modelBuilder
.Entity<User>()
.Property(t => t.LastName)
.IsRequired()
.HasMaxLength(60)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("IX_FirstNameLastName", 2) { IsUnique = true }));
Everything failed for me. Only thing that worked...is adding cache-view="false" into the view which I want to reload when going to it.
from this issue https://github.com/angular-ui/ui-router/issues/582
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
To change all classes for an element:
document.getElementById("ElementID").className = "CssClass";
To add an additional class to an element:
document.getElementById("ElementID").className += " CssClass";
To check if a class is already applied to an element:
if ( document.getElementById("ElementID").className.match(/(?:^|\s)CssClass(?!\S)/) )
1.this is my answer for your problem.
.ModalCarrot::before {
content:'';
background: url('blackCarrot.png'); /*url of image*/
height: 16px; /*height of image*/
width: 33px; /*width of image*/
position: absolute;
}
I notice a lot of people are recommending Convert.ChangeType
- This does work for some cases however as soon as you start involving nullable
types you will start receiving InvalidCastExceptions
:
A wrapper was written a few years ago to handle this but that isn't perfect either.
Perhaps with dataframes one of the most easy and practical solution is:
data = dplyr::mutate(data, rownum=row_number())
Following code snippet downloads a file.
The file is saved with its filename as in specified url.
import requests
url = "http://example.com/image.jpg"
filename = url.split("/")[-1]
r = requests.get(url, timeout=0.5)
if r.status_code == 200:
with open(filename, 'wb') as f:
f.write(r.content)
I don't know why you think there's no constructor. See the API.
Example how to run program and write stdout and stderr to file with timestamp:
cmd /c ""C:\Program Files (x86)\program.exe" -param fooo >> "c:\dir space\Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1"
Key part is to double quote whole part behind cmd /c
and inside it use double quotes as usual. Also note that date is locale dependent, this example works using US locale.
I got Gunders answer working with my App_GlobalResources by choosing the resources properties and switch "Custom Tool" to "PublicResXFileCodeGenerator" and build action to "Embedded Resource". Please observe Gunders comment below.
Works like a charm :)
You could easily use display:table to vertical-align content and text-align:center to horizontal align your iframe. http://jsfiddle.net/EnmD6/7/
html {
display:table;
height:100%;
width:100%;
}
body {
display:table-cell;
vertical-align:middle;
}
#top-element {
position:absolute;
top:0;
left:0;
background:orange;
width:100%;
}
#iframe-wrapper {
text-align:center;
}
version with table-row http://jsfiddle.net/EnmD6/9/
html {
height:100%;
width:100%;
}
body {
display:table;
height:100%;
width:100%;
margin:0;
}
#top-element {
display:table-row;
background:orange;
width:100%;
}
#iframe-wrapper {
display:table-cell;
height:100%;
vertical-align:middle;
text-align:center;
}
For nested structures of different depth, i.e. {node: {leaf: 4}, leaf: 1}
, this will work (using lodash or underscore):
function getMaxValue(d){
if(typeof d === "number") {
return d;
} else if(typeof d === "object") {
return _.max(_.map(_.keys(d), function(key) {
return getMaxValue(d[key]);
}));
} else {
return false;
}
}
As mentioned, you can use:
=Format(Fields!Price.Value, "C")
A digit after the "C" will specify precision:
=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")
You can also use Excel-style masks like this:
=Format(Fields!Price.Value, "#,##0.00")
Haven't tested the last one, but there's the idea. Also works with dates:
=Format(Fields!Date.Value, "yyyy-MM-dd")
I've tried lots of different answers in different forums. I guess it depends on the machine your developing. But I haved used the statement
ax.lines = []
and works perfectly. I don't use cla()
cause it deletes all the definitions I've made to the plot
Ex.
pylab.setp(_self.ax.get_yticklabels(), fontsize=8)
but I've tried deleting the lines many times. Also using the weakref library to check the reference to that line while I was deleting but nothing worked for me.
Hope this works for someone else =D
If I understood correctly, I would change the HTML to something like this:
<div id="shop">
<div class="content">
<img src="http://placehold.it/182x121"/>
<a href="#">Counter-Strike 1.6 Steam</a>
</div>
</div>
Then I would be able to use position:absolute
and position:relative
to force the blue button down.
I have created a jsfiddle: http://jsfiddle.net/y9w99/
NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* firstBit = [foo objectAtIndex: 0];
Update 7/3/2018:
Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:
let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]
Although note that it gives you an array of Substring
. If you need to convert these back to ordinary strings, use map
let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]
or
let firstBit = String(substrings[0])
Press Shift and the first mouse button. You can change the font size in the following way: This website has more detail.
If the binary is something more than a dll or something that can be edited directly like an image, or a blend file (and you don't need to trash/select one file or the other) a real merge would be some like:
I suggest searching for a diff tool oriented to what are your binary file, for example, there are some free ones for image files for example
and compare them.
If there is no diff tool out there for comparing your files, then if you have the original generator of the bin file (that is, there exist an editor for it... like blender 3d, you can then manually inspect those files, also see the logs, and ask the other person what you should include) and do output of the files with https://git-scm.com/book/es/v2/Git-Tools-Advanced-Merging#_manual_remerge
$ git show :1:hello.blend > hello.common.blend
$ git show :2:hello.blend > hello.ours.blend
$ git show :3:hello.blend > hello.theirs.blend
Vartec's answer with cURL didn't work for me. It did, with a slight improvement due to my specific problem.
e.g.,
When there is a redirect on the server (like when you are trying to save the facebook profile image) you will need following option set:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
The full solution becomes:
$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
Maybe help, if you want to add some filter:
context.Persons
.Where(c => c.state == myState)
.Select(c => c.age)
.DefaultIfEmpty(0)
.Max();
Map<Integer, Point2D> hm = new HashMap<Integer, Point2D>();
Simple example using an iframe
function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
};
Then just call the function wherever you want:
downloadURL('path/to/my/file');
I prepared following commands to find concise information about a Linux system:
clear
echo "\n----------OS Information------------"
hostnamectl | grep "Static hostname:"
hostnamectl | tail -n 3
echo "\n----------Memory Information------------"
cat /proc/meminfo | grep MemTotal
echo "\n----------CPU Information------------"
echo -n "Number of core(s): "
cat /proc/cpuinfo | grep "processor" | wc -l
cat /proc/cpuinfo | grep "model name" | head -n 1
echo "\n----------Disk Information------------"
echo -n "Total Size: "
df -h --total | tail -n 1| awk '{print $2}'
echo -n "Used: "
df -h --total | tail -n 1| awk '{print $3}'
echo -n "Available: "
df -h --total | tail -n 1| awk '{print $4}'
echo "\n-------------------------------------\n"
Copy and paste in an sh file like info.sh and then run it using command sh info.sh
It's really rather sad that none of the books published on Selenium/Python and most of the comments on this issue via Google do not clearly explain the pathing logic to set this up on Mac (everything is Windows!!!!). The YouTube videos all pickup at the "after" you've got the pathing setup (in my mind, the cheap way out!). So, for you wonderful Mac users, use the following to edit your Bash path files:
touch ~/.bash_profile; open ~/.bash_profile*
Then add a path something like this....
# Setting PATH for geckodriver
PATH=“/usr/bin/geckodriver:${PATH}”
export PATH
# Setting PATH for Selenium Firefox
PATH=“~/Users/yourNamePATH/VEnvPythonInterpreter/lib/python2.7/site-packages/selenium/webdriver/firefox/:${PATH}”
export PATH
# Setting PATH for executable on Firefox driver
PATH=“/Users/yournamePATH/VEnvPythonInterpreter/lib/python2.7/site-packages/selenium/webdriver/common/service.py:${PATH}”
export PATH*
This worked for me. My concern is when will the Selenium Windows community start playing the real game and include us Mac users into their arrogant club membership.
That is partly possible (for max 2 devices), because device can be connected only to one other device same time. Better solution in your case will be create an TCP server which sends informations to other devices - but that, of course, requires internet connection. Read also about Samsung Chord API - it provides functions which you need, but then every devices have to be connected to one and the same Wi-Fi network
This is now possible with JPA 2.1:
@Column(name = "RIGHT")
@Enumerated(EnumType.STRING)
private Right right;
Further details:
Try this:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
print(currentCell.textLabel!.text)
Linker & Interpreter are mutually exclusive Interpreter getting code line by line and execute line by line.
adding the following code in viewDidLayoutSubviews
worked for me with Autolayout. After trying all the answers:
- (void)viewDidLayoutSubviews
{
self.activationScrollView.contentSize = CGSizeMake(IPHONE_SCREEN_WIDTH, 620);
}
//set the height of content size as required
an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers...
I have replaced the printf
calls with calls to warning
in the C-code now. It will be effective in the version 2.17.2 which should be available tomorrow night. Then you should be able to avoid the warnings with suppressWarnings()
or any of the other above mentioned methods.
suppressWarnings({ your code })
diff -r dir1 dir2 | grep dir1 | awk '{print $4}' > difference1.txt
Explanation:
diff -r dir1 dir2
shows which files are only in dir1 and those only in dir2 and also the changes of the files present in both directories if any.
diff -r dir1 dir2 | grep dir1
shows which files are only in dir1
awk
to print only filename.
Another solution is the following:
ISNULL(NULLIF(DATEPART(dw,DateField)-1,0),7)
I made some modifications to original Jibberboy2000 script Hope it'll be usefull for someone
str = '**ANY HTML CONTENT HERE**';
str=str.replace(/<\s*br\/*>/gi, "\n");
str=str.replace(/<\s*a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) ");
str=str.replace(/<\s*\/*.+?>/ig, "\n");
str=str.replace(/ {2,}/gi, " ");
str=str.replace(/\n+\s*/gi, "\n\n");
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
If you just want to programmatically (as oppossed to giving the user a link to open in a browser) download a file through the Google Drive API, I would suggest using the downloadUrl
of the file instead of the webContentLink
, as documented here: https://developers.google.com/drive/web/manage-downloads
Try using in
like this:
>>> x = 'hello'
>>> y = 'll'
>>> y in x
True
In the "disable" script, the order by clause should be that:
ORDER BY c.constraint_type DESC, c.last_change DESC
The goal of this clause is disable the constraints in the right order.
Remember that char
is an integral type, and thus can be given an integer value, as well as a char constant.
char c = 0x2202;//aka 8706 in decimal. \u codepoints are in hex.
String s = String.valueOf(c);
So I agree there are some apps that you can configured to open on one screen by maximizing or right clicking and moving/sizing screen, then close and reopen. However, there are others that will only open on the main screen.
What I've done to resolve: set the monitor you prefer stubborn apps to open on, as monitor 1 and the your other monitor as 2, then change your monitor 2 to be the primary - so your desktop settings and start bar remain. Hope this helps.
See the git-pull man page:
git pull [options] [<repository> [<refspec>...]]
and in the examples section:
Merge into the current branch the remote branch next:
$ git pull origin next
So I imagine you want to do something like:
git pull origin dev
To set it up so that it does this by default while you're on the dev branch:
git branch --set-upstream-to dev origin/dev
You can sometimes get this if you accidentally import/embed the same JavaScript file twice, worth checking in your resources tab of the inspector.
It must be synchronized, using an object lock, stateless, or immutable.
link: http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
Did you include "Management Tools" as a chosen option during setup?
Ensure this option is selected, and SQL Server Management Studio will be installed on the machine.
You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod:
MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
For a static method, pass null
as the first argument to Invoke
. That's nothing to do with generic methods - it's just normal reflection.
As noted, a lot of this is simpler as of C# 4 using dynamic
- if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.
Since other SO answers link to this question it's worth noting that there is another option now in PyOxidizer.
It's a rust utility which works in some of the same ways as pyinstaller, however has some additional features detailed here, to summarize the key ones:
onefile
mode(One other advantage of pyoxidizer
is that it does not seem to suffer from the GLIBC_X.XX not found
problem that can crop up with pyinstaller if you've created your binary on a system that has a glibc version newer than the target system).
Overall pyinstaller is much simpler to use than PyOxidizer, which often requires some complexity in the configuration file, and it's less Pythony since it's written in Rust and uses a configuration file format not very familiar in the Python world, but PyOxidizer does some more advanced stuff, especially if you are looking to produce single binaries (which is not pyinstaller's default).
N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):
N[i]/2
will be a float64
but range()
expects an integer. Just cast the call to
for j in range(int(N[i]/2)):
Very, very good, thanks to everyone who contributed to this discussion. So if you don't want to deal with inconvenience of extending the class you can do the following (implemented for the right drawable only)
this.keyword = (AutoCompleteTextView) findViewById(R.id.search);
this.keyword.setOnTouchListener(new RightDrawableOnTouchListener(keyword) {
@Override
public boolean onDrawableTouch(final MotionEvent event) {
return onClickSearch(keyword,event);
}
});
private boolean onClickSearch(final View view, MotionEvent event) {
// do something
event.setAction(MotionEvent.ACTION_CANCEL);
return false;
}
And here's bare-bone listener implementation based on @Mark's answer
public abstract class RightDrawableOnTouchListener implements OnTouchListener {
Drawable drawable;
private int fuzz = 10;
/**
* @param keyword
*/
public RightDrawableOnTouchListener(TextView view) {
super();
final Drawable[] drawables = view.getCompoundDrawables();
if (drawables != null && drawables.length == 4)
this.drawable = drawables[2];
}
/*
* (non-Javadoc)
*
* @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
*/
@Override
public boolean onTouch(final View v, final MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN && drawable != null) {
final int x = (int) event.getX();
final int y = (int) event.getY();
final Rect bounds = drawable.getBounds();
if (x >= (v.getRight() - bounds.width() - fuzz) && x <= (v.getRight() - v.getPaddingRight() + fuzz)
&& y >= (v.getPaddingTop() - fuzz) && y <= (v.getHeight() - v.getPaddingBottom()) + fuzz) {
return onDrawableTouch(event);
}
}
return false;
}
public abstract boolean onDrawableTouch(final MotionEvent event);
}
You need to add onsubmit at your form:
<form action="YOUR_URL" method="post" accept-charset="utf-8" onsubmit="return validateRegisterForm();">
And the script will be like this:
function validateRegisterForm(){
if(SOMETHING IS WRONG)
{
alert("validation failed");
event.preventDefault();
return false;
}else{
alert("validations passed");
return true;
}
}
This works for me everytime :)
From Wikipedia
The
stdlib.h
andstddef.h
header files define a datatype calledsize_t
1 which is used to represent the size of an object. Library functions that take sizes expect them to be of typesize_t
, and the sizeof operator evaluates tosize_t
.The actual type of
size_t
is platform-dependent; a common mistake is to assumesize_t
is the same as unsigned int, which can lead to programming errors,2 particularly as 64-bit architectures become more prevalent.
From C99 7.17.1/2
The following types and macros are defined in the standard header
stddef.h
<snip>
size_t
which is the unsigned integer type of the result of the sizeof operator
df[df$aged <= df$laclen, ]
Should do the trick. The square brackets allow you to index based on a logical expression.
If using Vagrant try reloading your box. This solved my issue.
In Azure environment with Basic website that has 1 Instance.I tried to insert a Batch of 1000 records at a time out of 25000 records using for loop it took 11.5 min but in parallel execution it took less than a minute.So I recommend using TPL(Task Parallel Library).
var count = (you collection / 1000) + 1;
Parallel.For(0, count, x =>
{
ApplicationDbContext db1 = new ApplicationDbContext();
db1.Configuration.AutoDetectChangesEnabled = false;
var records = members.Skip(x * 1000).Take(1000).ToList();
db1.Members.AddRange(records).AsParallel();
db1.SaveChanges();
db1.Dispose();
});
Just set the view as null that will close the AlertDialog simple.
It has been some time since this question has been posted, but maybe it will help someone.
I am using GULP CLI 2.0.1 (installed globally) and GULP 4.0.0 (installed locally) here is how you do it without any additional plugin. I think the code is quite self-explanatory.
var cp = require('child_process'),
{ src, dest, series, parallel, watch } = require('gulp');
// == availableTasks: log available tasks to console
function availableTasks(done) {
var command = 'gulp --tasks-simple';
if (process.argv.indexOf('--verbose') > -1) {
command = 'gulp --tasks';
}
cp.exec(command, function(err, stdout, stderr) {
done(console.log('Available tasks are:\n' + stdout));
});
}
availableTasks.displayName = 'tasks';
availableTasks.description = 'Log available tasks to console as plain text list.';
availableTasks.flags = {
'--verbose': 'Display tasks dependency tree instead of plain text list.'
};
exports.availableTasks = availableTasks;
And run from the console:
gulp availableTasks
Then run and see the differences:
gulp availableTasks --verbose
This is the way to include an external javascript file to you HTML markup.
<script type="text/javascript" src="/js/external-javascript.js"></script>
Where external-javascript.js
is the external file to be included. Make sure the path and the file name are correct while you including it.
<a href="javascript:showCountry('countryCode')">countryCode</a>
The above mentioned method is correct for anchor tags and will work perfectly. But for other elements you should specify the event explicitly.
Example:
<select name="users" onChange="showUser(this.value)">
Thanks, XmindZ
Then, in your javascript:
var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);
Now you can look at the console, click on the statement and see what is inside blah
And for PHP 5.3, you can use this function, which can be embedded in a class or used in procedural style:
http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php
This should do it:
UPDATE ProductReviews
SET ProductReviews.status = '0'
FROM ProductReviews
INNER JOIN products
ON ProductReviews.pid = products.id
WHERE ProductReviews.id = '17190'
AND products.shopkeeper = '89137'
Don't use LONGs, use CLOB instead. You can index and search CLOBs like VARCHAR2.
Additionally, querying with a leading wildcard(%) will ALWAYS result in a full-table-scan. Look into Oracle Text indexes instead.
You can use pop()
:
x=[2,3,4,5,6,7]
print(x.pop(2))
use maven it will download all the required jar files for you.
in this case you need the below jar files:
slf4j-log4j12-1.6.1.jar slf4j-api-1.6.1.jar
These jars will also depend on the cassandra version which you are running. There are dependencies with cassandra version , jar version and jdk version you use.
You can use : jdk1.6 with : cassandra 1.1.12 and the above jars.
If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.
web.config
file of your application.web.config
file.Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…
If you like, you could declare an infix
operator
to do it.
// Put this at file level anywhere in your project
infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// ...
// Then you can do this...
let i = 2 ^^ 3
// ... or
println("2³ = \(2 ^^ 3)") // Prints 2³ = 8
I used two carets so you can still use the XOR operator.
Update for Swift 3
In Swift 3 the "magic number" precedence
is replaced by precedencegroups
:
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// ...
// Then you can do this...
let i2 = 2 ^^ 3
// ... or
print("2³ = \(2 ^^ 3)") // Prints 2³ = 8
I'd use the different methods based on how I wanted to reference the items.
Use foreach if you just want the current item.
Use for if you need an indexer to do relative comparisons. (I.e. how does this compare to the previous/next item?)
I have never noticed a performance difference. I'd wait until having a performance issue before worrying about it.
I tried to implement the result of Nick which is:
$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');
But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:
$("#modal_popup").html(data);
$("#modal_popup").dialog('option', 'title', 'My New Title');
$("#modal_popup").dialog({ width: 950, height: 550);
I fixed this by adding the title to the javascript function arguments of each dialog on the page:
function show_popup1() {
$("#modal_popup").html(data);
$("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});
}
function show_popup2() {
$("#modal_popup").html(data);
$("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});
}
document.location
is an object, not a string. It returns (by default) the full path, but it actually holds more info than that.
Shortcut for solution: document.location.toString().substring(2,3);
Or use document.location.href
or window.location.href
You can provide padding to an input like this:
HTML:
<input type=text id=firstname />
CSS:
input {
width: 250px;
padding: 5px;
}
however I would also add:
input {
width: 250px;
padding: 5px;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
Box sizing makes the input width stay at 250px rather than increase to 260px due to the padding.
From jQuery Docs:
const height = $(window).height();
const scrollTop = $(window).scrollTop();
http://api.jquery.com/scrollTop/
http://api.jquery.com/height/
I also had the same issue. I fixed this by installing the .NET framework version 4.5.
DateTime.now.new_offset(0)
will work in standard Ruby (i.e. without ActiveSupport).
You could try running the "mvn site" command and see what transitive dependencies you have, and then resolve potential conflicts (by ommitting an implicit dependency somewhere). Just a guess (it's a bit difficult to know what the problem could be without seeing your pom info)...
You can do this replacing position:absolute;
by position:fixed;
.
You're looking for http_build_query()
.
Since you already have sent some data,
System.out.println("going to demo.jsp");
you won't be able to send a redirect.
To answer the title of your question directly because this comes up in Google first:
YES, TypeScript can export a function!
Here is a direct quote from the TS Documentation:
"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."
There are ports of flex and bison for windows here: http://gnuwin32.sourceforge.net/
flex is the free implementation of lex. bison is the free implementation of yacc.
It seems the interface has changed in .NET 4.0. There is the following method that achieves all of the above. As Tommy Engebretsen suggested, putting it in a TextChanged event handler makes it automatic.
textBox1.ScrollToEnd();
You need to check that you have inserted v4 library and compile library? You must not repeat library in your app or your dependence program.
delete the repeat library so that just one V4 remains.
in your app dir build.gradle
file
add this command:
android{
configurations {
all*.exclude group: 'com.android.support', module: 'support-v4'
all*.exclude group: 'com.android.support', module: 'support-annotations'
}
}
it works for me! You can try it!
Make sure to watch your selectors. You appear to have forgotten the #
for div2
. Additionally, you can toggle the visibility of many elements at once with .toggle()
:
// Short-form of `document.ready`
$(function(){
$("#div2").hide();
$("#preview").on("click", function(){
$("#div1, #div2").toggle();
});
});
There is also a npm module, that add last
to Array.prototype
npm install array-prototype-last --save
usage
require('array-prototype-last');
[1, 2, 3].last; //=> 3
[].last; //=> undefined
I have a similar problem, I tested adding code and found some interesting results. With this code I add, I can deduce that depending on the "provider" to use, the firm can be different? (because the data included in the encryption is not always equal in all providers).
Conclusion.- Signature Decipher= ???(trash) + DigestInfo (if we know the value of "trash", the digital signatures will be equal)
Input data: This is the message being signed
Digest: 62b0a9ef15461c82766fb5bdaae9edbe4ac2e067
DigestInfo: 3021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067
Signature Decipher: 1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff003021300906052b0e03021a0500041462b0a9ef15461c82766fb5bdaae9edbe4ac2e067
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
public class prueba {
/**
* @param args
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
* @throws NoSuchPaddingException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*///
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
// TODO Auto-generated method stub
KeyPair keyPair = KeyPairGenerator.getInstance("RSA","BC").generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey puKey = keyPair.getPublic();
String plaintext = "This is the message being signed";
// Hacer la firma
Signature instance = Signature.getInstance("SHA1withRSA","BC");
instance.initSign(privateKey);
instance.update((plaintext).getBytes());
byte[] signature = instance.sign();
// En dos partes primero hago un Hash
MessageDigest digest = MessageDigest.getInstance("SHA1", "BC");
byte[] hash = digest.digest((plaintext).getBytes());
// El digest es identico a openssl dgst -sha1 texto.txt
//MessageDigest sha1 = MessageDigest.getInstance("SHA1","BC");
//byte[] digest = sha1.digest((plaintext).getBytes());
AlgorithmIdentifier digestAlgorithm = new AlgorithmIdentifier(new
DERObjectIdentifier("1.3.14.3.2.26"), null);
// create the digest info
DigestInfo di = new DigestInfo(digestAlgorithm, hash);
byte[] digestInfo = di.getDEREncoded();
//Luego cifro el hash
Cipher cipher = Cipher.getInstance("RSA","BC");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digestInfo);
//byte[] cipherText = cipher.doFinal(digest2);
Cipher cipher2 = Cipher.getInstance("RSA","BC");
cipher2.init(Cipher.DECRYPT_MODE, puKey);
byte[] cipherText2 = cipher2.doFinal(signature);
System.out.println("Input data: " + plaintext);
System.out.println("Digest: " + bytes2String(hash));
System.out.println("Signature: " + bytes2String(signature));
System.out.println("Signature2: " + bytes2String(cipherText));
System.out.println("DigestInfo: " + bytes2String(digestInfo));
System.out.println("Signature Decipher: " + bytes2String(cipherText2));
}
Classes in the default package cannot be imported by classes in packages. This is why you should not use the default package.
var ans = 334 + '';
var temp = ans.toLowerCase();
alert(temp);
this stores the generated pdf file in your custom folder of your project
$filename= "{$membership->id}.pdf";
$filelocation = "D:\\wamp\\www\\project\\custom";//windows
$filelocation = "/var/www/project/custom"; //Linux
$fileNL = $filelocation."\\".$filename;//Windows
$fileNL = $filelocation."/".$filename; //Linux
$this->pdf->Output($fileNL, 'F');
a regular grammer is never ambiguous because it is either left linear or right linear so we cant make two decision tree for regular grammer so it is always unambiguous.but othert than regular grammar all are may or may not be regular
<<
is a binary shift, shifting 1 to the left 8 places.
4'b0001 << 1 => 4'b0010
>>
is a binary right shift adding 0's to the MSB.
>>>
is a signed shift which maintains the value of the MSB if the left input is signed.
4'sb1011 >> 1 => 0101
4'sb1011 >>> 1 => 1101
Three ways to indicate left operand is signed:
module shift;
logic [3:0] test1 = 4'b1000;
logic signed [3:0] test2 = 4'b1000;
initial begin
$display("%b", $signed(test1) >>> 1 ); //Explicitly set as signed
$display("%b", test2 >>> 1 ); //Declared as signed type
$display("%b", 4'sb1000 >>> 1 ); //Signed constant
$finish;
end
endmodule
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
In a batch file (Windows 7 and above) I found this method most reliable
Call :logging >"C:\Temp\NAME_Your_Log_File.txt" 2>&1
:logging
TITLE "Logging Commands"
ECHO "Read this output in your log file"
ECHO ..
Prompt $_
COLOR 0F
Obviously, use whatever commands you want and the output will be directed to the text file. Using this method is reliable HOWEVER there is NO output on the screen.
One thing not mentioned is scoping issues. Not a great example, but here's the case where I ran into the problem:
def conf_decorator(dec):
"""Enables behavior like this:
@threaded
def f(): ...
or
@threaded(thread=KThread)
def f(): ...
(assuming threaded is wrapped with this function.)
Sends any accumulated kwargs to threaded.
"""
c_kwargs = {}
@wraps(dec)
def wrapped(f=None, **kwargs):
if f:
r = dec(f, **c_kwargs)
c_kwargs = {}
return r
else:
c_kwargs.update(kwargs) #<- UnboundLocalError: local variable 'c_kwargs' referenced before assignment
return wrapped
return wrapped
The solution is to replace c_kwargs = {}
with c_kwargs.clear()
If someone thinks up a more practical example, feel free to edit this post.
Here goes my 2 cents contribution:
I have a optimization problem where I use a Nlopt library for it. I initializing the class and some of its methods, I was using in several other parts of the code.
I was having ramdom results even if applying the same numerical problem.
I just realized that by doing it, some spurius data was contained in the object when it should have no issues at all. After using del, I guess the memory is being properly cleared and it might be an internal issue to that class where some variables might not be liking to be reused without proper constructor.
If you want examples of Algorithms/Group of Statements with Time complexity as given in the question, here is a small list -
O(1)
timeO(n)
timeIn a nutshell, all Brute Force Algorithms, or Noob ones which require linearity, are based on O(n) time complexity
O(log n)
timeO(n log n)
timeThe factor of 'log n' is introduced by bringing into consideration Divide and Conquer. Some of these algorithms are the best optimized ones and used frequently.
O(n^2)
timeThese ones are supposed to be the less efficient algorithms if their O(nlogn) counterparts are present. The general application may be Brute Force here.
there is a limited alternative you can use
header:
class std_int_vector;
class A{
std_int_vector* vector;
public:
A();
virtual ~A();
};
cpp:
#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}
A::A() : vector(new std_int_vector()) {}
[...]
not tested in real programs, so expect it to be non-perfect.
I usually use numpy sum over the logical condition column:
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)
2
This seems to me slightly shorter than the solution presented above
Try to not use setInterval
.
You can resend request to server after successful response with timeout.
jQuery:
sendRequest(); //call function
function sendRequest(){
$.ajax({
url: "test.php",
success:
function(result){
$('#links').text(result); //insert text of test.php into your div
setTimeout(function(){
sendRequest(); //this will send request again and again;
}, 5000);
}
});
}
URL url = Test.class.getResource(args[0]); // reading demo file path from
// same location where class
File input=null;
try {
input = new File(url.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I store my non-Github repo's on Dropbox. One caveat I ran into was syncing after a reinstall. Dropbox will download the smallest files first before moving to the larger ones. Not an issue if you start at night and come back after the weekend :-)
My thread - http://forums.dropbox.com/topic.php?id=29984&replies=6
If git branch -r
shows a lot of remote-tracking branches that you're not interested in and you want to remove them only from local, use the following command:
git branch -r | grep -Ev 'HEAD|master|develop' | xargs -r git branch -rd
A safer version would be to only remove the merged ones:
git branch -r --merged | grep -Ev 'HEAD|master|develop' | xargs -r git branch -rd
This might be useful for large projects, where you don't need the feature branches of other teammates but there're lots of remote-tracking branches fetched upon the initial clone.
However, this step alone is not sufficient, because those deleted remote-tracking branches would come back upon next git fetch
.
To stop fetching those remote-tracking branches you need to explicitly specify the refs to fetch in .git/config:
[remote "origin"]
# fetch = +refs/heads/*:refs/remotes/origin/* ### don't fetch everything
fetch = +refs/heads/master:refs/remotes/origin/master
fetch = +refs/heads/develop:refs/remotes/origin/develop
fetch = +refs/heads/release/*:refs/remotes/origin/release/*
In the above example we only fetch master
, develop
and release branches, feel free to adapt as you need.
The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0
[Ref 1].
The second is more readable.
The choice depends on user preference or the one which your coding standard mandates.
[Ref 1] Reference C99 Standard 6.7.8.21:
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
Good Read:
C and C++ : Partial initialization of automatic structure
This is what i have noticed for the above issue :- If the checkout folder (folder where your pom project resides) is same as the eclipse workspace folder then i am getting this issue
when i used a separate workspace folder for importing the project, eclipse did worked smoothly :)
Your execution plan should make this clear; the JOIN takes precedence, after which the results are filtered.
insert into OPT (email, campaign_id)
select 'mom@coxnet' as email, 100 as campaign_id from dual MINUS
select email, campaign_id from OPT;
If there is already a record with [email protected]
/100
in OPT, the MINUS
will subtract this record from the select 'mom@coxnet' as email, 100 as campaign_id from dual
record and nothing will be inserted. On the other hand, if there is no such record, the MINUS
does not subract anything and the values mom@coxnet
/100
will be inserted.
As p.marino has already pointed out, merge
is probably the better (and more correct) solution for your problem as it is specifically designed to solve your task.
Note that you can use a variable in a slice:
l = ['a',' b',' c',' d',' e']
c_index = l.index("c")
l2 = l[:c_index]
This would put the first two entries of l in l2
Maybe someone encounters a similar warning I had with a Scala project.
Package names doesn't correspond to directories structure, this may cause problems with resolve to classes from this file Inspection for files with package statement which does not correspond to package structure.
The file was in the right location, so the helper solutions the IDE provides are not helpful The Move File says file already exists (which is true) and Rename Package would actually move it to the incorrect package.
The problem is that if you have Scala Objects, you have to make sure that the first object in the file has the same name as the filename, so the solution is to move the objects inside the file.
Another alternative to use the exact json within javascript. As it is Javascript Object Notation you can just create your object directly with the json notation. If you store this in a .js file you can use the object in your application. This was a useful option for me when I had some static json data that I wanted to cache in a file separately from the rest of my app.
//Just hard code json directly within JS
//here I create an object CLC that represents the json!
$scope.CLC = {
"ContentLayouts": [
{
"ContentLayoutID": 1,
"ContentLayoutTitle": "Right",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/right.png",
"ContentLayoutIndex": 0,
"IsDefault": true
},
{
"ContentLayoutID": 2,
"ContentLayoutTitle": "Bottom",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/bottom.png",
"ContentLayoutIndex": 1,
"IsDefault": false
},
{
"ContentLayoutID": 3,
"ContentLayoutTitle": "Top",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/top.png",
"ContentLayoutIndex": 2,
"IsDefault": false
}
]
};
First of all, it's worth remembering that all Java archive files (.jar
/.war
/etc...) are all basically just fancy.zip
files, with a few added manifests and metadata.
Second, to tackle this problem I personally use several tools which handle this problem on all levels:
.class
filesjar
s. Well worth a try.The advantage of all the aforementioned, is that I do not need to hold any other external tool which clutters my work environment. Everything I will ever need from one of those files can be handled inside my IDE or diffed with other files natively.
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Replace '_' || '/' to your own need
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.
Use this one:
Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
Note that when you're using Dim range1, rng As range
, only rng
has type of Range
, but range1
is Variant
. That's why I'm using Dim range1 As Range, rng As Range
.
About meaning of parameters you can read is MSDN, but in short:
Type:=xlValidateList
means validation type, in that case you should select value from listAlertStyle:=xlValidAlertStop
specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.Operator:= xlBetween
is odd. It can be used only if two formulas are provided for validation.Formula1:="='" & ws.Name & "'!" & range1.Address
for list data validation provides address of list with values (in format =Sheet!A1:A5
)From at least, the 2.0
version, Spring-Data-Jpa
modified findOne()
.
Now, findOne()
has neither the same signature nor the same behavior.
Previously, it was defined in the CrudRepository
interface as:
T findOne(ID primaryKey);
Now, the single findOne()
method that you will find in CrudRepository
is the one defined in the QueryByExampleExecutor
interface as:
<S extends T> Optional<S> findOne(Example<S> example);
That is implemented finally by SimpleJpaRepository
, the default implementation of the CrudRepository
interface.
This method is a query by example search and you don't want that as a replacement.
In fact, the method with the same behavior is still there in the new API, but the method name has changed.
It was renamed from findOne()
to findById()
in the CrudRepository
interface :
Optional<T> findById(ID id);
Now it returns an Optional
, which is not so bad to prevent NullPointerException
.
So, the actual method to invoke is now Optional<T> findById(ID id)
.
How to use that?
Learning Optional
usage.
Here's important information about its specification:
A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).
Some hints on how to use Optional
with Optional<T> findById(ID id)
.
Generally, as you look for an entity by id, you want to return it or make a particular processing if that is not retrieved.
Here are three classical usage examples.
You could write :
Foo foo = repository.findById(id)
.orElse(new Foo());
or get a null
default value if it makes sense (same behavior as before the API change) :
Foo foo = repository.findById(id)
.orElse(null);
You could write :
return repository.findById(id)
.orElseThrow(() -> new EntityNotFoundException(id));
You could write :
Optional<Foo> fooOptional = fooRepository.findById(id);
if (fooOptional.isPresent()) {
Foo foo = fooOptional.get();
// processing with foo ...
} else {
// alternative processing....
}
I ended up doing the following and it works.
public static string Serialize(object obj)
{
using (MemoryStream memoryStream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
public static object Deserialize(string xml, Type toType)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
DataContractSerializer serializer = new DataContractSerializer(toType);
return serializer.ReadObject(reader);
}
}
It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.
Array values = Enum.GetValues(typeof(myEnum));
foreach( MyEnum val in values )
{
Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}
Or, you can cast the System.Array that is returned:
string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));
for( int i = 0; i < names.Length; i++ )
{
print(names[i], values[i]);
}
But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?
One way, using regular expressions:
>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup 20 99 That s ridiculous '
\w
will match alphanumeric characters and underscores
[^\w]
will match anything that's not alphanumeric or underscore
http://api.jqueryui.com/datepicker/#option-maxDate
$( ".selector" ).datepicker( "option", "maxDate", '+0m +0w' );
From w3 schools:
<style>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<div class="tooltip">Hover over me
<img src="/pathtoimage" class="tooltiptext">
</div>
Sounds like about what you want
Mozilla's MDN suggests something like the following [source]:
p {
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
}
There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:
I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.
You can also do it this way to reference the previous branch implicitly:
git checkout mainline
git pull
git merge -
git push
You will always only get an indent error if there is actually an indent error. Double check that your final line is indented the same was as the other lines -- either with spaces or with tabs. Most likely, some of the lines had spaces (or tabs) and the other line had tabs (or spaces).
Trust in the error message -- if it says something specific, assume it to be true and figure out why.
I found several functions defined in http://tw1.php.net/unpack are very useful.
They can covert string to byte array and vice versa.
Take byteStr2byteArray() as an example:
<?php
function byteStr2byteArray($s) {
return array_slice(unpack("C*", "\0".$s), 1);
}
$msg = "abcdefghijk";
$byte_array = byteStr2byteArray($msg);
for($i=0;$i<count($byte_array);$i++)
{
printf("0x%02x ", $byte_array[$i]);
}
?>
Use substring function
Check this out http://jsfiddle.net/kuc5as83/
var string = "1234567890"
var substr=string.substr(-8);
document.write(substr);
Output >> 34567890
substr(-8)
will keep last 8 chars
var substr=string.substr(8);
document.write(substr);
Output >> 90
substr(8)
will keep last 2 chars
var substr=string.substr(0, 8);
document.write(substr);
Output >> 12345678
substr(0, 8)
will keep first 8 chars
Check this out string.substr(start,length)
Adding this here because the more relevant questions have all been marked as duplicates pointing here…
My situation is simpler:
a[href='#something']
)e.preventDefault()
$("html,body").stop(true,true).animate({ "scrollTop": linkoffset.top }, scrollspeed, "swing" );
window.location = link;
This way, the scroll occurs, and there's no jump when the location is updated.
Sometimes you must change the name (or check to get it automatically from compiler).
Example:
Filename = amp2-rot.png
It is not working as:
PictureBoxName.Image = resources.GetObject("amp2-rot.png")
It works, just as amp2_rot
for me:
PictureBox_L1.Image = My.Resources.Resource.amp2_rot
Also, if you got this error and installed mysql via Homebrew, I found that this works (though you need to change "5.6.12" to your own version):
/usr/local/Cellar/mysql/5.6.12/bin/mysql.server restart
I just created a file ~/restartMysql.sh in my home directory (with only the line above in it) so that I can just use this whenever MySQL is acting up
Your code is correct. I tested:
r = requests.get("http://www.google.com")
print(r.content)
And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!
There is an important difference between std::min
, std::max
and fmin
and fmax
.
std::min(-0.0,0.0) = -0.0
std::max(-0.0,0.0) = -0.0
whereas
fmin(-0.0, 0.0) = -0.0
fmax(-0.0, 0.0) = 0.0
So std::min
is not a 1-1 substitute for fmin
. The functions std::min
and std::max
are not commutative. To get the same result with doubles with fmin
and fmax
one should swap the arguments
fmin(-0.0, 0.0) = std::min(-0.0, 0.0)
fmax(-0.0, 0.0) = std::max( 0.0, -0.0)
But as far as I can tell all these functions are implementation defined anyway in this case so to be 100% sure you have to test how they are implemented.
There is another important difference. For x ! = NaN
:
std::max(Nan,x) = NaN
std::max(x,NaN) = x
std::min(Nan,x) = NaN
std::min(x,NaN) = x
whereas
fmax(Nan,x) = x
fmax(x,NaN) = x
fmin(Nan,x) = x
fmin(x,NaN) = x
fmax
can be emulated with the following code
double myfmax(double x, double y)
{
// z > nan for z != nan is required by C the standard
int xnan = isnan(x), ynan = isnan(y);
if(xnan || ynan) {
if(xnan && !ynan) return y;
if(!xnan && ynan) return x;
return x;
}
// +0 > -0 is preferred by C the standard
if(x==0 && y==0) {
int xs = signbit(x), ys = signbit(y);
if(xs && !ys) return y;
if(!xs && ys) return x;
return x;
}
return std::max(x,y);
}
This shows that std::max
is a subset of fmax
.
Looking at the assembly shows that Clang uses builtin code for fmax
and fmin
whereas GCC calls them from a math library. The assembly for clang for fmax
with -O3
is
movapd xmm2, xmm0
cmpunordsd xmm2, xmm2
movapd xmm3, xmm2
andpd xmm3, xmm1
maxsd xmm1, xmm0
andnpd xmm2, xmm1
orpd xmm2, xmm3
movapd xmm0, xmm2
whereas for std::max(double, double)
it is simply
maxsd xmm0, xmm1
However, for GCC and Clang using -Ofast
fmax
becomes simply
maxsd xmm0, xmm1
So this shows once again that std::max
is a subset of fmax
and that when you use a looser floating point model which does not have nan
or signed zero then fmax
and std::max
are the same. The same argument obviously applies to fmin
and std::min
.
Personally, I've used this before to build a JSON to POJO converter. In the case that the JSONObject processed with the function contains an array or nested JSONObjects (implying that the data here isn't of a primitive type or String
), I attempt to invoke the setter method using class.cast()
in this fashion:
public static Object convertResponse(Class<?> clazz, JSONObject readResultObject) {
...
for(Method m : clazz.getMethods()) {
if(!m.isAnnotationPresent(convertResultIgnore.class) &&
m.getName().toLowerCase().startsWith("set")) {
...
m.invoke(returnObject, m.getParameters()[0].getClass().cast(convertResponse(m.getParameters()[0].getType(), readResultObject.getJSONObject(key))));
}
...
}
Not sure if this is extremely helpful, but as said here before, reflection is one of the very few legitimate use case of class.cast()
I can think of, at least you have another example now.
<script src="~/fileupload/fileinput.min.js"></script>
<link href="~/fileupload/fileinput.min.css" rel="stylesheet" />
Download above files named fileinput add the path i your index page.
<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"
`enter code here`accept=".pdf" multiple>
</div>
<script>
$("#uploadFile1").fileinput({
autoReplace: true,
maxFileCount: 5
});
</script>
s = s.Replace( """", "" )
Two quotes next to each other will function as the intended " character when inside a string.
To schedule the update to be automatic you should:
If you cannot find the Schedule settings, look under: Properties, Edit, Triggers.
I prefer instanceof
:
if (obj instanceof SomeType) { ... }
which is much more common and readable than SomeType.isInstance(obj)
I'm also surprised these aren't compile time constants. But I suppose you could create these values easily enough by simply executing an instruction that returns such an invalid result. Dividing by 0, log of 0, tan of 90, that kinda thing.
After creating Set just convert it to List and get by index from List:
Set<String> stringsSet = new HashSet<>();
stringsSet.add("string1");
stringsSet.add("string2");
List<String> stringsList = new ArrayList<>(stringsSet);
stringsList.get(0); // "string1";
stringsList.get(1); // "string2";
In case someone being a beginner who tried all of the above and still didn't manage to get the project to work. Check your namespace. In an instance where you copy code from one project to another and you forget to change the namespace of the project then it will also give you this error.
Hope it helps someone.
This example would help you remember *args
, **kwargs
and even super
and inheritance in Python at once.
class base(object):
def __init__(self, base_param):
self.base_param = base_param
class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1
You just need to drag and drop an ImageView
, create the outlet action, link it, and provide an image (Xcode is going to look in your assets
folder for the name you provided (here: "toronto"))
In yourProject/ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imgView.image = UIImage(named: "toronto")
}
}
You can use usort function to create own sorting rules
Alternatively:
const onClickOutsideListener = () => {
alert("click outside")
document.removeEventListener("click", onClickOutsideListener)
}
...
return (
<div
onMouseLeave={() => {
document.addEventListener("click", onClickOutsideListener)
}}
>
...
</div>
insert
is not a recommended way - it is one of the ways to insert into map. The difference with operator[]
is that the insert
can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert
. operator[]
needs the default constructor because the map checks if the element exists. If it doesn't then it creates one using default constructor and returns a reference (or const reference to it).Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.
Simplest version, assuming you're working on the same branch that the file you want is on:
git checkout path/to/file
.
I do this so often that I've got an alias set to gc='git checkout'
.
As I understood, the desired effect you want is to scroll to the end of a list (or scrollable div) when something happens (e.g.: a item is added to the list). If so, you can scroll to the end of a container element (or even the page it self) using only pure Javascript and the VueJS selectors.
var container = this.$el.querySelector("#container");
container.scrollTop = container.scrollHeight;
I've provided a working example in this fiddle: https://jsfiddle.net/my54bhwn
Every time a item is added to the list, the list is scrolled to the end to show the new item.
Hope this help you.
You can configure logging in your settings.py
file.
One example:
if DEBUG:
# will output to your console
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
)
else:
# will output to logging file
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
filename = '/my_log_file.log',
filemode = 'a'
)
However that's dependent upon setting DEBUG, and maybe you don't want to have to worry about how it's set up. See this answer on How can I tell whether my Django application is running on development server or not? for a better way of writing that conditional. Edit: the example above is from a Django 1.1 project, logging configuration in Django has changed somewhat since that version.
// This is wrong
categoryTitle.textColor = [UIColor colorWithRed:188 green:149 blue:88 alpha:1.0];
// This should be
categoryTitle.textColor = [UIColor colorWithRed:188/255 green:149/255 blue:88/255 alpha:1.0];
// In the documentation, the limit of the parameters are mentioned.
Although most of the points are already discussed. But I would like to highlight again one more reason for NaN which is missing.
tf.estimator.DNNClassifier(
hidden_units, feature_columns, model_dir=None, n_classes=2, weight_column=None,
label_vocabulary=None, optimizer='Adagrad', activation_fn=tf.nn.relu,
dropout=None, config=None, warm_start_from=None,
loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE, batch_norm=False
)
By default activation function is "Relu". It could be possible that intermediate layer's generating a negative value and "Relu" convert it into the 0. Which gradually stops training.
I observed the "LeakyRelu" able to solve such problems.
If you use MySQL instead of SQL Server, the syntax is:
UPDATE Table1
INNER JOIN Table2
ON Table1.id = Table2.id
SET Table1.col1 = Table2.col1,
Table1.col2 = Table2.col2
Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.
Replace this:
StreamWriter file2 = new StreamWriter("c:/file.txt");
with this:
StreamWriter file2 = new StreamWriter("c:/file.txt", true);
true
indicates that it appends text.
First of all, you probably don't want the align
environment if you have only one column of equations. In fact, your example is probably best with the cases
environment. But to answer your question directly, used the aligned
environment within equation
- this way the outside environment gives the number:
\begin{equation}
\begin{aligned}
w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1, \\
w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
\end{aligned}
\end{equation}
The documentation of the amsmath
package explains this and more.
If you have a large data frame and need to divide into a variable number of sub data frames rows, like for example each sub dataframe has a max of 4500 rows, this script could help:
max_rows = 4500
dataframes = []
while len(df) > max_rows:
top = df[:max_rows]
dataframes.append(top)
df = df[max_rows:]
else:
dataframes.append(df)
You could then save out these data frames:
for _, frame in enumerate(dataframes):
frame.to_csv(str(_)+'.csv', index=False)
Hope this helps someone!
Jan 2018 UPDATE: When I answered this question last year, I neglected to mention a third way to access Google APIs with JavaScript, and that would be from Node.js apps using its client library, so I added it below.
It's Mar 2017, and most of the answers here are outdated -- the accepted answer now refers to a library that uses an older API version. A more current answer: you can access most Google APIs with JavaScript only. Google provides 3 ways to do this today:
When using the REST API, you need to manage & store your source code as well as perform authorization by rolling your own auth code (see samples above). Apps Script handles this on your behalf, managing the data (reducing the "pain" as mentioned by Ape-inago in their answer), and your code is stored on Google's servers. But your functionality is restricted to what services App Script provides whereas the REST API gives developers much broader access to the API. But hey, it's good to have choices, right? In summary, to answer the OP original question, instead of zero, developers have three ways of accessing Google Sheets using JavaScript.
On UNIX system, suppose binary (executable) name is test. Then we use the following command to list the libraries used in the test is
ldd test
Below works for first tr
of the table under thead
table thead tr:first-child {
background: #f2f2f2;
}
And this works for the first tr
of thead
and tbody
both:
table thead tbody tr:first-child {
background: #f2f2f2;
}
They're nearly identical but bash
has more features – sh
is (more or less) an older subset of bash
.
sh
often means the original Bourne shell
, which predates bash
(Bourne *again* shell
), and was created in 1977. But, in practice, it may be better to think of it as a highly-cross-compatible shell compliant with the POSIX standard from 1992.
Scripts that start with #!/bin/sh
or use the sh
shell usually do so for backwards compatibility. Any unix/linux OS will have an sh
shell. On Ubuntu sh
often invokes dash
and on MacOS it's a special POSIX version of bash
. These shells may be preferred for standard-compliant behavior, speed or backwards compatibility.
bash
is newer than the original sh
, adds more features, and seeks to be backwards compatible with sh
. In theory, sh
programs should run in bash
. bash
is available on nearly all linux/unix machines and usually used by default – with the notable exception of MacOS defaulting to zsh
as of Catalina (10.15). FreeBSD, by default, does not come with bash
installed.
Atom currently does not have a built-in terminal(that I know of), so you would have to install an additional package such as platformio-ide-terminal
.
The following screenshots were taken on a mac.
+
to Install a new packageIt only works for three-digit numbers, but it works
a = int(input())
print(a // 100 + a // 10 % 10 + a % 10)
Create a static constructor to add values in the Dictionary
enum Commands
{
StudentDetail
}
public static class Quires
{
public static Dictionary<Commands, String> quire
= new Dictionary<Commands, String>();
static Quires()
{
quire.add(Commands.StudentDetail,@"SELECT * FROM student_b");
}
}
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
The Dictionary throws a KeyNotFound
exception in the event that the dictionary does not contain your key.
As suggested, ContainsKey
is the appropriate precaution. TryGetValue
is also effective.
This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.
Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \
escapes, etc.
Example:
$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")
The Bash manual has this to say:
Enclosing characters in single quotes (
'
) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.Enclosing characters in double quotes (
"
) preserves the literal value of all characters within the quotes, with the exception of$
,`
,\
, and, when history expansion is enabled,!
. The characters$
and`
retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters:$
,`
,"
,\
, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an!
appearing in double quotes is escaped using a backslash. The backslash preceding the!
is not removed.The special parameters
*
and@
have special meaning when in double quotes (see Shell Parameter Expansion).
I had ETIMEDOUT error, and after putting
{
"proxy":"http://<user>:<password>@<host>:<port>",
"https-proxy":"http://<user>:<password>@<host>:<port>"
}
just worked. I don't know if you have something wrong in the .bowerrc or ECONNRESET can't be solved with this, but I hope this help you ;)
Try to set response dataType property directly:
dataType: 'text'
and put
die('');
in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.
import shutil
import os
import logging
source = '/var/spools/asterisk/monitor'
dest1 = '/tmp/'
files = os.listdir(source)
for f in files:
shutil.move(source+f, dest1)
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s
- %(levelname)s - %(message)s')
logging.info('directories moved')
A little bit cooked code with log feature. You can also configure this to run at some period of time using crontab.
* */1 * * * python /home/yourprogram.py > /dev/null 2>&1
runs every hour! cheers
Just as a note you can also use this for iPads:
activityViewController.popoverPresentationController?.sourceView = sender
So the popover pops from the sender (the button in that case).
TL;DR: The biggest difference in everyday use isn't nested dependencies... it's the difference between modules and globals.
I think the previous posters have covered well some of the basic distinctions. (npm's use of nested dependencies is indeed very helpful in managing large, complex applications, though I don't think it's the most important distinction.)
I'm surprised, however, that nobody has explicitly explained one of the most fundamental distinctions between Bower and npm. If you read the answers above, you'll see the word 'modules' used often in the context of npm. But it's mentioned casually, as if it might even just be a syntax difference.
But this distinction of modules vs. globals (or modules vs. 'scripts') is possibly the most important difference between Bower and npm. The npm approach of putting everything in modules requires you to change the way you write Javascript for the browser, almost certainly for the better.
<script>
TagsAt root, Bower is about loading plain-old script files. Whatever those script files contain, Bower will load them. Which basically means that Bower is just like including all your scripts in plain-old <script>
's in the <head>
of your HTML.
So, same basic approach you're used to, but you get some nice automation conveniences:
bower install
and instantly have what they need, locally.bower.json
, those'll be downloaded for you as well.But beyond that, Bower doesn't change how we write javascript. Nothing about what goes inside the files loaded by Bower needs to change at all. In particular, this means that the resources provided in scripts loaded by Bower will (usually, but not always) still be defined as global variables, available from anywhere in the browser execution context.
All code in Node land (and thus all code loaded via npm) is structured as modules (specifically, as an implementation of the CommonJS module format, or now, as an ES6 module). So, if you use NPM to handle browser-side dependencies (via Browserify or something else that does the same job), you'll structure your code the same way Node does.
Smarter people than I have tackled the question of 'Why modules?', but here's a capsule summary:
window.variable
. The one accident that still tends to occur is assigning this.variable
, not realizing that this
is actually window
in the current context.)To me, the use of modules for front-end code boils down to: working in a much narrower context that's easier to reason about and test, and having greater certainty about what's going on.
It only takes about 30 seconds to learn how to use the CommonJS/Node module syntax. Inside a given JS file, which is going to be a module, you first declare any outside dependencies you want to use, like this:
var React = require('react');
Inside the file/module, you do whatever you normally would, and create some object or function that you'll want to expose to outside users, calling it perhaps myModule
.
At the end of a file, you export whatever you want to share with the world, like this:
module.exports = myModule;
Then, to use a CommonJS-based workflow in the browser, you'll use tools like Browserify to grab all those individual module files, encapsulate their contents at runtime, and inject them into each other as needed.
AND, since ES6 modules (which you'll likely transpile to ES5 with Babel or similar) are gaining wide acceptance, and work both in the browser or in Node 4.0, we should mention a good overview of those as well.
More about patterns for working with modules in this deck.
EDIT (Feb 2017): Facebook's Yarn is a very important potential replacement/supplement for npm these days: fast, deterministic, offline package-management that builds on what npm gives you. It's worth a look for any JS project, particularly since it's so easy to swap it in/out.
EDIT (May 2019) "Bower has finally been deprecated. End of story." (h/t: @DanDascalescu, below, for pithy summary.)
And, while Yarn is still active, a lot of the momentum for it shifted back to npm once it adopted some of Yarn's key features.
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
Use format string
intNum = 123
print "0x%x"%(intNum)
or hex
function.
intNum = 123
print hex(intNum)
import os, os.path
To get (full-path) immediate sub-directories in a directory:
def SubDirPath (d):
return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)])
To get the latest (newest) sub-directory:
def LatestDirectory (d):
return max(SubDirPath(d), key=os.path.getmtime)
You can control the data returned from SQL database by ordering the data returned:
orderby [Name]
If you execute the SQL query from your application, order the data returned. For example, make a function that calls the procedure or executes the SQL and give it a parameter that gets the orderby criteria. Because if you ordered the data returned from database it will consume time but order it since it's executed as you say that you want it to be ordered not from the UI you want it to be ordered in the run time so order it when executing the SQL query.
Directly from the Windows.h header file:
#ifndef WIN32_LEAN_AND_MEAN
#include <cderr.h>
#include <dde.h>
#include <ddeml.h>
#include <dlgs.h>
#ifndef _MAC
#include <lzexpand.h>
#include <mmsystem.h>
#include <nb30.h>
#include <rpc.h>
#endif
#include <shellapi.h>
#ifndef _MAC
#include <winperf.h>
#include <winsock.h>
#endif
#ifndef NOCRYPT
#include <wincrypt.h>
#include <winefs.h>
#include <winscard.h>
#endif
#ifndef NOGDI
#ifndef _MAC
#include <winspool.h>
#ifdef INC_OLE1
#include <ole.h>
#else
#include <ole2.h>
#endif /* !INC_OLE1 */
#endif /* !MAC */
#include <commdlg.h>
#endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */
if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.
Also, from Microsoft's support page:
To speed the build process, Visual C++ and the Windows Headers provide the following new defines:
VC_EXTRALEAN
WIN32_LEAN_AND_MEANYou can use them to reduce the size of the Win32 header files.
Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.