This doesn't directly answer your question, but it does solve your problem...
What make of router do you have? Your router firmware may allow you to set DNS records for your local network. This is what I do with the Tomato firmware
I'm keeping the following list updated for a couple of years now:
1.0.0.0/24
1.1.1.0/24
1.2.3.0/24
8.6.48.0/21
8.8.8.0/24
8.35.192.0/21
8.35.200.0/21
8.34.216.0/21
8.34.208.0/21
23.236.48.0/20
23.251.128.0/19
63.161.156.0/24
63.166.17.128/25
64.9.224.0/19
64.18.0.0/20
64.233.160.0/19
64.233.171.0/24
65.167.144.64/28
65.170.13.0/28
65.171.1.144/28
66.102.0.0/20
66.102.14.0/24
66.249.64.0/19
66.249.92.0/24
66.249.86.0/23
70.32.128.0/19
72.14.192.0/18
74.125.0.0/16
89.207.224.0/21
104.154.0.0/15
104.132.0.0/14
107.167.160.0/19
107.178.192.0/18
108.59.80.0/20
108.170.192.0/18
108.177.0.0/17
130.211.0.0/16
142.250.0.0/15
144.188.128.0/24
146.148.0.0/17
162.216.148.0/22
162.222.176.0/21
172.253.0.0/16
173.194.0.0/16
173.255.112.0/20
192.158.28.0/22
193.142.125.0/28
199.192.112.0/22
199.223.232.0/21
206.160.135.240/24
207.126.144.0/20
208.21.209.0/24
209.85.128.0/17
216.239.32.0/19
My icons had disappeared too. The registry fixes did not work for me either.
This is how I got them back:
Keep it Simple and use Java 8:-
Map<String, AccountGroupMappingModel> mapAccountGroup=CustomerDAO.getAccountGroupMapping();
Map<String, AccountGroupMappingModel> mapH2ToBydAccountGroups =
mapAccountGroup.entrySet().stream()
.collect(Collectors.toMap(e->e.getValue().getH2AccountGroup(),
e ->e.getValue())
);
Whenever you do some form of operation outside of AngularJS, such as doing an Ajax call with jQuery, or binding an event to an element like you have here you need to let AngularJS know to update itself. Here is the code change you need to do:
app.directive("remove", function () {
return function (scope, element, attrs) {
element.bind ("mousedown", function () {
scope.remove(element);
scope.$apply();
})
};
});
app.directive("resize", function () {
return function (scope, element, attrs) {
element.bind ("mousedown", function () {
scope.resize(element);
scope.$apply();
})
};
});
Here is the documentation on it: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply
You could also do it more concisely using
driver.find_element_by_id("some_id").size != 0
If you can't find it in numpy or scipy, here are a couple of quick functions and a point class:
import math
def rect(r, theta):
"""theta in degrees
returns tuple; (float, float); (x,y)
"""
x = r * math.cos(math.radians(theta))
y = r * math.sin(math.radians(theta))
return x,y
def polar(x, y):
"""returns r, theta(degrees)
"""
r = (x ** 2 + y ** 2) ** .5
theta = math.degrees(math.atan2(y,x))
return r, theta
class Point(object):
def __init__(self, x=None, y=None, r=None, theta=None):
"""x and y or r and theta(degrees)
"""
if x and y:
self.c_polar(x, y)
elif r and theta:
self.c_rect(r, theta)
else:
raise ValueError('Must specify x and y or r and theta')
def c_polar(self, x, y, f = polar):
self._x = x
self._y = y
self._r, self._theta = f(self._x, self._y)
self._theta_radians = math.radians(self._theta)
def c_rect(self, r, theta, f = rect):
"""theta in degrees
"""
self._r = r
self._theta = theta
self._theta_radians = math.radians(theta)
self._x, self._y = f(self._r, self._theta)
def setx(self, x):
self.c_polar(x, self._y)
def getx(self):
return self._x
x = property(fget = getx, fset = setx)
def sety(self, y):
self.c_polar(self._x, y)
def gety(self):
return self._y
y = property(fget = gety, fset = sety)
def setxy(self, x, y):
self.c_polar(x, y)
def getxy(self):
return self._x, self._y
xy = property(fget = getxy, fset = setxy)
def setr(self, r):
self.c_rect(r, self._theta)
def getr(self):
return self._r
r = property(fget = getr, fset = setr)
def settheta(self, theta):
"""theta in degrees
"""
self.c_rect(self._r, theta)
def gettheta(self):
return self._theta
theta = property(fget = gettheta, fset = settheta)
def set_r_theta(self, r, theta):
"""theta in degrees
"""
self.c_rect(r, theta)
def get_r_theta(self):
return self._r, self._theta
r_theta = property(fget = get_r_theta, fset = set_r_theta)
def __str__(self):
return '({},{})'.format(self._x, self._y)
The code below removes remove grid lines from chart area only not the ones in x&y axis labels
Chart.defaults.scale.gridLines.drawOnChartArea = false;
From where did you get the idea that you need to free(token)
and free(tk)
? You don't. strsep()
doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc()
(or similar), so free()
ing them is undefined behavior. You only need to free(s)
when you are done with the entire string.
Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup()
and free()
altogether by simply writing char *s = p;
.
(1) Is it possible to pass a JSON object to the url like in Ex.2?
No, because http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}
is not a valid URL.
If you want to do it the RESTful way, use http://localhost:8080/api/v1/mno/objectKey/1/Saif
, and defined your method like this:
@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
// code here
}
(2) How can we pass and parse the parameters in Ex.1?
Just add two request parameters, and give the correct path.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
// code here
}
UPDATE (from comment)
What if we have a complicated parameter structure ?
"A": [ { "B": 37181, "timestamp": 1160100436, "categories": [ { "categoryID": 2653, "timestamp": 1158555774 }, { "categoryID": 4453, "timestamp": 1158555774 } ] } ]
Send that as a POST
with the JSON data in the request body, not in the URL, and specify a content type of application/json
.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
// code here
}
If the component name is explained in the file name MyComponent.js
, just don't name the component, keeps code slim.
import React from 'react'
export default (props) =>
<div id='static-page-template'>
{props.children}
</div>
Update: Since this labels it as unknown in stack tracing, it isn't recommended
To get the values use pattern.exec() instead of pattern.test() (the .test() returns a boolean value).
My table has 100 fields, and I needed a query to just work. Now I can switch out any number of fields with some basic conditional logic and not worry about its ordinal position.
Replace the below table name with your table name
SQLcolums = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'TABLE-NAME')"
Set GetColumns = Conn.Execute(SQLcolums)
Do WHILE not GetColumns.eof
colName = GetColumns("COLUMN_NAME")
Replace the original identity field name with your PK field name
IF colName = "ORIGINAL-IDENTITY-FIELD-NAME" THEN ' ASSUMING THAT YOUR PRIMARY KEY IS THE FIRST FIELD DONT WORRY ABOUT COMMAS AND SPACES
columnListSOURCE = colName
columnListTARGET = "[PreviousId field name]"
ELSE
columnListSOURCE = columnListSOURCE & colName
columnListTARGET = columnListTARGET & colName
END IF
GetColumns.movenext
loop
GetColumns.close
Replace the table names again (both target table name and source table name); edit your where
conditions
SQL = "INSERT INTO TARGET-TABLE-NAME (" & columnListTARGET & ") SELECT " & columnListSOURCE & " FROM SOURCE-TABLE-NAME WHERE (FIELDNAME = FIELDVALUE)"
Conn.Execute(SQL)
One approach would be to iterate over the array, calling the description
message on each item:
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
[result appendString:[obj description]];
}
NSLog(@"The concatenated string is %@", result);
Another approach would be to do something based on each item's class:
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
if ([obj isKindOfClass:[NSNumber class]])
{
// append something
}
else
{
[result appendString:[obj description]];
}
}
NSLog(@"The concatenated string is %@", result);
If you want commas and other extraneous information, you can just do:
NSString * result = [array description];
It's not defined in the ECMA JSON standard. And generally speaking, a lack of definition in a standard means, "Don't count on this working the same way everywhere."
If you're a gambler, "many" JSON engines will allow duplication and simply use the last-specified value. This:
var o = {"a": 1, "b": 2, "a": 3}
Becomes this:
Object {a: 3, b: 2}
But if you're not a gambler, don't count on it!
Open the project you want to push in Android Studio.
Click VCS -> Enable version Control Integration -> Git
There doesn't seem to be a way to add a remote through the GUI. So open Git Bash in the root of the project and do git remote add <remote_name> <remote_url>
Now when you do VCS -> Commit changes -> Commit & Push
you should see your remote and everything should work through the GUI.
If you are getting the error: fatal: remote <remote_name> already exists
that means you already added it. To see your remotes do git remote -v
and git remote rm <remote_name>
to remove.
See these pages for details:
http://www.jetbrains.com/idea/webhelp/using-git-integration.html
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
I need to somehow query Google and ask: Is this access token valid for [email protected]?
No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.
The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.
So you need be from same domain as 'public interface'.
And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.
I realize this is old, but maybe this function I created is useful to someone out there:
order_axis<-function(data, axis, column)
{
# for interactivity with ggplot2
arguments <- as.list(match.call())
col <- eval(arguments$column, data)
ax <- eval(arguments$axis, data)
# evaluated factors
a<-reorder(with(data, ax),
with(data, col))
#new_data
df<-cbind.data.frame(data)
# define new var
within(df,
do.call("<-",list(paste0(as.character(arguments$axis),"_o"), a)))
}
Now, with this function you can interactively plot with ggplot2, like this:
ggplot(order_axis(df, AXIS_X, COLUMN_Y),
aes(x = AXIS_X_o, y = COLUMN_Y)) +
geom_bar(stat = "identity")
As can be seen, the order_axis
function creates another dataframe with a new column named the same but with a _o
at the end. This new column has levels in ascending order, so ggplot2 automatically plots in that order.
This is somewhat limited (only works for character or factor and numeric combinations of columns and in ascending order) but I still find it very useful for plotting on the go.
There are several ways to achieve this.
Probably the easiest would be to use JavaScript to change the form's action.
<input type="submit" value="SecondServlet" onclick="form.action='SecondServlet';">
But this of course won't work when the enduser has JS disabled (mobile browsers, screenreaders, etc).
Another way is to put the second button in a different form, which may or may not be what you need, depending on the concrete functional requirement, which is not clear from the question at all.
<form action="FirstServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" value="FirstServlet">
</form>
<form action="SecondServlet" method="Post">
<input type="submit"value="SecondServlet">
</form>
Note that a form would on submit only send the input data contained in the very same form, not in the other form.
Again another way is to just create another single entry point servlet which delegates further to the right servlets (or preferably, the right business actions) depending on the button pressed (which is by itself available as a request parameter by its name
):
<form action="MainServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" name="action" value="FirstServlet">
<input type="submit" name="action" value="SecondServlet">
</form>
with the following in MainServlet
String action = request.getParameter("action");
if ("FirstServlet".equals(action)) {
// Invoke FirstServlet's job here.
} else if ("SecondServlet".equals(action)) {
// Invoke SecondServlet's job here.
}
This is only not very i18n/maintenance friendly. What if you need to show buttons in a different language or change the button values while forgetting to take the servlet code into account?
A slight change is to give the buttons its own fixed and unique name, so that its presence as request parameter could be checked instead of its value which would be sensitive to i18n/maintenance:
<form action="MainServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" name="first" value="FirstServlet">
<input type="submit" name="second" value="SecondServlet">
</form>
with the following in MainServlet
if (request.getParameter("first") != null) {
// Invoke FirstServlet's job here.
} else if (request.getParameter("second") != null) {
// Invoke SecondServlet's job here.
}
Last way would be to just use a MVC framework like JSF so that you can directly bind javabean methods to buttons, but that would require drastic changes to your existing code.
<h:form>
Last Name: <h:inputText value="#{bean.lastName}" size="20" />
<br/><br/>
<h:commandButton value="First" action="#{bean.first}" />
<h:commandButton value="Second" action="#{bean.Second}" />
</h:form>
with just the following javabean instead of a servlet
@ManagedBean
@RequestScoped
public class Bean {
private String lastName; // +getter+setter
public void first() {
// Invoke original FirstServlet's job here.
}
public void second() {
// Invoke original SecondServlet's job here.
}
}
according to http://msdn.microsoft.com/en-us/library/aa337556.aspx
This task is not supported using Transact-SQL statements.
Well, it can be done, using create
/ copy / drop
/ rename, as answered by komma8.komma1
Or you can use SQL Server Management Studio
- In Object Explorer, right-click the table with columns you want to reorder and click Design (Modify in ver. 2005 SP1 or earlier)
- Select the box to the left of the column name that you want to reorder. (You can select multiple columns by holding the [shift] or the [ctrl] keys on your keyboard.)
- Drag the column(s) to another location within the table.
Then click save. This method actually drops and recreates the table, so some errors might occur.
If Change Tracking option is enabled for the database and the table, you shouldn't use this method.
If it is disabled, the Prevent saving changes that require the table re-creation option should be cleared in Tools menu > Options > Designers, otherwise "Saving changes is not permitted" error will occur.
Problems may also arise during primary and foreign key creation.
If any of the above errors occurs, saving fails which leaves you with the original column order.
Customizing FROM address
MESSAGE="SOME MESSAGE"
SUBJECT="SOME SUBJECT"
TOADDR="[email protected]"
FROM="DONOTREPLY"
echo $MESSAGE | mail -s "$SUBJECT" $TOADDR -- -f $FROM
Mount remount the /
Eg.
mount -o remount,rw /dev/xyz /
sed -i 's/1 1/0 0/' /etc/fstab
sed -i 's/1 2/0 0/' /etc/fstab
It's 2020 and stuffs had greatly evolved with php 7.4 and opcache.
Here is the OP^ benchmark, ran as unix CLI, without the echo and html parts.
Test ran locally on a regular computer.
php -v
PHP 7.4.6 (cli) (built: May 14 2020 10:02:44) ( NTS )
Modified benchmark script:
<?php
## preperations; just a simple environment state
$test_iterations = 100;
$test_arr_size = 1000;
// a shared function that makes use of the loop; this should
// ensure no funny business is happening to fool the test
function test($input)
{
//echo '<!-- '.trim($input).' -->';
}
// for each test we create a array this should avoid any of the
// arrays internal representation or optimizations from getting
// in the way.
// normal array
$test_arr1 = array();
$test_arr2 = array();
$test_arr3 = array();
// hash tables
$test_arr4 = array();
$test_arr5 = array();
for ($i = 0; $i < $test_arr_size; ++$i)
{
mt_srand();
$hash = md5(mt_rand());
$key = substr($hash, 0, 5).$i;
$test_arr1[$i] = $test_arr2[$i] = $test_arr3[$i] = $test_arr4[$key] = $test_arr5[$key]
= $hash;
}
## foreach
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr1 as $k => $v)
{
test($v);
}
}
echo 'foreach '.(microtime(true) - $start)."\n";
## foreach (using reference)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr2 as &$value)
{
test($value);
}
}
echo 'foreach (using reference) '.(microtime(true) - $start)."\n";
## for
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
$size = count($test_arr3);
for ($i = 0; $i < $size; ++$i)
{
test($test_arr3[$i]);
}
}
echo 'for '.(microtime(true) - $start)."\n";
## foreach (hash table)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr4 as $k => $v)
{
test($v);
}
}
echo 'foreach (hash table) '.(microtime(true) - $start)."\n";
## for (hash table)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
$keys = array_keys($test_arr5);
$size = sizeOf($test_arr5);
for ($i = 0; $i < $size; ++$i)
{
test($test_arr5[$keys[$i]]);
}
}
echo 'for (hash table) '.(microtime(true) - $start)."\n";
Output:
foreach 0.0032877922058105
foreach (using reference) 0.0029420852661133
for 0.0025191307067871
foreach (hash table) 0.0035080909729004
for (hash table) 0.0061779022216797
As you can see the evolution is insane, about 560 time faster than reported in 2012.
On my machines and servers, following my numerous experiments, basics for loops are the fastest. This is even clearer using nested loops ($i $j $k..)
It is also the most flexible in usage, and has a better readability from my view.
I had exactly same problem, my solution was to
scp -i /path/pem -r /path/file/ ec2-user@public aws dns name:
(leave it blank here)
once you done this part, get into ssh server and mv file to desired location
FirebaseInstanceId
class and it's method getInstanceId
are also deprecated. So you have to use FirebaseMessaging
class and it's getToken
method instead.
FirebaseMessaging.getInstance().getToken().addOnSuccessListener(token -> {
if (!TextUtils.isEmpty(token)) {
Log.d(TAG, "retrieve token successful : " + token);
} else{
Log.w(TAG, "token should not be null...");
}
}).addOnFailureListener(e -> {
//handle e
}).addOnCanceledListener(() -> {
//handle cancel
}).addOnCompleteListener(task -> Log.v(TAG, "This is the token : " + task.getResult()));
The method getToken()
is deprecated. You can use getInstanceId()
instead.
If you want to handle results when requesting instanceId(token)
, check this code.
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(instanceIdResult -> {
if (instanceIdResult != null) {
String token = instanceIdResult.getToken();
if (!TextUtils.isEmpty(token)) {
Log.d(TAG, "retrieve token successful : " + token);
}
} else{
Log.w(TAG, "instanceIdResult should not be null..");
}
}).addOnFailureListener(e -> {
//do something with e
}).addOnCanceledListener(() -> {
//request has canceled
}).addOnCompleteListener(task -> Log.v(TAG, "task result : " + task.getResult().getToken()));
You can simply check out a new branch, and then commit:
git checkout -b my_new_branch
git commit
Checking out the new branch will not discard your changes.
String[] result = "hi i'm paul".split("\\s+");
to split across one or more cases.
Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str)
method that splits string using white space as delimiter. It also has other useful utility methods
><
by >\n<
with Regular Expressions enabledThe reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.
There is a great book called Chaos and Fractals that has simple example code at the end of each chapter that implements some fractal or other example. A long time ago when I read that book, I converted each sample program (in some Basic dialect) into a Java applet that runs on a web page. The applets are here: http://hewgill.com/chaos-and-fractals/
One of the samples is a simple Mandelbrot implementation.
I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.
From http://api.jquery.com/live/
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.
So instead of...
$(".myclass").click( function() {
// do something
});
You can write...
$('body').on('click', 'a.myclass', function() {
// do something
});
This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.
The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:
$('ul').on('click', 'li', function() {
alert( $(this).text() );
});
As long as the ul tag exists this will work (no li elements need exist yet).
you can use a formatstring
DateTime time = DateTime.Now;
String format = "MMM ddd d HH:mm yyyy";
Console.WriteLine(time.ToString(format));
Since C++11, there's a safe alternative to new[]
and delete[]
which is zero-overhead unlike std::vector
:
std::unique_ptr<int[]> array(new int[size]);
In C++14:
auto array = std::make_unique<int[]>(size);
Both of the above rely on the same header file, #include <memory>
I just had a similar error using the openssl.exe from the Apache for windows bin folder. I had the -config flag specified by had a typo in the path of the openssl.cnf file. I think you'll find that
openssl req -config C:\OpenSSL\bin\openssl.conf -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem
should be
openssl req -config "C:\OpenSSL\bin\openssl.cnf" -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem
Note: the conf should probably be cnf.
So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.
Setting a timer
First you need to create a Timer (I'm using the java.util
version here):
import java.util.Timer;
..
Timer timer = new Timer();
To run the task once you would do:
timer.schedule(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);
To have the task repeat after the duration you would do:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000, 2*60*1000);
// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);
Making a task timeout
To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
@Override
public void run() {
// Database task
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.
One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.
(This is for posts, not pages - the principle is same. The permalink hook is different by exact use case)
I just had the same issue and created a more convenient way to do that - where you don't have to re-edit your functions.php
all the time, or fiddle around with your server settings on each addition (I do not like both).
TLTR
You can add a filter on the actual WP permalink function you need (for me it was post_link
, because I needed that page alias in an archive/category list), and dynamically read the referenced ID from the alias post itself.
This is ok, because the post is an alias, so you won't need the content anyways.
First step is to open the alias post and put the ID of the referenced post as content (and nothing else):
Next, open your functions.php
and add:
function prefix_filter_post_permalink($url, $post) {
// if the content of the post to get the permalink for is just a number...
if (is_numeric($post->post_content)) {
// instead, return the permalink for the post that has this ID
return get_the_permalink((int)$post->post_content);
}
return $url;
}
add_filter('post_link', 'prefix_filter_post_permalink', 10, 2 );
That's it
Now, each time you need to create an alias post, just put the ID of the referenced post as the content, and you're done.
This will just change the permalink. Title, excerpt and so on will be shown as-is, which is usually desired. More tweaking to your needs is on you, also, the "is it a number" part in the PHP
code is far from ideal, but like this for making the point readable.
Cast the Boolean to an integer and sum.
SELECT count(*),sum(myCol::int);
You get 6,3
.
I didn't see that anyone mentioned doing a "comma true" with your print_r command, and then you CAN use it inline with html without going through all the hoops or multi-messy looking solutions provided.
print "session: <br><pre>".print_r($_SESSION, true)."</pre><BR>";
To get it to work with FullScreen:
Use the ionic keyboard plugin. This allows you to listen for when the keyboard appears and disappears.
OnDeviceReady add these event listeners:
// Allow Screen to Move Up when Keyboard is Present
window.addEventListener('native.keyboardshow', onKeyboardShow);
// Reset Screen after Keyboard hides
window.addEventListener('native.keyboardhide', onKeyboardHide);
The Logic:
function onKeyboardShow(e) {
// Get Focused Element
var thisElement = $(':focus');
// Get input size
var i = thisElement.height();
// Get Window Height
var h = $(window).height()
// Get Keyboard Height
var kH = e.keyboardHeight
// Get Focused Element Top Offset
var eH = thisElement.offset().top;
// Top of Input should still be visible (30 = Fixed Header)
var vS = h - kH;
i = i > vS ? (vS - 30) : i;
// Get Difference
var diff = (vS - eH - i);
if (diff < 0) {
var parent = $('.myOuter-xs.myOuter-md');
// Add Padding
var marginTop = parseInt(parent.css('marginTop')) + diff - 25;
parent.css('marginTop', marginTop + 'px');
}
}
function onKeyboardHide(e) {
// Remove All Style Attributes from Parent Div
$('.myOuter-xs.myOuter-md').removeAttr('style');
}
Basically if they difference is minus then that is the amount of pixels that the keyboard is covering of your input. So if you adjust your parent div by this that should counteract it.
Adding timeouts to the logic say 300ms should also optimise performance (as this will allow keyboard time to appear.
We can force vbscript always run with 32 bit mode by changing "system32" to "sysWOW64" in default value of key "Computer\HKLM\SOFTWARE]\Classes\VBSFile\Shell\Open\Command"
Follow the steps as below: (Linux)
Edit the file ~/.bashrc
, to enter following lines at its end (In case, of Mac, file would be ~/.bash_profile
)
# Git branch in prompt.
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
Now, start the new terminal window, and try entering to any git-repo. The current branch would be shown, with the prompt.
I like to place all my sql connections in using
statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.
// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
try
{
conn.Open();
// initialize command
using (SqlCommand cmd = conn.CreateCommand())
{
// generate query with parameters
with cmd
{
.CommandType = CommandType.Text;
.CommandText = "insert into time(project,iteration) values(@name, @iteration)";
.Parameters.Add(new SqlParameter("@name", this.name1.SelectedValue));
.Parameters.Add(new SqlParameter("@iteration", this.iteration.SelectedValue));
.ExecuteNonQuery();
}
}
}
catch (Exception)
{
//throw;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
{
conn.Close;
}
}
}
Yes DOK has the right answer ... either pre-sort the results before you write the HTML (assuming it's dynamic and you are responsible for the output), or you write javascript.
The Javascript Sort method will be your friend here. Simply pull the values out of the select list, then sort it, and put them back :-)
The solution to change the encoding to Latin1 / ISO-8859-1 solves an issue I observed with html2text.py as invoked on an output of tex4ht. I use that for an automated word count on LaTeX documents: tex4ht converts them to HTML, and then html2text.py strips them down to pure text for further counting through wc -w. Now, if, for example, a German "Umlaut" comes in through a literature database entry, that process would fail as html2text.py would complain e.g.
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 32243-32245: invalid data
Now these errors would then subsequently be particularly hard to track down, and essentially you want to have the Umlaut in your references section. A simple change inside html2text.py from
data = data.decode(encoding)
to
data = data.decode("ISO-8859-1")
solves that issue; if you're calling the script using the HTML file as first parameter, you can also pass the encoding as second parameter and spare the modification.
In wind32, console-mode applications are a completely different beast from the usual message-queue-receiving applications. They are declared and compile differently. You might create an application which has both a console part and normal window and hide one or the other. But suspect you will find the whole thing a bit more work than you thought.
I'm using the following, though it's hardcoded for gnome-terminal
. It also changes the CWD and buffer for vim to be the same as your current buffer and it's directory.
:silent execute '!gnome-terminal -- zsh -i -c "cd ' shellescape(expand("%:h")) '; vim' shellescape(expand("%:p")) '; zsh -i"' <cr>
This Android library handles the case changes in KitKat(including the oldere versions - 2.1+):
https://github.com/iPaulPro/aFileChooser
Use the String path = FileUtils.getPath(context, uri)
to convert the returned Uri to a path string useable on all OS version.
See more about it here: https://stackoverflow.com/a/20559175/860488
This means your MySQL table is corrupted and you need to repair it. Use
myisamchk -r /DB_NAME/wp_posts
from the command line. While you running the repair you should shut down your website temporarily so that no new connections are attempted to your database while its being repaired.
As another answer mentioned, you can now do this in C11 with _Generic
.
For example, here's a macro that will check if some input is compatible with another type:
#include <stdbool.h>
#define isCompatible(x, type) _Generic(x, type: true, default: false)
You can use the macro like so:
double doubleVar;
if (isCompatible(doubleVar, double)) {
printf("doubleVar is of type double!\n"); // prints
}
int intVar;
if (isCompatible(intVar, double)) {
printf("intVar is compatible with double too!\n"); // doesn't print
}
This can also be used on other types, including structs. E.g.
struct A {
int x;
int y;
};
struct B {
double a;
double b;
};
int main(void)
{
struct A AVar = {4, 2};
struct B BVar = {4.2, 5.6};
if (isCompatible(AVar, struct A)) {
printf("Works on user-defined types!\n"); // prints
}
if (isCompatible(BVar, struct A)) {
printf("And can differentiate between them too!\n"); // doesn't print
}
return 0;
}
And on typedefs.
typedef char* string;
string greeting = "Hello world!";
if (isCompatible(greeting, string)) {
printf("Can check typedefs.\n");
}
However, it doesn't always give you the answer you expect. For instance, it can't distinguish between an array and a pointer.
int intArray[] = {4, -9, 42, 3};
if (isCompatible(intArray, int*)) {
printf("Treats arrays like pointers.\n");
}
// The code below doesn't print, even though you'd think it would
if (isCompatible(intArray, int[4])) {
printf("But at least this works.\n");
}
Answer borrowed from here: http://www.robertgamble.net/2012/01/c11-generic-selections.html
From my understanding, all the SQL statement don't need forward slash as they will run automatically at the end of semicolons, including DDL, DML, DCL and TCL statements.
For other PL/SQL blocks, including Procedures, Functions, Packages and Triggers, because they are multiple line programs, Oracle need a way to know when to run the block, so we have to write a forward slash at the end of each block to let Oracle run it.
The simplest solution would be to keep track of the item size and the number of items, and then create a buffer of the appropriate number of bytes:
typedef struct circular_buffer
{
void *buffer; // data buffer
void *buffer_end; // end of data buffer
size_t capacity; // maximum number of items in the buffer
size_t count; // number of items in the buffer
size_t sz; // size of each item in the buffer
void *head; // pointer to head
void *tail; // pointer to tail
} circular_buffer;
void cb_init(circular_buffer *cb, size_t capacity, size_t sz)
{
cb->buffer = malloc(capacity * sz);
if(cb->buffer == NULL)
// handle error
cb->buffer_end = (char *)cb->buffer + capacity * sz;
cb->capacity = capacity;
cb->count = 0;
cb->sz = sz;
cb->head = cb->buffer;
cb->tail = cb->buffer;
}
void cb_free(circular_buffer *cb)
{
free(cb->buffer);
// clear out other fields too, just to be safe
}
void cb_push_back(circular_buffer *cb, const void *item)
{
if(cb->count == cb->capacity){
// handle error
}
memcpy(cb->head, item, cb->sz);
cb->head = (char*)cb->head + cb->sz;
if(cb->head == cb->buffer_end)
cb->head = cb->buffer;
cb->count++;
}
void cb_pop_front(circular_buffer *cb, void *item)
{
if(cb->count == 0){
// handle error
}
memcpy(item, cb->tail, cb->sz);
cb->tail = (char*)cb->tail + cb->sz;
if(cb->tail == cb->buffer_end)
cb->tail = cb->buffer;
cb->count--;
}
With me, in the project directory run the following commands.
For react native old version (you will see index.android.js in root):
mkdir -p android/app/src/main/assets && rm -rf android/app/build && react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && cd android && ./gradlew clean assembleRelease && cd ../
For react native new version (you just see index.js in root):
mkdir -p android/app/src/main/assets && rm -rf android/app/build && react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && cd android && ./gradlew clean assembleRelease && cd ../
The apk file will be generated at:
Functions in Python are first-class objects. But your function definition is a bit off.
def myfunc(anotherfunc, extraArgs, extraKwArgs):
return anotherfunc(*extraArgs, **extraKwArgs)
This error happens if you did not set the password on install, in this case the mysql using unix-socket plugin.
But if delete the plugin link from settings (table mysql.user) will other problem. This does not fix the problem and creates another problem. To fix the deleted link and set password ("PWD") do:
1) Run with --skip-grant-tables
as said above.
If it doesnt works then add the string skip-grant-tables
in section [mysqld]
of /etc/mysql/mysql.conf.d/mysqld.cnf
. Then do
sudo service mysql restart
.
2) Run mysql -u root -p
, then (change "PWD"):
update mysql.user
set authentication_string=PASSWORD("PWD"), plugin="mysql_native_password"
where User='root' and Host='localhost';
flush privileges;
quit
then sudo service mysql restart
. Check: mysql -u root -p
.
Before restart
remove that string from file mysqld.cnf, if you set it there.
Shorter way is do it as follows:
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
Just comment out the whole "User for advanced features" and "Advanced phpMyAdmin features" code blocks in config.inc.php
.
For me its simple solution (Mac User)
run in terminal --> alias j8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8`;java -version"
then run --> j8
thats it !!(now run your mvn commands)
_x000D_
Or you can set above in your .bash_profile
I contribute with my settings for buttons: view, edit and delete. The last column has data: null At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.
//...
columns: [
{ title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
{ title: "Id", "data": "id", defaultContent: '', "visible":false },
{ title: "Nombre", "data": "nombre" },
{ title: "Apellido", "data": "apellido" },
{ title: "Documento", "data": "tipo_documento.siglas" },
{ title: "Numero", "data": "numero_documento" },
{ title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
{ title: "TelƩfono", "data": "telefono1" },
{ title: "Email", "data": "email1" }
, { title: "", "data": null }
],
columnDefs: [
{
"searchable": false,
"orderable": false,
"targets": 0
},
{
width: '3%',
targets: 0 //la primer columna tendra una anchura del 20% de la tabla
},
{
targets: -1, //-1 es la ultima columna y 0 la primera
data: null,
defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button> <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
},
{ orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
],
//...
Download the following jars and add it to your WEB-INF/lib
directory:
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function($scope) {_x000D_
_x000D_
$scope.minus = function() { _x000D_
_x000D_
var a = Number($scope.a || 0);_x000D_
var b = Number($scope.b || 0);_x000D_
$scope.sum1 = a-b;_x000D_
// $scope.sum = $scope.sum1+1; _x000D_
alert($scope.sum1);_x000D_
}_x000D_
_x000D_
$scope.add = function() { _x000D_
_x000D_
var c = Number($scope.c || 0);_x000D_
var d = Number($scope.d || 0);_x000D_
$scope.sum2 = c+d;_x000D_
alert($scope.sum2);_x000D_
}_x000D_
});
_x000D_
<head>_x000D_
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
<h3>Using Double Negation</h3>_x000D_
_x000D_
<p>First Number:_x000D_
<input type="text" ng-model="a" />_x000D_
</p>_x000D_
<p>Second Number:_x000D_
<input type="text" ng-model="b" />_x000D_
</p>_x000D_
<button id="minus" ng-click="minus()">Minus</button>_x000D_
<!-- <p>Sum: {{ a - b }}</p> -->_x000D_
<p>Sum: {{ sum1 }}</p>_x000D_
_x000D_
<p>First Number:_x000D_
<input type="number" ng-model="c" />_x000D_
</p>_x000D_
<p>Second Number:_x000D_
<input type="number" ng-model="d" />_x000D_
</p>_x000D_
<button id="minus" ng-click="add()">Add</button>_x000D_
<p>Sum: {{ sum2 }}</p>_x000D_
</div>
_x000D_
In my case sleep
created side effect so I used wait
let _ = XCTWaiter.wait(for: [XCTestExpectation(description: "Hello World!")], timeout: 2.0)
There are a lot of answers here but none that use git-fetch
to update the local ref directly, which is a lot simpler than checking out branches, and safer than git-update-ref
.
Here we use git-fetch
to update non-current branches and git pull --ff-only
for the current branch. It:
and here it is:
#!/bin/bash
currentbranchref="$(git symbolic-ref HEAD 2>&-)"
git branch -r | grep -v ' -> ' | while read remotebranch
do
# Split <remote>/<branch> into remote and branchref parts
remote="${remotebranch%%/*}"
branchref="refs/heads/${remotebranch#*/}"
if [ "$branchref" == "$currentbranchref" ]
then
echo "Updating current branch $branchref from $remote..."
git pull --ff-only
else
echo "Updating non-current ref $branchref from $remote..."
git fetch "$remote" "$branchref:$branchref"
fi
done
From the manpage for git-fetch
:
<refspec>
The format of a <refspec> parameter is an optional plus +, followed by the source ref <src>,
followed by a colon :, followed by the destination ref <dst>.
The remote ref that matches <src> is fetched, and if <dst> is not empty string, the local ref
that matches it is fast-forwarded using <src>. If the optional plus + is used, the local ref is
updated even if it does not result in a fast-forward update.
By specifying git fetch <remote> <ref>:<ref>
(without any +
) we get a fetch that updates the local ref only when it can be fast-forwarded.
Note: this assumes the local and remote branches are named the same (and that you want to track all branches), it should really use information about which local branches you have and what they are set up to track.
The major browser vendors differ on what "offline" means.
Chrome, Safari, and Firefox (since version 41) will detect when you go "offline" automatically - meaning that "online" events and properties will fire automatically when you unplug your network cable.
Mozilla Firefox (before version 41), Opera, and IE take a different approach, and consider you "online" unless you explicitly pick "Offline Mode" in the browser - even if you don't have a working network connection.
There are valid arguments for the Firefox/Mozilla behavior, which are outlined in the comments of this bug report:
https://bugzilla.mozilla.org/show_bug.cgi?id=654579
But, to answer the question - you can't rely on the online/offline events/property to detect if there is actually network connectivity.
Instead, you must use alternate approaches.
The "Notes" section of this Mozilla Developer article provides links to two alternate methods:
https://developer.mozilla.org/en/Online_and_offline_events
"If the API isn't implemented in the browser, you can use other signals to detect if you are offline including listening for AppCache error events and responses from XMLHttpRequest"
This links to an example of the "listening for AppCache error events" approach:
http://www.html5rocks.com/en/mobile/workingoffthegrid/#toc-appcache
...and an example of the "listening for XMLHttpRequest failures" approach:
http://www.html5rocks.com/en/mobile/workingoffthegrid/#toc-xml-http-request
HTH, -- Chad
I'd like to add to the right and successful answers, that if you initialize a view with visibility as View.GONE
, the view could have been not initialized and you will get some random errors.
For example if you initialize a layout as View.GONE
and then you try to start an animation, from my experience I've got my animation working randomly times. Sometimes yes, sometimes no.
So before handling (resizing, move, whatever) a view, you have to init it as View.VISIBLE
or View.INVISIBLE
to render it (draw it) in the screen, and then handle it.
there is no need to use for cycle
you can benefit from bash parameter expansion functions:
var="a b c";
var=${var// /\\n};
echo -e $var
a
b
c
or just use tr:
var="a b c"
echo $var | tr " " "\n"
a
b
c
In Java you can do this to concatenate multiple columns. The sample code is to provide you a scenario and how to use it for better understanding.
SparkSession spark = JavaSparkSessionSingleton.getInstance(rdd.context().getConf());
Dataset<Row> reducedInventory = spark.sql("select * from table_name")
.withColumn("concatenatedCol",
concat(col("col1"), lit("_"), col("col2"), lit("_"), col("col3")));
class JavaSparkSessionSingleton {
private static transient SparkSession instance = null;
public static SparkSession getInstance(SparkConf sparkConf) {
if (instance == null) {
instance = SparkSession.builder().config(sparkConf)
.getOrCreate();
}
return instance;
}
}
The above code concatenated col1,col2,col3 seperated by "_" to create a column with name "concatenatedCol".
Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.
Also based on your markup your selector is wrong. it should be #advisersDiv
function fadeIn() {
$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
setTimeout(fadeOut,1); //<-- Provide any delay here
};
function fadeOut() {
$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();
In windows, you need to use double quotes "". So the command would be
git commit -m "t"
Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.
If it is a windows system, then it may be because you are using 32 bit winpcap library in a 64 bit pc or vie versa. If it is a 64 bit pc then copy the winpcap library and header packet.lib and wpcap.lib from winpcap/lib/x64 to the winpcap/lib directory and overwrite the existing
foreach (var v in structure)
{
var group = groups.Single(g => g.Key == v. ??? );
v.ListOfSmth = group.ToList();
}
First you need to select the desired group. Then you can use the ToList
method of on the group. The IGrouping
is a IEnumerable
of the values.
myList.Where(item=>item.Name == nameToExtract)
Check out this one:
https://github.com/VBA-tools/VBA-Web
It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.
If you use findAll()
, I recommend you to use this:
$data_email = EmailArchive::model()->findAll(
array(
'condition' => 'email_id = :email_id',
'params' => array(':email_id' => $id)
)
);
Below is an example of multiple figures that I used recently in Latex. You need to call these packages
\usepackage{graphicx}
\usepackage{subfig})
\begin{figure}[H]%
\centering
\subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%
\subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%
\subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
\hfill
\subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%
\subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%
\caption{Multiple figures in latex.}%
\label{fig:MFL}%
\end{figure}
Another sneaky issue related to this is naming your columns with -
instead of _
.
Something like this will trigger an error at the moment your tables are getting created.
@Column(name="verification-token")
F5 triggers a standard reload.
Ctrl + F5 triggers a forced reload. This causes the browser to re-download the page from the web server, ensuring that it always has the latest copy.
Unlike with F5, a forced reload does not display a cached copy of the page.
To check if PowerShell is installed use:
HKLM\Software\Microsoft\PowerShell\1 Install ( = 1 )
To check if RC2 or RTM is installed use:
HKLM\Software\Microsoft\PowerShell\1 PID (=89393-100-0001260-00301) -- For RC2
HKLM\Software\Microsoft\PowerShell\1 PID (=89393-100-0001260-04309) -- For RTM
Source: this website.
for XML line width, update preferences > XML > XML Files > Editor > Line width
If SQLCMD is an option, it supports scripting variables above and beyond what straight T-SQL can do. For example: http://msdn.microsoft.com/en-us/library/ms188714.aspx
The s
command can use any character as a delimiter; whatever character comes after the s
is used. I was brought up to use a #
. Like so:
s#?page=one&#/page/one#g
Like this:
import operator
l = [...]
sorted_list = sorted(l, key=operator.itemgetter(desired_item_index))
assuming the item numbers are unique, a VLOOKUP
should get you the information you need.
first value would be =VLOOKUP(E1,A:B,2,FALSE)
, and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE)
. Wrap them in an IFERROR
if you want to return anything other than #N/A if there is no corresponding value in the item column(s)
If you're using JSX with Harmony, you could do this:
<img className="image" src={`images/${this.props.image}`} />
Here you are writing the value of src
as an expression.
stockPicker = [[UIPickerView alloc] init];
stockPicker.frame = CGRectMake(70.0,155, 180,100);
If You want to set the size of UiPickerView. Above code is surely gonna work for u.
v
has 10
element, the index starts from 0
to 9
.
for(int j=10;j>0;--j)
{
cout<<v[j]; // v[10] out of range
}
you should update for
loop to
for(int j=9; j>=0; --j)
// ^^^^^^^^^^
{
cout<<v[j]; // out of range
}
Or use reverse iterator to print element in reverse order
for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
std::cout << *ri << std::endl;
}
The constructor of your A object allocates another object dynamically and stores a pointer to that dynamically allocated object in a raw pointer.
For that scenario, you must define your own copy constructor , assignment operator and destructor. The compiler generated ones will not work correctly. (This is a corollary to the "Law of the Big Three": A class with any of destructor, assignment operator, copy constructor generally needs all 3).
You have defined your own destructor (and you mentioned creating a copy constructor), but you need to define both of the other 2 of the big three.
An alternative is to store the pointer to your dynamically allocated int[]
in some other object that will take care of these things for you. Something like a vector<int>
(as you mentioned) or a boost::shared_array<>
.
To boil this down - to take advantage of RAII to the full extent, you should avoid dealing with raw pointers to the extent possible.
And since you asked for other style critiques, a minor one is that when you are deleting raw pointers you do not need to check for 0 before calling delete
- delete
handles that case by doing nothing so you don't have to clutter you code with the checks.
Until the session timeout we get a normal request, after which we get an Ajax request. We can identify it the following way:
String ajaxRequestHeader = request.getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(ajaxRequestHeader)) {
response.sendRedirect("/login.jsp");
}
I had the same error on Debian and all I had to do was:
sudo su
and then run the command again and it worked.
You could also send your testers the apk that is signed with your debug key. You can find that in the bin folder of your project after building in debug mode.
Following Joe Shaw's answer about multi-threaded code not to work as expected, I figured that the runcall
method in cProfile is merely doing self.enable()
and self.disable()
calls around the profiled function call, so you can simply do that yourself and have whatever code you want in-between with minimal interference with existing code.
$("div[id^=" + controlid + "]")
will return all the controls with the same name but you need to ensure that the text should not present in any of the controls
A really dumb answer (I'll vote myself down in a minute), but this worked for me:
After adding your pipe, if you're still getting the errors and are running your Angular site using "ng serve
", stop it... then start it up again.
For me, none of the other suggestions worked, but simply stopping, then restarting "ng serve
" was enough to make the error go away.
Strange.
Can you change the if condition to this:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
If you want to just check if they are identical or not, a == b
should give you true / false with ordering taken into account.
In case you want to compare elements, you can use numpy for comparison
c = (numpy.array(a) == numpy.array(b))
Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.
kotlin.UninitializedPropertyAccessException: lateinit property clientKeypair has not been initialized
Bytecode says...blah blah..
public final static synthetic access$getClientKeypair$p(Lcom/takharsh/ecdh/MainActivity;)Ljava/security/KeyPair;
`L0
LINENUMBER 11 L0
ALOAD 0
GETFIELD com/takharsh/ecdh/MainActivity.clientKeypair : Ljava/security/KeyPair;
DUP
IFNONNULL L1
LDC "clientKeypair"
INVOKESTATIC kotlin/jvm/internal/Intrinsics.throwUninitializedPropertyAccessException (Ljava/lang/String;)V
L1
ARETURN
L2 LOCALVARIABLE $this Lcom/takharsh/ecdh/MainActivity; L0 L2 0 MAXSTACK = 2 MAXLOCALS = 1
Kotlin creates an extra local variable of same instance and check if it null or not, if null then throws 'throwUninitializedPropertyAccessException' else return the local object.
Above bytecode explained here
Solution
Since kotlin 1.2 it allows to check weather lateinit var has been initialized or not using .isInitialized
The Nathan Matthews's solution did not work for me but it is totally correct but there is little point to reaching a workaround:
The key point is: Type of defined parameters and toParamas of $state.go should be same array or object on both sides of state transition.
For example when you define a params in a state as follows you means params is array because of using "[]":
$stateProvider
.state('home', {
templateUrl: 'home',
controller: 'homeController'
})
.state('view', {
templateUrl: 'overview',
params: ['index', 'anotherKey'],
controller: 'overviewController'
})
So also you should pass toParams as array like this:
params = { 'index': 123, 'anotherKey': 'This is a test' }
paramsArr = (val for key, val of params)
$state.go('view', paramsArr)
And you can access them via $stateParams as array like this:
app.controller('overviewController', function($scope, $stateParams) {
var index = $stateParams[0];
var anotherKey = $stateParams[1];
});
Better solution is using object instead of array in both sides:
$stateProvider
.state('home', {
templateUrl: 'home',
controller: 'homeController'
})
.state('view', {
templateUrl: 'overview',
params: {'index': null, 'anotherKey': null},
controller: 'overviewController'
})
I replaced [] with {} in params definition. For passing toParams to $state.go also you should using object instead of array:
$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' })
then you can access them via $stateParams easily:
app.controller('overviewController', function($scope, $stateParams) {
var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
});
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
You need to escape the braces:
git stash pop stash@\{1\}
I was struggling with the above solutions when I wanted to automate my ordering process for n columns, whose column names could be different each time. I found a super helpful function from the psych
package to do this in a straightforward manner:
dfOrder(myDf, columnIndices)
where columnIndices
are indices of one or more columns, in the order in which you want to sort them. More information here:
Thanks a lot, it works like this:
java -Djava.rmi.server.hostname=xxx.xxx.xxx.xxx -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=25000 -jar myjar.jar
In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using
<encoder>
<pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern>
</encoder>
the %ex in pattern is what makes the difference
there is a function that will return an array of all the strings found.
Filter(sourcearray, match[, include[, compare]])
The sourcearray has to be 1 dimensional
The function will return all strings in the array that have the match
string in them
If I understand the question correctly you are looking for something like this:
>>> s = "a1 c2 OR c3 AND"
>>> boolops = ["AND", "OR", "NOT"]
>>> if not any(boolop in s for boolop in boolops):
... print "no boolean operator"
...
>>> s = "test"
>>> if not any(boolop in s for boolop in boolops):
... print "no boolean operator"
...
no boolean operator
>>>
Put the URLs into an HTML table, load the HTML page into a browser, copy the contents of that page, paste into Excel. At this point the URLs are preserved as active links.
Solution was proposed on http://answers.microsoft.com/en-us/mac/forum/macoffice2008-macexcel/how-to-copy-and-paste-to-mac-excel-2008-a-list-of/c5fa2890-acf5-461d-adb5-32480855e11e by (Jim Gordon Mac MVP)[http://answers.microsoft.com/en-us/profile/75a2b744-a259-49bb-8eb1-7db61dae9e78]
I found that it worked.
I had these URLs:
https://twitter.com/keeseter/status/578350771235872768/photo/1 https://instagram.com/p/ys5ASPCDEV/ https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-15/10881854_329617847240910_1814142151_n.jpg https://twitter.com/ranadotson/status/539485028712189952/photo/1 https://instagram.com/p/0OgdvyxMhW/ https://instagram.com/p/1nynTiiLSb/
I put them into an HTML file (links.html) like this:
<table>
<tr><td><a href="https://twitter.com/keeseter/status/578350771235872768/photo/1">https://twitter.com/keeseter/status/578350771235872768/photo/1</a></td></tr>
<tr><td><a href="https://instagram.com/p/ys5ASPCDEV/">https://instagram.com/p/ys5ASPCDEV/</a></td></tr>
<tr><td><a href="https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-15/10881854_329617847240910_1814142151_n.jpg">https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-15/10881854_329617847240910_1814142151_n.jpg</a></td></tr>
<tr><td><a href="https://twitter.com/ranadotson/status/539485028712189952/photo/1">https://twitter.com/ranadotson/status/539485028712189952/photo/1</a></td></tr>
<tr><td><a href="https://instagram.com/p/0OgdvyxMhW/">https://instagram.com/p/0OgdvyxMhW/</a></td></tr>
</table>
Then I loaded the links.html into my browser, copied, pasted into Excel, and the links were active.
When you read the string from the GUI control, it is already a "raw" string. If you print out the string you might see the backslashes doubled up, but that's an artifact of how Python displays strings; internally there's still only a single backslash.
>>> a='\nu + \lambda + \theta'
>>> a
'\nu + \\lambda + \theta'
>>> len(a)
20
>>> b=r'\nu + \lambda + \theta'
>>> b
'\\nu + \\lambda + \\theta'
>>> len(b)
22
>>> b[0]
'\\'
>>> print b
\nu + \lambda + \theta
if you're utilizing a UINavigationController and also want to handle modal views, the following is what i use:
#import <objc/runtime.h>
UIViewController* topMostController = self.navigationController.visibleViewController;
if([[NSString stringWithFormat:@"%s", class_getName([topMostController class])] isEqualToString:@"NAME_OF_CONTROLLER_YOURE_CHECKING_IN"]) {
//is topmost visible view controller
}
The ".then()" function is wideley used for promised objects in Asynchoronus programming For Windows 8 Store Apps. As far as i understood it works some way like a callback.
Find Details in this Documentantion http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx
Of Cause it could also be the name for any other defined function.
Use MoreLINQ, which has a DistinctBy
method :)
IEnumerable<Car> distinctCars = cars.DistinctBy(car => car.CarCode);
(This is only for LINQ to Objects, mind you.)
Performance characteristics for lists are described on Effbot.
Python lists are actually implemented as vector for fast random access, so the container will basically hold as many items as there is space for in memory. (You need space for pointers contained in the list as well as space in memory for the object(s) being pointed to.)
Appending is O(1)
(amortized constant complexity), however, inserting into/deleting from the middle of the sequence will require an O(n)
(linear complexity) reordering, which will get slower as the number of elements in your list.
Your sorting question is more nuanced, since the comparison operation can take an unbounded amount of time. If you're performing really slow comparisons, it will take a long time, though it's no fault of Python's list data type.
Reversal just takes the amount of time it required to swap all the pointers in the list (necessarily O(n)
(linear complexity), since you touch each pointer once).
I created this Function after researching on the internet since I wanted to print an XML string when you select a row from a data grid view.
static void HighlightPhrase(RichTextBox box, string StartTag, string EndTag, string ControlTag, Color color1, Color color2)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ; )
{
int jx = s.IndexOf(StartTag, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
int ex = s.IndexOf(EndTag, ix, StringComparison.CurrentCultureIgnoreCase);
box.SelectionStart = jx;
box.SelectionLength = ex - jx + 1;
box.SelectionColor = color1;
int bx = s.IndexOf(ControlTag, ix, StringComparison.CurrentCultureIgnoreCase);
int bxtest = s.IndexOf(StartTag, (ex + 1), StringComparison.CurrentCultureIgnoreCase);
if (bx == bxtest)
{
box.SelectionStart = ex + 1;
box.SelectionLength = bx - ex + 1;
box.SelectionColor = color2;
}
ix = ex + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
and this is how you call it
HighlightPhrase(richTextBox1, "<", ">","</", Color.Red, Color.Black);
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!
<form action="{{url('/url_part_in_route').'/'.$parameter_of_update_function_of_resource_controller}}" method="post">
@csrf
<input type="hidden" name="_method" value="PUT"> // or @method('put')
.... // remained instructions
<form>
You get the value of the textarea, use it :
$('.type').keyup(function() {
var v = $('.type').val(); // you'd better use this.value here
if (v.indexOf('> <')!=-1) {
console.log('contains > <');
}
});
Simple
<input type="text" />
<script>
$("input").focusin(function() {
alert("I am in Focus");
});
</script>
This worked for me:
list.stream().distinct().collect(Collectors.toList());
You need to implement equals, of course
This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.
int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();
Hope this answers the question.
UTF-8 is a variable-length encoding. In the case of UTF-8, this means that storing one code point requires one to four bytes. However, MySQL's encoding called "utf8" (alias of "utf8mb3") only stores a maximum of three bytes per code point.
So the character set "utf8"/"utf8mb3" cannot store all Unicode code points: it only supports the range 0x000 to 0xFFFF, which is called the "Basic Multilingual Plane". See also Comparison of Unicode encodings.
This is what (a previous version of the same page at) the MySQL documentation has to say about it:
The character set named utf8[/utf8mb3] uses a maximum of three bytes per character and contains only BMP characters. As of MySQL 5.5.3, the utf8mb4 character set uses a maximum of four bytes per character supports supplemental characters:
For a BMP character, utf8[/utf8mb3] and utf8mb4 have identical storage characteristics: same code values, same encoding, same length.
For a supplementary character, utf8[/utf8mb3] cannot store the character at all, while utf8mb4 requires four bytes to store it. Since utf8[/utf8mb3] cannot store the character at all, you do not have any supplementary characters in utf8[/utf8mb3] columns and you need not worry about converting characters or losing data when upgrading utf8[/utf8mb3] data from older versions of MySQL.
So if you want your column to support storing characters lying outside the BMP (and you usually want to), such as emoji, use "utf8mb4". See also What are the most common non-BMP Unicode characters in actual use?.
In java you don't check if a key is pressed, instead you listen to KeyEvent
s.
The right way to achieve your goal is to register a KeyEventDispatcher
, and implement it to maintain the state of the desired key:
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class IsKeyPressed {
private static volatile boolean wPressed = false;
public static boolean isWPressed() {
synchronized (IsKeyPressed.class) {
return wPressed;
}
}
public static void main(String[] args) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (IsKeyPressed.class) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = true;
}
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = false;
}
break;
}
return false;
}
}
});
}
}
Then you can always use:
if (IsKeyPressed.isWPressed()) {
// do your thing.
}
You can, of course, use same method to implement isPressing("<some key>")
with a map of keys and their state wrapped inside IsKeyPressed
.
In this working example, the user confirms in JavaScript that he really wants to abort. If true, the button is disabled to prevent double click and then the code behind which updates the database will run.
<asp:button id="btnAbort" runat="server" OnClick="btnAbort_Click" OnClientClick="if (!abort()) {return false;};" UseSubmitBehavior="false" text="Abort" ></asp:button>
I had issues because .net can change the name of the button
function abort() {
if (confirm('<asp:Literal runat="server" Text="Do you want to abort?" />')) {
var btn = document.getElementById('btnAbort');
btn.disabled = true;
btn.innerText = 'Aborting...'
return true;
}
else {
return false;
}
}
Because you are overriding the OnClick with OnClientClick, even if your validation method succeeds, the code behind wont work. That's why you set UseSubmitBehavior to false to make it work
PS: You don't need the OnClick if your code is in vb.net!
Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/
That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.
$('.bwWrapper').BlackAndWhite({
hoverEffect : true, // default true
// set the path to BnWWorker.js for a superfast implementation
webworkerPath : false,
// to invert the hover effect
invertHoverEffect: false,
// this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
intensity:1,
speed: { //this property could also be just speed: value for both fadeIn and fadeOut
fadeIn: 200, // 200ms for fadeIn animations
fadeOut: 800 // 800ms for fadeOut animations
},
onImageReady:function(img) {
// this callback gets executed anytime an image is converted
}
});
Use php function array_diff(array1, array2);
It will return a the difference between arrays. If its empty then they're equal.
example:
$array1 = array(
'a' => 'value1',
'b' => 'value2',
'c' => 'value3'
);
$array2 = array(
'a' => 'value1',
'b' => 'value2',
'c' => 'value4'
);
$diff = array_diff(array1, array2);
var_dump($diff);
//it will print array = (0 => ['c'] => 'value4' )
Example 2:
$array1 = array(
'a' => 'value1',
'b' => 'value2',
'c' => 'value3',
);
$array2 = array(
'a' => 'value1',
'b' => 'value2',
'c' => 'value3',
);
$diff = array_diff(array1, array2);
var_dump($diff);
//it will print empty;
You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399
part to the URL (you can see this in your dump of the request).
What you're returning is JSON, not JSONP. Your response looks like
{"red" : "#f00"}
and jQuery is expecting something like this:
jQuery16406345664265099913_1319854793396({"red" : "#f00"})
If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json
needs to be able to actually return a JSONP response.
If the same origin policy isn't an issue for your application, then you just need to fix the dataType
in your jQuery.ajax
call to be json
instead of jsonp
.
The server name should be same as the first/last name which you give while create a certificate
There are two common approaches for this:
Specify http-proxy-
options in your /etc/.subversion/servers or %APPDATA%\Subversion\servers file,
Use --config-option
command-line option to specify the same http-proxy-
options in single command-line you run. For example,
svn checkout ^
--config-option servers:global:http-proxy-host=<PROXY-HOST> ^
--config-option servers:global:http-proxy-port=<PORT> <REPO-URL> <LWC-DIR>
If you are on Windows, you can also write http-proxy-
options to Windows Registry. It's pretty handy if you need to apply proxy settings in Active Directory environment via Group Policy Objects.
Immediately after the object is instantiatd, you can attach a property, say name
, to the object and assign the string value you expect to it:
var myObj = new someClass();
myObj.name="myObj";
document.write(myObj.name);
Alternatively, the assignment can be made inside the codes of the class, i.e.
var someClass = function(P)
{ this.name=P;
// rest of the class definition...
};
var myObj = new someClass("myObj");
document.write(myObj.name);
Why javascript when you can use just css?
a[aria-expanded="true"]{_x000D_
background-color: #42DCA3;_x000D_
}
_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> _x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> _x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>
_x000D_
You can use as the following code;
cd /my_folder && \
rm *.jar && \
svn co path to repo && \
mvn compile package install
It works...
you can also try
git show <filename>
For commits, git show will show the log message and textual diff (between your file and the commited version of the file).
You can check git show Documentation for more info.
If you have a LDAP connection with a username and password to connect to Active Directory, here is the code I used to connect properly:
using System.DirectoryServices.AccountManagement;
// ...
// Connection information
var connectionString = "LDAP://domain.com/DC=domain,DC=com";
var connectionUsername = "your_ad_username";
var connectionPassword = "your_ad_password";
// Get groups for this user
var username = "myusername";
// Split the LDAP Uri
var uri = new Uri(connectionString);
var host = uri.Host;
var container = uri.Segments.Count() >=1 ? uri.Segments[1] : "";
// Create context to connect to AD
var princContext = new PrincipalContext(ContextType.Domain, host, container, connectionUsername, connectionPassword);
// Get User
UserPrincipal user = UserPrincipal.FindByIdentity(princContext, IdentityType.SamAccountName, username);
// Browse user's groups
foreach (GroupPrincipal group in user.GetGroups())
{
Console.Out.WriteLine(group.Name);
}
If you are using Java configuration in a spring-data-jpa project, make sure you are scanning the package that the entity is in. For example, if the entity lived com.foo.myservice.things then the following configuration annotation below would not pick it up.
You could fix it by loosening it up to just com.foo.myservice (of course, keep in mind any other effects of broadening your scope to scan for entities).
@Configuration
@EnableJpaAuditing
@EnableJpaRepositories("com.foo.myservice.repositories")
public class RepositoryConfiguration {
}
How about creating a function to hijack the reject and return it ?
function createRejectablePromise(handler) {
let _reject;
const promise = new Promise((resolve, reject) => {
_reject = reject;
handler(resolve, reject);
})
promise.reject = _reject;
return promise;
}
// Usage
const { reject } = createRejectablePromise((resolve) => {
setTimeout(() => {
console.log('resolved')
resolve();
}, 2000)
});
reject();
I've actually resorted to a bit of trickery to deal with this at times. I developed a jQuery scrollbar widget where I encountered the problem that I don't know ahead of time if the scrollable content is a part of a hidden piece of markup or not. Here's what I did:
// try to grab the height of the elem
if (this.element.height() > 0) {
var scroller_height = this.element.height();
var scroller_width = this.element.width();
// if height is zero, then we're dealing with a hidden element
} else {
var copied_elem = this.element.clone()
.attr("id", false)
.css({visibility:"hidden", display:"block",
position:"absolute"});
$("body").append(copied_elem);
var scroller_height = copied_elem.height();
var scroller_width = copied_elem.width();
copied_elem.remove();
}
This works for the most part, but there's an obvious problem that can potentially come up. If the content you are cloning is styled with CSS that includes references to parent markup in their rules, the cloned content will not contain the appropriate styling, and will likely have slightly different measurements. To get around this, you can make sure that the markup you are cloning has CSS rules applied to it that do not include references to parent markup.
Also, this didn't come up for me with my scroller widget, but to get the appropriate height of the cloned element, you'll need to set the width to the same width of the parent element. In my case, a CSS width was always applied to the actual element, so I didn't have to worry about this, however, if the element doesn't have a width applied to it, you may need to do some kind of recursive traversal of the element's DOM ancestry to find the appropriate parent element's width.
from http://code.google.com/p/fast-serialization/wiki/QuickStartHeapOff
What is Heap-Offloading ?
Usually all non-temporary objects you allocate are managed by java's garbage collector. Although the VM does a decent job doing garbage collection, at a certain point the VM has to do a so called 'Full GC'. A full GC involves scanning the complete allocated Heap, which means GC pauses/slowdowns are proportional to an applications heap size. So don't trust any person telling you 'Memory is Cheap'. In java memory consumtion hurts performance. Additionally you may get notable pauses using heap sizes > 1 Gb. This can be nasty if you have any near-real-time stuff going on, in a cluster or grid a java process might get unresponsive and get dropped from the cluster.
However todays server applications (frequently built on top of bloaty frameworks ;-) ) easily require heaps far beyond 4Gb.
One solution to these memory requirements, is to 'offload' parts of the objects to the non-java heap (directly allocated from the OS). Fortunately java.nio provides classes to directly allocate/read and write 'unmanaged' chunks of memory (even memory mapped files).
So one can allocate large amounts of 'unmanaged' memory and use this to save objects there. In order to save arbitrary objects into unmanaged memory, the most viable solution is the use of Serialization. This means the application serializes objects into the offheap memory, later on the object can be read using deserialization.
The heap size managed by the java VM can be kept small, so GC pauses are in the millis, everybody is happy, job done.
It is clear, that the performance of such an off heap buffer depends mostly on the performance of the serialization implementation. Good news: for some reason FST-serialization is pretty fast :-).
Sample usage scenarios:
Edit: For some scenarios one might choose more sophisticated Garbage Collection algorithms such as ConcurrentMarkAndSweep or G1 to support larger heaps (but this also has its limits beyond 16GB heaps). There is also a commercial JVM with improved 'pauseless' GC (Azul) available.
Converted DateID having date in Int format to date format: Presto Query
Select CAST(date_format(date_parse(cast(dateid as varchar(10)), '%Y%m%d'), '%Y/%m-%d') AS DATE)
from
Table_Name
limit 10;
Try using an Object, not an Array:
var test = new Object(); test[2300] = 'Some string';
My issue was that I was creating objects that I wanted to be stored in a NSMutableDictionary but I never initialized the dictionary. Therefore the objects were getting deleted by garbage collection and breaking later. Check that you have at least one strong reference to the objects youre interacting with.
With Git 2.7 (release January 5th, 2015), you have a more coherent solution using git remote
:
git remote get-url origin
(nice pendant of git remote set-url origin <newurl>
)
See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf
).
(Merged by Junio C Hamano -- gitster
-- in commit e437cbd, 05 Oct 2015):
remote: add get-url subcommand
Expanding
insteadOf
is a part ofls-remote --url
and there is no way to expandpushInsteadOf
as well.
Add aget-url
subcommand to be able to query both as well as a way to get all configured URLs.
get-url:
Retrieves the URLs for a remote.
Configurations forinsteadOf
andpushInsteadOf
are expanded here.
By default, only the first URL is listed.
- With '
--push
', push URLs are queried rather than fetch URLs.- With '
--all
', all URLs for the remote will be listed.
Before git 2.7, you had:
git config --get remote.[REMOTE].url
git ls-remote --get-url [REMOTE]
git remote show [REMOTE]
Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.
from numpy.polynomial import Polynomial
p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())
p
uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with
pnormal = p.convert(domain=(-1, 1))
try this code: :)
get value:
$("#Ostans option:selected").val() + '.' + $("#shahrha option:selected").val()
get text:
$("#Ostans option:selected").text() + '.' + $("#shahrha option:selected").text()
CTRL+D? http://www.scribd.com/doc/7580088/SQL-Developer-Hot-Keys
If that doesn't work, you might be able to set up an Accelerator: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b31695/intro.htm#sthref208
I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.
Here's Sun's docs on the subject matter.
Queue is an Interface so you can not initiate it directly. Initiate it by one of its implementing classes.
From the docs all known implementing classes:
You can use any of above based on your requirement to initiate a Queue object.
My issue was that I was trying to give my ssh key a SPECIFIC NAME every time I entered ssh-keygen
on my mac terminal.
I solved the issue by just leaving the name that "ssh-keygen" generates = id_rsa
. You'll end up with 2 keys in your .ssh folder on a mac, id_rsa
, which is your private key, and the id_rsa.pub
, which is your public key. Then I copied and saved the code from id_rsa.pub
into my GitHub account settings, and that was it. Problem solved.
So it would become:
List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
Iterator<Integer> myListIterator = myCoords.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.print("\r" + coord);
try{
Thread.sleep(2000);
}catch(Exception e){
// handle the exception...
}
}
}
This question is old. But I would like to mention an other approach. Using Enums for declaring constant values. Based on the answer of Nandkumar Tekale, the Enum can be used as below:
Enum:
public enum Planck {
REDUCED();
public static final double PLANCK_CONSTANT = 6.62606896e-34;
public static final double PI = 3.14159;
public final double REDUCED_PLANCK_CONSTANT;
Planck() {
this.REDUCED_PLANCK_CONSTANT = PLANCK_CONSTANT / (2 * PI);
}
public double getValue() {
return REDUCED_PLANCK_CONSTANT;
}
}
Client class:
public class PlanckClient {
public static void main(String[] args) {
System.out.println(getReducedPlanckConstant());
// or using Enum itself as below:
System.out.println(Planck.REDUCED.getValue());
}
public static double getReducedPlanckConstant() {
return Planck.PLANCK_CONSTANT / (2 * Planck.PI);
}
}
Reference : The usage of Enums for declaring constant fields is suggested by Joshua Bloch in his Effective Java book.
According to your example here it seems that they both reside in the same namespace, i conclude that they are both part of the same project ( if you haven't created another project with the same namespace) and all class by default are defined as internal to the project they are defined in, if haven't declared otherwise, therefore i guess the problem is that your file is not included in your project. You can include it by right clicking the file in the solution explorer window => Include in project, if you cannot see the file inside the project files in the solution explorer then click the show the upper menu button of the solution explorer called show all files ( just hove your mouse cursor over the button there and you'll see the names of the buttons)
Just for basic knowledge: If the file resides in a different project\ assembly then it has to be defined, otherwise it has to be define at least as internal or public. in case your class is inheriting from that class that it can be protected as well.
How to update in codeignitor?
whenever you want to update same status with multiple rows you use where_in insteam of where or if you want to change only single record can use where.
below is my code
$conditionArray = array(1, 3, 4, 6);
$this->db->where_in("ip_id", $conditionArray);
$this->db->update($this->table, array("status" => 'active'));
its working perfect.
There's one huge difference between git and mercurial; the way the represent each commit. git represents commits as snapshots, while mercurial represents them as diffs.
What does this means in practice? Well, many operations are faster in git, such as switching to another commit, comparing commits, etc. Specially if these commits are far away.
AFAIK there's no advantage of mercurial's approach.
The best way would be sharing the variable using View::share('var', $value);
Problems with composing using "*"
:
Consider following approach:
<?php
// from AppServiceProvider::boot()
$viewFactory = $this->app->make(Factory::class);
$viewFacrory->compose('*', GlobalComposer::class);
From an example blade view:
@for($i = 0; $i<1000; $i++)
@include('some_partial_view_to_display_i', ['toDisplay' => $i])
@endfor
What happens?
GlobalComposer
class is instantiated 1000 times using
App::make
. composing:some_partial_view_to_display_i
is handled
1000 times.compose
function inside the GlobalComposer
class is called 1000 times.But the partial view some_partial_view_to_display_i
has nothing to do with the variables composed by GlobalComposer
but heavily increases render time.
Best approach?
Using View::share
along a grouped middleware.
Route::group(['middleware' => 'WebMiddleware'], function(){
// Web routes
});
Route::group(['prefix' => 'api'], function (){
});
class WebMiddleware {
public function handle($request)
{
\View::share('user', auth()->user());
}
}
Update
If you are using something that is computed over the middleware pipeline you can simply listen to the proper event or put the view share middleware at the last bottom of the pipeline.
a fix to fann95's response, using in-place modification of the string, and assuming the buffer pointed to by line is large enough to hold the resulting string.
static void replacestr(char *line, const char *search, const char *replace)
{
char *sp;
if ((sp = strstr(line, search)) == NULL) {
return;
}
int search_len = strlen(search);
int replace_len = strlen(replace);
int tail_len = strlen(sp+search_len);
memmove(sp+replace_len,sp+search_len,tail_len+1);
memcpy(sp, replace, replace_len);
}
As other have answered, the result is exactly the same, None
is returned in all cases.
The difference is stylistic, but please note that PEP8 requires the use to be consistent:
Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).
Yes:
def foo(x): if x >= 0: return math.sqrt(x) else: return None def bar(x): if x < 0: return None return math.sqrt(x)
No:
def foo(x): if x >= 0: return math.sqrt(x) def bar(x): if x < 0: return return math.sqrt(x)
https://www.python.org/dev/peps/pep-0008/#programming-recommendations
Basically, if you ever return non-None
value in a function, it means the return value has meaning and is meant to be caught by callers. So when you return None
, it must also be explicit, to convey None
in this case has meaning, it is one of the possible return values.
If you don't need return at all, you function basically works as a procedure instead of a function, so just don't include the return
statement.
If you are writing a procedure-like function and there is an opportunity to return earlier (i.e. you are already done at that point and don't need to execute the remaining of the function) you may use empty an return
s to signal for the reader it is just an early finish of execution and the None
value returned implicitly doesn't have any meaning and is not meant to be caught (the procedure-like function always returns None
anyway).
A very simple check you can do with Cell formulas:
Sheet 1 (new - old)
=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")
Sheet 2 (old - new)
=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")
This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)
You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".
Doe the same for Sheet two.
Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.
But two cases are not covered here:
To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com
I have found that if you are using ammps that for some reason its always forbidden when its in your root folder so i put it in the directory above my root folder and made a alias in the httpd.conf
using this
Alias /phpmyadmin "C:/Program Files (x86)/Ampps/phpMyAdmin"
please note i am using ammps and i dont know for sure if it will work for others but its worth a try ;)
In my case, i succeeded by doing this:
1- enable 'Auto-Rotate', if it isnĀ“t yet.
2- either use rotation left-right option at panel located next to the virtual device, or click (ctrl + left/right arrow key), in order to rotate the device.
Hope it works for you.
To make the solution by @flion look really great, you could adjust the center point for that icon so it doesn't wobble up and down. This looks right for me at a small font size:
.glyphicon-refresh.spinning {
transform-origin: 48% 50%;
}
@Query("SELECT DISTINCT name FROM people WHERE name NOT IN (:names)")
List<String> findNonReferencedNames(@Param("names") List<String> names);
This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)
other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};
printMatrix(matrix);
public void printMatrix(int[][] m){
try{
int rows = m.length;
int columns = m[0].length;
String str = "|\t";
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
str += m[i][j] + "\t";
}
System.out.println(str + "|");
str = "|\t";
}
}catch(Exception e){System.out.println("Matrix is empty!!");}
}
Output:
| 1 2 3 |
| 4 5 6 |
| 7 8 9 |
| 10 11 12 |
Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top
, padding-bottom
, padding-left
, and padding-right;
or padding: [top] [right] [bottom] [left];
).
Both of the answers presented here will not handle repeated elements. For example, if you are testing whether [1,2,2] is a sublist of [1,2,3,4], both will return True. That may be what you mean to do, but I just wanted to clarify. If you want to return false for [1,2,2] in [1,2,3,4], you would need to sort both lists and check each item with a moving index on each list. Just a slightly more complicated for loop.
Additional to @Daniel Waltrip answer. Table need to enclose with div position: relative
in order to work with position:sticky
. So I would like to post my sample code here.
CSS
/* Set table width/height as you want.*/
div.freeze-header {
position: relative;
max-height: 150px;
max-width: 400px;
overflow:auto;
}
/* Use position:sticky to freeze header on top*/
div.freeze-header > table > thead > tr > th {
position: sticky;
top: 0;
background-color:yellow;
}
/* below is just table style decoration.*/
div.freeze-header > table {
border-collapse: collapse;
}
div.freeze-header > table td {
border: 1px solid black;
}
HTML
<html>
<body>
<div>
other contents ...
</div>
<div>
other contents ...
</div>
<div>
other contents ...
</div>
<div class="freeze-header">
<table>
<thead>
<tr>
<th> header 1 </th>
<th> header 2 </th>
<th> header 3 </th>
<th> header 4 </th>
<th> header 5 </th>
<th> header 6 </th>
<th> header 7 </th>
<th> header 8 </th>
<th> header 9 </th>
<th> header 10 </th>
<th> header 11 </th>
<th> header 12 </th>
<th> header 13 </th>
<th> header 14 </th>
<th> header 15 </th>
</tr>
</thead>
<tbody>
<tr>
<td> data 1 </td>
<td> data 2 </td>
<td> data 3 </td>
<td> data 4 </td>
<td> data 5 </td>
<td> data 6 </td>
<td> data 7 </td>
<td> data 8 </td>
<td> data 9 </td>
<td> data 10 </td>
<td> data 11 </td>
<td> data 12 </td>
<td> data 13 </td>
<td> data 14 </td>
<td> data 15 </td>
</tr>
<tr>
<td> data 1 </td>
<td> data 2 </td>
<td> data 3 </td>
<td> data 4 </td>
<td> data 5 </td>
<td> data 6 </td>
<td> data 7 </td>
<td> data 8 </td>
<td> data 9 </td>
<td> data 10 </td>
<td> data 11 </td>
<td> data 12 </td>
<td> data 13 </td>
<td> data 14 </td>
<td> data 15 </td>
</tr>
<tr>
<td> data 1 </td>
<td> data 2 </td>
<td> data 3 </td>
<td> data 4 </td>
<td> data 5 </td>
<td> data 6 </td>
<td> data 7 </td>
<td> data 8 </td>
<td> data 9 </td>
<td> data 10 </td>
<td> data 11 </td>
<td> data 12 </td>
<td> data 13 </td>
<td> data 14 </td>
<td> data 15 </td>
</tr>
<tr>
<td> data 1 </td>
<td> data 2 </td>
<td> data 3 </td>
<td> data 4 </td>
<td> data 5 </td>
<td> data 6 </td>
<td> data 7 </td>
<td> data 8 </td>
<td> data 9 </td>
<td> data 10 </td>
<td> data 11 </td>
<td> data 12 </td>
<td> data 13 </td>
<td> data 14 </td>
<td> data 15 </td>
</tr>
<tr>
<td> data 1 </td>
<td> data 2 </td>
<td> data 3 </td>
<td> data 4 </td>
<td> data 5 </td>
<td> data 6 </td>
<td> data 7 </td>
<td> data 8 </td>
<td> data 9 </td>
<td> data 10 </td>
<td> data 11 </td>
<td> data 12 </td>
<td> data 13 </td>
<td> data 14 </td>
<td> data 15 </td>
</tr>
<tr>
<td> data 1 </td>
<td> data 2 </td>
<td> data 3 </td>
<td> data 4 </td>
<td> data 5 </td>
<td> data 6 </td>
<td> data 7 </td>
<td> data 8 </td>
<td> data 9 </td>
<td> data 10 </td>
<td> data 11 </td>
<td> data 12 </td>
<td> data 13 </td>
<td> data 14 </td>
<td> data 15 </td>
</tr>
<tr>
<td> data 1 </td>
<td> data 2 </td>
<td> data 3 </td>
<td> data 4 </td>
<td> data 5 </td>
<td> data 6 </td>
<td> data 7 </td>
<td> data 8 </td>
<td> data 9 </td>
<td> data 10 </td>
<td> data 11 </td>
<td> data 12 </td>
<td> data 13 </td>
<td> data 14 </td>
<td> data 15 </td>
</tr>
<tr>
<td> data 1 </td>
<td> data 2 </td>
<td> data 3 </td>
<td> data 4 </td>
<td> data 5 </td>
<td> data 6 </td>
<td> data 7 </td>
<td> data 8 </td>
<td> data 9 </td>
<td> data 10 </td>
<td> data 11 </td>
<td> data 12 </td>
<td> data 13 </td>
<td> data 14 </td>
<td> data 15 </td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Demo
git push --follow-tags
This is a sane option introduced in Git 1.8.3:
git push --follow-tags
It pushes both commits and only tags that are both:
This is sane because:
It is for those reasons that --tags
should be avoided.
Git 2.4 has added the push.followTags
option to turn that flag on by default which you can set with:
git config --global push.followTags true
or by adding followTags = true
to the [push]
section of your ~/.gitconfig
file.
Google has created a library for easy Permissions management. Its called EasyPermissions
Here is a simple example on requesting Location permission using this library.
public class MainActivity extends AppCompatActivity {
private final int REQUEST_LOCATION_PERMISSION = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestLocationPermission();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(this, perms)) {
Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
}
@AfterPermissionsGranted(REQUEST_CODE)
is used to indicate the method that needs to be executed after a permission request with the request code REQUEST_CODE
has been granted.
This above case, the method requestLocationPermission()
method is called if the user grants the permission to access location services. So, that method acts as both a callback and a method to request the permissions.
You can implement separate callbacks for permission granted and permission denied as well. It is explained in the github page.
I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.
The steps are :
You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers
Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.
Edit : you have to repeat the steps every time you will go on the production site.
The same problem when I export the library httclient-4.3.5 in Android Studio 0.8.6 I need include this:
packagingOptions{
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
}
The library zip content the next jar:
commons-codec-1.6.jar
commons-logging-1.1.3.jar
fluent-hc-4.3.5.jar
httpclient-4.3.5.jar
httpclient-cache-4.3.5.jar
httpcore-4.3.2.jar
httpmime-4.3.5.jar
I wanted to support a self signed certificate in a Tomcat App but the following snippet failed to work
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HTTPSPlayground {
public static void main(String[] args) throws Exception {
URL url = new URL("https:// ... .com");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
String serializedMessage = "{}";
wr.writeBytes(serializedMessage);
wr.flush();
wr.close();
int responseCode = httpURLConnection.getResponseCode();
System.out.println(responseCode);
}
}
this is what solved my issue:
.crt
fileecho -n | openssl s_client -connect <your domain>:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/<your domain>.crt
<your domain>
with your domain (e.g. jossef.com
).crt
file in Java's cacerts
certificate storekeytool -import -v -trustcacerts -alias <your domain> -file ~/<your domain>.crt -keystore <JAVA HOME>/jre/lib/security/cacerts -keypass changeit -storepass changeit
<your domain>
with your domain (e.g. jossef.com
)<JAVA HOME>
with your java home directoryEven though iv'e installed my certificate in Java
's default certificate stores, Tomcat ignores that (seems like it's not configured to use Java's default certificate stores).
To hack this, add the following somewhere in your code:
String certificatesTrustStorePath = "<JAVA HOME>/jre/lib/security/cacerts";
System.setProperty("javax.net.ssl.trustStore", certificatesTrustStorePath);
// ...
Use url instead of path.
from django.conf.urls import url
urlpatterns = [
url('', views.homepageview, name='home')
]
Hope below code will work :
<!--Disable Copy And Paste-->
<script language='JavaScript1.2'>
function disableselect(e){
return false
}
function reEnable(){
return true
}
document.onselectstart=new Function ("return false")
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
First of all, this line
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click()
there.
If you read the JavaScript you've got there, document.getElementById('foo')
it's looking for an HTML element with an ID of foo
. You don't have one. Give your image that ID:
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
Alternatively, you could throw the JS in a function and put an onclick in your HTML:
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />
I suggest you do some reading up on JavaScript and HTML though.
The others are right about needing to move the <img>
above the JS click binding too.
myclass.h
#ifndef __MYCLASS_H__
#define __MYCLASS_H__
class MyClass
{
public:
MyClass();
/* use virtual otherwise linker will try to perform static linkage */
virtual void DoSomething();
private:
int x;
};
#endif
myclass.cc
#include "myclass.h"
#include <iostream>
using namespace std;
extern "C" MyClass* create_object()
{
return new MyClass;
}
extern "C" void destroy_object( MyClass* object )
{
delete object;
}
MyClass::MyClass()
{
x = 20;
}
void MyClass::DoSomething()
{
cout<<x<<endl;
}
class_user.cc
#include <dlfcn.h>
#include <iostream>
#include "myclass.h"
using namespace std;
int main(int argc, char **argv)
{
/* on Linux, use "./myclass.so" */
void* handle = dlopen("myclass.so", RTLD_LAZY);
MyClass* (*create)();
void (*destroy)(MyClass*);
create = (MyClass* (*)())dlsym(handle, "create_object");
destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object");
MyClass* myClass = (MyClass*)create();
myClass->DoSomething();
destroy( myClass );
}
On Mac OS X, compile with:
g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user
On Linux, compile with:
g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user
If this were for a plugin system, you would use MyClass as a base class and define all the required functions virtual. The plugin author would then derive from MyClass, override the virtuals and implement create_object
and destroy_object
. Your main application would not need to be changed in any way.
This worked for me to copy a table remotely from my localhost to Heroku's postgresql:
pg_dump -C -t source_table -h localhost source_db | psql -h destination_host -U destination_user -p destination_port destination_db
This creates the table for you.
For the other direction (from Heroku to local)
pg_dump -C -t source_table -h source_host -U source_user -p source_port source_db | psql -h localhost destination_db
you can also try to parse the data and then check if you got object:
var testIfJson = JSON.parse(data);
if (typeOf testIfJson == "object")
{
//Json
}
else
{
//Not Json
}
While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt
and python-pip
.
Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
php5-mcrypt \
python-pip
However, according to this answer you should think about installing the python3-pip
package instead of the python-pip
package when using Python 3.x.
Furthermore, to make the php5-mcrypt
package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository
command missing in the Ubuntu Docker image so I installed the package software-properties-common
at first to make the command available.
Splitting up the statements and putting apt-get update
and apt-get install
into one RUN
command is also recommended here.
Oh and by the way, you actually don't need the -y
flag at apt-get update
because there is nothing that has to be confirmed automatically.
FROM ubuntu:14.04
# Install dependencies
RUN apt-get update && apt-get install -y \
software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
apache2 \
curl \
git \
libapache2-mod-php5 \
php5 \
php5-mcrypt \
php5-mysql \
python3.4 \
python3-pip
Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.
If you have two Location Objects Location loc1
and Location loc2
you do
float distance = loc1.distanceTo(loc2);
If you have longitude and latitude values you use the static distanceBetween()
function
float[] results = new float[1];
Location.distanceBetween(startLatitude, startLongitude,
endLatitude, endLongitude, results);
float distance = results[0];
scan
can read from a web page automatically; you don't necessarily have to mess with connections.
I just noticed that with C++20, we will have
bool std::map::contains( const Key& key ) const;
That will return true if map holds an element with key key
.
A different approach:
The vrapper plugin emulates vim
inside the Eclipse editor. One of its features is visual block
mode which works fine inside Eclipse.
It is by default mapped to Ctrl-V
which interferes with the paste command in Eclipse. You can either remap the visual block
mode to a different shortcut, or remap the paste
command to a different key. I chose the latter: remapped the paste
command to Ctrl-Shift-V
to match my terminal's behavior.
e.currentTarget
is always the element the event is actually bound do. e.target
is the element the event originated from, so e.target
could be a child of e.currentTarget
, or e.target
could be === e.currentTarget
, depending on how your markup is structured.
Read up some on css, it's fun: http://www.w3.org/Style/Examples/007/units.en.html
<style>
.bottom-three {
margin-bottom: 3cm;
}
</style>
<p class="bottom-three">
This is the first question?
</p>
<p class="bottom-three">
This is the second question?
</p>
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
After inserting new row to ListView, I just scroll the ListView to new position.
ListView.smoothScrollToPosition(position);
Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestClass test = new TestClass();
test.ModifyText(textBox1);
}
}
public class TestClass
{
public void ModifyText(TextBox textBox)
{
textBox.Text = "New text";
}
}
You could use various online tools to convert a HEX string to an actual UIColor. Check out uicolor.org or UI Color Picker. The output would be converted into Objective-C code, like:
[UIColor colorWithRed:0.93 green:0.80 blue:0.80 alpha:1.0];
Which you could embed in your application. Hope this helps!
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
try this
import java.sql.ResultSet;
import java.util.ArrayList;
import com.rcb.dbconnection.DbConnection;
import com.rcb.model.Docter;
public class DocterService {
public ArrayList<Docter> getAllDocters() {
ArrayList<Docter> docters = new ArrayList<Docter>();
try {
String sql = "SELECT tbl_docters";
ResultSet rs = db.getData(sql);
while (rs.next()) {
Docter docter = new Docter();
docter.setD_id(rs.getInt("d_id"));
docter.setD_FName(rs.getString("d_fname"));
docter.setD_LName(rs.getString("d_lname"));
docters.add(docter);
}
} catch (Exception e) {
System.out.println("getAllDocters()");
e.printStackTrace();
}
return (docters);
}
public static void main(String args[]) {
DocterService ds = new DocterService();
ArrayList<Docter> doctersList = ds.getAllDocters();
String s[] = null;
for (int i = 0; i < doctersList.size(); i++) {
System.out.println(doctersList.get(i).getD_id());
System.out.println(doctersList.get(i).getD_FName());
}
}
}
Algorithm
while(!game_over)
{
for each possible move:
evaluate next state
choose the maximum evaluation
}
Evaluation
Evaluation =
128 (Constant)
+ (Number of Spaces x 128)
+ Sum of faces adjacent to a space { (1/face) x 4096 }
+ Sum of other faces { log(face) x 4 }
+ (Number of possible next moves x 256)
+ (Number of aligned values x 2)
Evaluation Details
128 (Constant)
This is a constant, used as a base-line and for other uses like testing.
+ (Number of Spaces x 128)
More spaces makes the state more flexible, we multiply by 128 (which is the median) since a grid filled with 128 faces is an optimal impossible state.
+ Sum of faces adjacent to a space { (1/face) x 4096 }
Here we evaluate faces that have the possibility to getting to merge, by evaluating them backwardly, tile 2 become of value 2048, while tile 2048 is evaluated 2.
+ Sum of other faces { log(face) x 4 }
In here we still need to check for stacked values, but in a lesser way that doesn't interrupt the flexibility parameters, so we have the sum of { x in [4,44] }.
+ (Number of possible next moves x 256)
A state is more flexible if it has more freedom of possible transitions.
+ (Number of aligned values x 2)
This is a simplified check of the possibility of having merges within that state, without making a look-ahead.
Note: The constants can be tweaked..
If your close button is going to be text, this works very well for me:
#close {
position: fixed;
width: 70%; /* the width of the parent */
text-align: right;
}
#close span {
cursor: pointer;
}
Then your HTML
can just be:
<div id="close"><span id="x">X</span></div>
Here is how to build a function that returns a result set that can be queried as if it were a table:
SQL> create type emp_obj is object (empno number, ename varchar2(10));
2 /
Type created.
SQL> create type emp_tab is table of emp_obj;
2 /
Type created.
SQL> create or replace function all_emps return emp_tab
2 is
3 l_emp_tab emp_tab := emp_tab();
4 n integer := 0;
5 begin
6 for r in (select empno, ename from emp)
7 loop
8 l_emp_tab.extend;
9 n := n + 1;
10 l_emp_tab(n) := emp_obj(r.empno, r.ename);
11 end loop;
12 return l_emp_tab;
13 end;
14 /
Function created.
SQL> select * from table (all_emps);
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7902 FORD
7934 MILLER
You can hide an image using javascript like this:
document.images['imageName'].style.visibility = hidden;
If that isn't what you are after, you need to explain yourself more clearly.
You need to use some kind of file-transfer protocol (ftp, scp, etc), putty can't send remote files back to your computer. I use Win-SCP, which has a straightforward gui. Select SCP and you should be able to log in with the same ssh credentials and on the same port (probably 22) that you use with putty.
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild
using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
okay got it , you have to use ngAfterViewInit
method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit
will not throw any error because it will render after template loading
This adds the index as a dataframe column, drops duplicates on that, then removes the new column:
df = df.reset_index().drop_duplicates(subset='index', keep='last').set_index('index').sort_index()
Note that the use of .sort_index()
above at the end is as needed and is optional.
The F5 Refresh has the semantic of "please reload the current HTML AND its direct dependancies". Hence you should expect to see any imgs, css and js resource directly referenced by the HTML also being refetched. Of course a 304 is an acceptable response to this but F5 refresh implies that the browser will make the request rather than rely on fresh cache content.
Instead try simply navigating somewhere else and then navigating back.
You can force the refresh, past a 304, by holding ctrl while pressing f5 in most browsers.
The most reliable way to check for this is to check whether sys.prefix == sys.base_prefix
. If they are equal, you are not in a virtual environment; if they are unequal, you are. Inside a virtual environment, sys.prefix
points to the virtual environment, and sys.base_prefix
is the prefix of the system Python the virtualenv was created from.
The above always works for Python 3 stdlib venv
and for recent virtualenv
(since version 20). Older versions of virtualenv
used sys.real_prefix
instead of sys.base_prefix
(and sys.real_prefix
did not exist outside a virtual environment), and in Python 3.3 and earlier sys.base_prefix
did not ever exist. So a fully robust check that handles all of these cases could look like this:
import sys
def get_base_prefix_compat():
"""Get base/real prefix, or sys.prefix if there is none."""
return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix
def in_virtualenv():
return get_base_prefix_compat() != sys.prefix
If you only care about supported Python versions and latest virtualenv
, you can replace get_base_prefix_compat()
with simply sys.base_prefix
.
Using the VIRTUAL_ENV
environment variable is not reliable. It is set by the virtualenv activate
shell script, but a virtualenv can be used without activation by directly running an executable from the virtualenv's bin/
(or Scripts
) directory, in which case $VIRTUAL_ENV
will not be set. Or a non-virtualenv Python binary can be executed directly while a virtualenv is activated in the shell, in which case $VIRTUAL_ENV
may be set in a Python process that is not actually running in that virtualenv.
JavaScript btoa() function can be used to convert data into base64 encoded string
One can add rows to NULL
:
df<-NULL;
while(...){
#Some code that generates new row
rbind(df,row)->df
}
for instance
df<-NULL
for(e in 1:10) rbind(df,data.frame(x=e,square=e^2,even=factor(e%%2==0)))->df
print(df)
Use the ternary operator
direction == 1 ? dosomething () : dosomethingelse ();
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.