In your .htaccess you can add:
PHP 5.x
<IfModule mod_php5.c>
php_value memory_limit 64M
</IfModule>
PHP 7.x
<IfModule mod_php7.c>
php_value memory_limit 64M
</IfModule>
If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.
If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.
Read more on http://support.tigertech.net/php-value
Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS
variant or a LEFT JOIN
), but your query is perfectly legit.
Be aware of pitfalls with NOT IN
, though, when involving any NULL
values:
Variant with LEFT JOIN:
SELECT *
FROM friend f
LEFT JOIN likes l USING (id1, id2)
WHERE l.id1 IS NULL;
See @Michal's answer for the NOT EXISTS
variant.
A more detailed assessment of four basic variants:
In you app config file change the url
to localhost/example/public
Then when you want to link to something
<a href="{{ url('page') }}">Some Text</a>
without blade
<a href="<?php echo url('page') ?>">Some Text</a>
Do you need any other information except the date? If not:
SELECT DISTINCT start_date FROM table;
Just wanna update this for beginners now you should definitly use flexbox to do that, it's more appropriate and work for responsive try this : http://jsfiddle.net/x5vyC/3957/
#wrapper{
display:flex;
justify-content:space-between;
background:red;
}
#c1{
background:blue;
}
#c2{
background:green;
}
<div id="wrapper">
<div id="c1">con1</div>
<div id="c2">con2</div>
</div>?
This is how I solved this in ImpressPages:
//initial request with login data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name'); //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp'); //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
//another request preserving the session
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
This issue is happening because you have installed jre1.8.0_101-1.8.0_101-fcs.i58.rpm as well jdk-1.7.0_80-fcs.x86_64.rpm. so just uninstall your jre rpm & restart your application. It should work out.
Here is an easy way with String output (I created a method to do this):
public static String (String input){
String output = "";
try {
/* From ISO-8859-1 to UTF-8 */
output = new String(input.getBytes("ISO-8859-1"), "UTF-8");
/* From UTF-8 to ISO-8859-1 */
output = new String(input.getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return output;
}
// Example
input = "Música";
output = "Música";
To understand the difference between these you must understand the Gradient Descent Algorithm and its Variants.
Before I start with the actual answer, I would like to build some background.
A batch is the complete dataset. Its size is the total number of training examples in the available dataset.
Mini-batch size is the number of examples the learning algorithm processes in a single pass (forward and backward).
A Mini-batch is a small part of the dataset of given mini-batch size.
Iterations is the number of batches of data the algorithm has seen (or simply the number of passes the algorithm has done on the dataset).
Epochs is the number of times a learning algorithm sees the complete dataset. Now, this may not be equal to the number of iterations, as the dataset can also be processed in mini-batches, in essence, a single pass may process only a part of the dataset. In such cases, the number of iterations is not equal to the number of epochs.
In the case of Batch gradient descent, the whole batch is processed on each training pass. Therefore, the gradient descent optimizer results in smoother convergence than Mini-batch gradient descent, but it takes more time. The batch gradient descent is guaranteed to find an optimum if it exists.
Stochastic gradient descent is a special case of mini-batch gradient descent in which the mini-batch size is 1.
Use setDataAndType on the Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);
Use "video/mp4" as MIME or use "video/*" if you don't know the type.
The answer is simple. Just divide string by 1. Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
You could also set the default format for float :
pd.options.display.float_format = '{:.2%}'.format
Use '{:.2%}' instead of '{:.2f}%' - The former converts 0.41 to 41.00% (correctly), the latter to 0.41% (incorrectly)
Got it! Solved the issue modifying the user properties in security session of SQL Server. In SQL Server Management, go into security -> Logon -> Choose the user used for DB connection and go into his properties. Go to "Securators" tab and look for line "Connect SQL", mark "Grant" option and take a try. It works for me!
Regards
A fast-forward update is where the only changes one one side are after the most recent commit on the other side, so there doesn't need to be any merging. This is saying that you need to merge your changes before you can push.
To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.
Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:
SELECT @@VERSION
To get only the name of the directory where script executed:
//Path to script: /data/html/cars/index.php
echo basename(dirname(__FILE__)); //"cars"
You can locate it in the doc Block from bootstrap.min.css, at the top part.
Adding to what deceze said above. This is a parse error, so in order to debug a parse error, create a new file in the root named debugSyntax.php. Put this in it:
<?php
/////// SYNTAX ERROR CHECK ////////////
error_reporting(E_ALL);
ini_set('display_errors','On');
//replace "pageToTest.php" with the file path that you want to test.
include('pageToTest.php');
?>
Run the debugSyntax.php page and it will display parse errors from the page that you chose to test.
If you are using arrow functions:
it('should do something', async () => {
// do your testing
}).timeout(15000)
I would go like this (regex explained in comments):
import re
# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")
# <\/{0,}\[\d+>
#
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
# Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
# Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»
subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.
and there are many other lines in the txt files
with<[3> such tags </[3>"""
result = pattern.sub("", subject)
print(result)
If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.
You can use iter to process lines as soon as the command outputs them: lines = iter(fd.readline, "")
. Here's a full example showing a typical use case (thanks to @jfs for helping out):
from __future__ import print_function # Only Python 2.x
import subprocess
def execute(cmd):
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
for stdout_line in iter(popen.stdout.readline, ""):
yield stdout_line
popen.stdout.close()
return_code = popen.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, cmd)
# Example
for path in execute(["locate", "a"]):
print(path, end="")
In C++ you can declare a string like this:
#include <string>
using namespace std;
int main()
{
string str1("argue2000"); //define a string and Initialize str1 with "argue2000"
string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
string str3; //just declare a string, it has no value
return 1;
}
It's true that including the class in application-context.xml avoids the need to use getBean. However, even that is actually unnecessary. If you are writing a standalone application and you DON'T want to include your driver class in application-context.xml, you can use the following code to have Spring autowire the driver's dependencies:
public class AutowireThisDriver {
private MySpringBean mySpringBean;
public static void main(String[] args) {
AutowireThisDriver atd = new AutowireThisDriver(); //get instance
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"/WEB-INF/applicationContext.xml"); //get Spring context
//the magic: auto-wire the instance with all its dependencies:
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(atd,
AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
// code that uses mySpringBean ...
mySpringBean.doStuff() // no need to instantiate - thanks to Spring
}
public void setMySpringBean(MySpringBean bean) {
this.mySpringBean = bean;
}
}
I've needed to do this a couple of times when I have some sort of standalone class that needs to use some aspect of my app (eg for testing) but I don't want to include it in application-context because it is not actually part of the app. Note also that this avoids the need to look up the bean using a String name, which I've always thought was ugly.
Use the Moment.js library http://momentjs.com/ It will save you a LOT of trouble.
moment().format('DD-MMM-YYYY');
You can use command prompt to open explorer with path.
here example with batch or command prompt:
start "" explorer.exe (path)
so In VBA ms.access you can write with:
Dim Path
Path="C:\Example"
shell "cmd /c start """" explorer.exe " & Path ,vbHide
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
Build.IS_DEBUGGABLE could be all right. It comes from "ro.debuggable"
According to official documentation, the following command worked for me.
Link is here
I was trying to run by "react-native run-android" command. make sure to have react-native cli installed globally!
Are you referring to address validation? Like the previous answer by Mike, you need to cater for the othe 95%.
What you can do is when the user select's their country, then enable validation. Address validation and zipcode validation are 2 different things. Validating the ZIP is just making sure its integer. Address validation is validating the actual address for accuracy, preferably for mailing.
Using onclick
instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html
Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html
Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm
Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html
In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).
You could also do:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = DATE '2011-01-26'
The way i usually have my hierarchy of folder-
In this case, you could use life
to reference the parent object. Or you could store a reference to life
in the users object. There can't be a fixed parent
available to you in the language, because users is just a reference to an object, and there could be other references...
var death = { residents : life.users };
life.users.smallFurryCreaturesFromAlphaCentauri = { exist : function() {} };
// death.residents.smallFurryCreaturesFromAlphaCentauri now exists
// - because life.users references the same object as death.residents!
You might find it helpful to use something like this:
function addChild(ob, childName, childOb)
{
ob[childName] = childOb;
childOb.parent = ob;
}
var life= {
mameAndDestroy : function(group){ },
kiss : function(group){ }
};
addChild(life, 'users', {
guys : function(){ this.parent.mameAndDestroy(this.girls); },
girls : function(){ this.parent.kiss(this.boys); },
});
// life.users.parent now exists and points to life
Here is a Simple approach if you are using the AOSP library Volley
.
Extend the class Request<T>
as follows-
public class MultipartRequest extends Request<String> {
private static final String FILE_PART_NAME = "file";
private final Response.Listener<String> mListener;
private final Map<String, File> mFilePart;
private final Map<String, String> mStringPart;
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, Map<String, File> file,
Map<String, String> mStringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
this.mStringPart = mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
buildMultipartEntity();
}
public void addStringBody(String param, String value) {
mStringPart.put(param, value);
}
private void buildMultipartEntity() {
for (Map.Entry<String, File> entry : mFilePart.entrySet()) {
// entity.addPart(entry.getKey(), new FileBody(entry.getValue(), ContentType.create("image/jpeg"), entry.getKey()));
try {
entity.addBinaryBody(entry.getKey(), Utils.toByteArray(new FileInputStream(entry.getValue())), ContentType.create("image/jpeg"), entry.getKey() + ".JPG");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
}
@Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity = entity.build();
httpentity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
Log.d("Response", new String(response.data));
return Response.success(new String(response.data), getCacheEntry());
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
You can create and add a request like-
Map<String, String> params = new HashMap<>();
params.put("name", name.getText().toString());
params.put("email", email.getText().toString());
params.put("user_id", appPreferences.getInt( Utils.PROPERTY_USER_ID, -1) + "");
params.put("password", password.getText().toString());
params.put("imageName", pictureName);
Map<String, File> files = new HashMap<>();
files.put("photo", new File(Utils.LOCAL_RESOURCE_PATH + pictureName));
MultipartRequest multipartRequest = new MultipartRequest(Utils.BASE_URL + "editprofile/" + appPreferences.getInt(Utils.PROPERTY_USER_ID, -1), new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("Error: ", error.toString());
FugaDialog.showErrorDialog(ProfileActivity.this);
}
}, new Response.Listener<String>() {
@Override
public void onResponse(String jsonResponse) {
JSONObject response = null;
try {
Log.d("jsonResponse: ", jsonResponse);
response = new JSONObject(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (response != null && response.has("statusmessage") && response.getBoolean("statusmessage")) {
updateLocalRecord();
}
} catch (JSONException e) {
e.printStackTrace();
}
FugaDialog.dismiss();
}
}, files, params);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(multipartRequest);
Often when you need to show so many points on the map, you'd be better off using the server-side approach, this article explains when to use each:
Geocoding Strategies: https://developers.google.com/maps/articles/geocodestrat
The client-side limit is not exactly "10 requests per second", and since it's not explained in the API docs I wouldn't rely on its behavior.
Here is a working example in both Javascript and jQuery:
http://jsfiddle.net/GuLYN/312/
//In jQuery
$("#calculate").click(function() {
var num = parseFloat($("#textbox").val());
var new_num = $("#textbox").val(num.toFixed(2));
});
// In javascript
document.getElementById('calculate').onclick = function() {
var num = parseFloat(document.getElementById('textbox').value);
var new_num = num.toFixed(2);
document.getElementById('textbox').value = new_num;
};
?
Given a Date dt
you have several possibilities:
Solution 1: You can use the Calendar
class for that:
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
Solution 2: You should seriously consider using the Joda-Time library, because of the various shortcomings of the Date
class. With Joda-Time you can do the following:
Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);
Solution 3: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda-Time):
Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);
You should be able to use the "ours" merge strategy to overwrite master with seotweaks like this:
git checkout seotweaks
git merge -s ours master
git checkout master
git merge seotweaks
The result should be your master is now essentially seotweaks.
(-s ours
is short for --strategy=ours
)
From the docs about the 'ours' strategy:
This resolves any number of heads, but the resulting tree of the merge is always that of the current branch head, effectively ignoring all changes from all other branches. It is meant to be used to supersede old development history of side branches. Note that this is different from the -Xours option to the recursive merge strategy.
Update from comments: If you get fatal: refusing to merge unrelated histories
, then change the second line to this: git merge --allow-unrelated-histories -s ours master
Say the 1st date is in A1 cell
& the 2nd date is in B1 cell
Make sure that the cell type of both A1
& B1
is DATE
.
Then simply put the following formula in C1:
=A1-B1
The result of this formula may look funny to you.
Then Change the Cell type of C1
to GENERAL
.
It will give you the difference in Days.
You can also use this formula to get the remaining days of year or change the formula as you need:
=365-(A1-B1)
Partially. The text is inserted, but the warning is still generated.
I found a discussion that indicated the text needed to be preceded with 'E', as such:
insert into EscapeTest (text) values (E'This is the first part \n And this is the second');
This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.
As such:
insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
Thanks @twoleggedhorse.
Here is the solution.
First we created a function
CREATE FUNCTION GetAIntFromStoredProc(@parm Nvarchar(50)) RETURNS INTEGER
AS
BEGIN
DECLARE @id INTEGER
set @id= (select TOP(1) id From tbl where col=@parm)
RETURN @id
END
then we do the select query
Select col1, col2, col3,
GetAIntFromStoredProc(T.col1) As col4
From Tbl as T
Where col2=@parm
Adding the missing files(files in red color in Xcode->target->Build Phases->compiled sources) to the target folder resolved the issue for me.
$('li[rel=7]').siblings().andSelf();
// or:
$('li[rel=7]').parent().children();
Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:
var rels = [];
$('ul').each(function() {
var localRels = [];
$(this).find('li').each(function(){
localRels.push( $(this).attr('rel') );
});
rels.push(localRels);
});
It's to avoid a stack overflow. The Python interpreter limits the depths of recursion to help you avoid infinite recursions, resulting in stack overflows.
Try increasing the recursion limit (sys.setrecursionlimit
) or re-writing your code without recursion.
From the Python documentation:
sys.getrecursionlimit()
Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by
setrecursionlimit()
.
You can also use synchronized
keyword for addFinisher
method like this
//Implement the one method in the RaceListener interface
public synchronized void addFinisher(RaceCar finisher) {
finishingOrder.add(finisher);
}
So you can use ArrayList add method thread-safe with this way.
If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period
public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
AsyncTask<Params, Progress, Result> {
private static final int HTTP_REQUEST_TIMEOUT = 30000;
@Override
protected Result doInBackground(Params... params) {
createTimeoutListener();
return doInBackgroundImpl(params);
}
private void createTimeoutListener() {
Thread timeout = new Thread() {
public void run() {
Looper.prepare();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (AsyncTaskWithTimer.this != null
&& AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
AsyncTaskWithTimer.this.cancel(true);
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, HTTP_REQUEST_TIMEOUT);
Looper.loop();
}
};
timeout.start();
}
abstract protected Result doInBackgroundImpl(Params... params);
}
A Sample for this
public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {
@Override
protected void onCancelled(Void void) {
Log.d(TAG, "Async Task onCancelled With Result");
super.onCancelled(result);
}
@Override
protected void onCancelled() {
Log.d(TAG, "Async Task onCancelled");
super.onCancelled();
}
@Override
protected Void doInBackgroundImpl(Void... params) {
// Do background work
return null;
};
}
Old, but still helps...
Another great way of achieving the same behavior is through configuration file (web.config)
<system.net>
<settings>
<servicePointManager checkCertificateName="false" checkCertificateRevocationList="false" />
</settings>
</system.net>
NOTE: tested on .net full.
You are correct in that the entire transaction will be rolled back. You should issue the command to roll it back.
You can wrap this in a TRY CATCH
block as follows
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
COMMIT TRAN -- Transaction Success!
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN --RollBack in case of Error
-- you can Raise ERROR with RAISEERROR() Statement including the details of the exception
RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), 1)
END CATCH
You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = Bike.class, name = "bike"),
@Type(value = Auto.class, name = "auto"),
@Type(value = Car.class, name = "car")
})
public abstract class Vehicle {
// fields, constructors, getters, setters
}
Try this:
concat(left(datefield,10),left(timefield,8))
10 char on date field based on full date yyyy-MM-dd
.
8 char on time field based on full time hh:mm:ss
.
It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.
Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.
After trying to get this to work for too many hours, I finally found this: https://github.com/vierno/django-xhtml2pdf
It's a fork of https://github.com/chrisglass/django-xhtml2pdf that provides a mixin for a generic class-based view. I used it like this:
# views.py
from django_xhtml2pdf.views import PdfMixin
class GroupPDFGenerate(PdfMixin, DetailView):
model = PeerGroupSignIn
template_name = 'groups/pdf.html'
# templates/groups/pdf.html
<html>
<style>
@page { your xhtml2pdf pisa PDF parameters }
</style>
</head>
<body>
<div id="header_content"> (this is defined in the style section)
<h1>{{ peergroupsignin.this_group_title }}</h1>
...
Use the model name you defined in your view in all lowercase when populating the template fields. Because its a GCBV, you can just call it as '.as_view' in your urls.py:
# urls.py (using url namespaces defined in the main urls.py file)
url(
regex=r"^(?P<pk>\d+)/generate_pdf/$",
view=views.GroupPDFGenerate.as_view(),
name="generate_pdf",
),
Unix cp
doesn't 'support both directories and files':
betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).
To make cp copy a directory, you have to manually tell cp that it's a directory, by using the '-r' flag.
There is some disconnect here though - cp -r
when passed a filename as the source will happily copy just the single file; copytree won't.
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
Best method I found:
source activate old_env
conda env export > old_env.yml
Then process it with something like this:
with open('old_env.yml', 'r') as fin, open('new_env.yml', 'w') as fout:
for line in fin:
if 'py35' in line: # replace by the version you want to supersede
line = line[:line.rfind('=')] + '\n'
fout.write(line)
then edit manually the first (name: ...
) and last line (prefix: ...
) to reflect your new environment name and run:
conda env create -f new_env.yml
you might need to remove or change manually the version pin of a few packages for which which the pinned version from old_env
is found incompatible or missing for the new python version.
I wish there was a built-in, easier way...
For you to output foo {1, 2, 3}
you have to do something like:
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
To output a {
you use {{
and to output a }
you use }}
.
or Now, you can also use c# string interpolation like this (feature available in C# 6.0)
Escaping Brackets: String Interpolation $(""). it is new feature in C# 6.0
var inVal = "1, 2, 3";
var outVal = $" foo {{{inVal}}}";
//Output will be: foo {1, 2, 3}
Another way is to use this.
String path = "/abc/def/ghfj.doc"
String fileName = StringUtils.substringAfterLast(path, "/");
If you pass null to this method it will return null. If there is no match with separator it will return empty string.
You may be interested in the csv
module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.
import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]
for row in csv.reader( lines ):
...
Since Java 8 there is an easier way to transform:
import java.util.List;
import static java.util.stream.Collectors.toList;
public static <T> List<T> fromArray(T[] array) {
return Arrays.stream(array).collect(toList());
}
Sure:
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}
While size(A,2)
is correct, I find it's much more readable to first define
rows = @(x) size(x,1);
cols = @(x) size(x,2);
and then use, for example, like this:
howManyColumns_in_A = cols(A)
howManyRows_in_A = rows(A)
It might appear as a small saving, but size(.., 1)
and size(.., 2)
must be some of the most commonly used functions, and they are not optimally readable as-is.
The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:
input -> [1,2,[3,4]]
output -> [1,2,3,4]
The code below gives me the result, but I would like to know if anyone can create a simpler answer:
def get_elements_from_nested_list(l, new_l):
if l is not None:
e = l[0]
if isinstance(e, list):
get_elements_from_nested_list(e, new_l)
else:
new_l.append(e)
if len(l) > 1:
return get_elements_from_nested_list(l[1:], new_l)
else:
return new_l
l = [1,2,[3,4]]
new_l = []
get_elements_from_nested_list(l, new_l)
Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps
https://nominatim.openstreetmap.org/search?q=Mumbai&format=json
Here is the API documentation for reference.
Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.
docker save nginx > nginx.tar
tar -xvf nginx.tar
Following files are present:
https://sreeninet.wordpress.com/2016/06/11/looking-inside-container-images/
OR
you can use dive to view the image content interactively with TUI
@user1417684 and @chris-foster are right!
excerpt from working code (without error handling):
var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel = mongoose.model('items', ItemSchema);
var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {
var new_item = new ItemModel(new_item);
new_item.subitem = new_sub_item._id;
new_item.save(function (error, new_item) {
// so this is a valid way to populate via the Model
// as documented in comments above (here @stack overflow):
ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
callback(new_item.toObject());
});
// or populate directly on the result object
new_item.populate('subitem', function(error, new_item) {
callback(new_item.toObject());
});
});
});
A hash is an fixed sized integer that identifies a particular value. Each value needs to have its own hash, so for the same value you will get the same hash even if it's not the same object.
>>> hash("Look at me!")
4343814758193556824
>>> f = "Look at me!"
>>> hash(f)
4343814758193556824
Hash values need to be created in such a way that the resulting values are evenly distributed to reduce the number of hash collisions you get. Hash collisions are when two different values have the same hash. Therefore, relatively small changes often result in very different hashes.
>>> hash("Look at me!!")
6941904779894686356
These numbers are very useful, as they enable quick look-up of values in a large collection of values. Two examples of their use are Python's set
and dict
. In a list
, if you want to check if a value is in the list, with if x in values:
, Python needs to go through the whole list and compare x
with each value in the list values
. This can take a long time for a long list
. In a set
, Python keeps track of each hash, and when you type if x in values:
, Python will get the hash-value for x
, look that up in an internal structure and then only compare x
with the values that have the same hash as x
.
The same methodology is used for dictionary lookup. This makes lookup in set
and dict
very fast, while lookup in list
is slow. It also means you can have non-hashable objects in a list
, but not in a set
or as keys in a dict
. The typical example of non-hashable objects is any object that is mutable, meaning that you can change its value. If you have a mutable object it should not be hashable, as its hash then will change over its life-time, which would cause a lot of confusion, as an object could end up under the wrong hash value in a dictionary.
Note that the hash of a value only needs to be the same for one run of Python. In Python 3.3 they will in fact change for every new run of Python:
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
1849024199686380661
>>>
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
-7416743951976404299
This is to make is harder to guess what hash value a certain string will have, which is an important security feature for web applications etc.
Hash values should therefore not be stored permanently. If you need to use hash values in a permanent way you can take a look at the more "serious" types of hashes, cryptographic hash functions, that can be used for making verifiable checksums of files etc.
This way worked very well in my situation. I just added some modifications based on other code presented in this thread.
import sys, os
orig_stdout = sys.stdout # capture original state of stdout
te = open('log.txt','w') # File where you need to keep the logs
class Unbuffered:
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
te.write(data) # Write the data of stdout here to a text file as well
sys.stdout=Unbuffered(sys.stdout)
#######################################
## Feel free to use print function ##
#######################################
print("Here is an Example =)")
#######################################
## Feel free to use print function ##
#######################################
# Stop capturing printouts of the application from Windows CMD
sys.stdout = orig_stdout # put back the original state of stdout
te.flush() # forces python to write to file
te.close() # closes the log file
# read all lines at once and capture it to the variable named sys_prints
with open('log.txt', 'r+') as file:
sys_prints = file.readlines()
# erase the file contents of log file
open('log.txt', 'w').close()
Use JSON.stringify
with a custom replacer. For example:
// Demo: Circular reference
var circ = {};
circ.circ = circ;
// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(circ, (key, value) => {
if (typeof value === 'object' && value !== null) {
// Duplicate reference found, discard key
if (cache.includes(value)) return;
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null; // Enable garbage collection
The replacer in this example is not 100% correct (depending on your definition of "duplicate"). In the following case, a value is discarded:
var a = {b:1}
var o = {};
o.one = a;
o.two = a;
// one and two point to the same object, but two is discarded:
JSON.stringify(o, ...);
But the concept stands: Use a custom replacer, and keep track of the parsed object values.
As a utility function written in es6:
// safely handles circular references
JSON.safeStringify = (obj, indent = 2) => {
let cache = [];
const retVal = JSON.stringify(
obj,
(key, value) =>
typeof value === "object" && value !== null
? cache.includes(value)
? undefined // Duplicate reference found, discard key
: cache.push(value) && value // Store value in our collection
: value,
indent
);
cache = null;
return retVal;
};
// Example:
console.log('options', JSON.safeStringify(options))
If you want to keep the history, showing the commit and the revert, you should use:
git revert GIT_COMMIT_HASH
enter the message explaining why are you reverting and then:
git push
When you issue git log
you'll see both the "wrong" commit and revert log messages.
string s ="000000000100";
decimal iv = 0;
decimal.TryParse(s, out iv);
Console.WriteLine((iv / 100).ToString("0.00"));
The regexp in Hugo's answer is correct when there is no spaces in the line. In case if there are space regexp can be ^\s+$
In javascript the "+" operator is used to add numbers or to concatenate strings. if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"
Change 1000 to the number of milliseconds you want to delay.
just hoping to be helpful to someone as old problems seem to come back every now and again and I always find good tips here.
My problem was to list in a text file all the names of the "*.txt" files in a certain directory without path and without extension from a Datastage 7.5 sequence.
The solution we used is:
ls /home/user/new/*.txt | xargs -n 1 basename | cut -d '.' -f1 > name_list.txt
With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt
in the root of your project. Then from the root of your project:
mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make
And for Debug
(again from the root of your project):
mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
Release
/ Debug
will add the appropriate flags for your compiler. There are also RelWithDebInfo
and MinSizeRel
build configurations.
You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT
variables, e.g.:
set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")
See CMAKE_BUILD_TYPE for more details.
As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.
This will safely remove only if token is at end of string.
StringUtils.removeEnd(string, ".xml");
Apache StringUtils functions are null-, empty-, and no match- safe
this works fine, but file name does not display anymore.
$(document).ready(function(){ $("img.attach2").click(function(){ $("input.attach1").click(); return false; }); });
pip install tensorflow.tensorboard # install tensorboard
pip show tensorflow.tensorboard
# Location: c:\users\<name>\appdata\roaming\python\python35\site-packages
# now just run tensorboard as:
python c:\users\<name>\appdata\roaming\python\python35\site-packages\tensorboard\main.py --logdir=<logidr>
Try this, Add @ob_start()
function in top of the page,
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit();
}
Simply use this one:
select * from t1 where to_date(date_column)='8/3/2010'
What are the options to clone or copy a list in Python?
In Python 3, a shallow copy can be made with:
a_copy = a_list.copy()
In Python 2 and 3, you can get a shallow copy with a full slice of the original:
a_copy = a_list[:]
There are two semantic ways to copy a list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing new equivalent objects.
A shallow copy only copies the list itself, which is a container of references to the objects in the list. If the objects contained themselves are mutable and one is changed, the change will be reflected in both lists.
There are different ways to do this in Python 2 and 3. The Python 2 ways will also work in Python 3.
In Python 2, the idiomatic way of making a shallow copy of a list is with a complete slice of the original:
a_copy = a_list[:]
You can also accomplish the same thing by passing the list through the list constructor,
a_copy = list(a_list)
but using the constructor is less efficient:
>>> timeit
>>> l = range(20)
>>> min(timeit.repeat(lambda: l[:]))
0.30504298210144043
>>> min(timeit.repeat(lambda: list(l)))
0.40698814392089844
In Python 3, lists get the list.copy
method:
a_copy = a_list.copy()
In Python 3.5:
>>> import timeit
>>> l = list(range(20))
>>> min(timeit.repeat(lambda: l[:]))
0.38448613602668047
>>> min(timeit.repeat(lambda: list(l)))
0.6309100328944623
>>> min(timeit.repeat(lambda: l.copy()))
0.38122922903858125
Using new_list = my_list then modifies new_list every time my_list changes. Why is this?
my_list
is just a name that points to the actual list in memory. When you say new_list = my_list
you're not making a copy, you're just adding another name that points at that original list in memory. We can have similar issues when we make copies of lists.
>>> l = [[], [], []]
>>> l_copy = l[:]
>>> l_copy
[[], [], []]
>>> l_copy[0].append('foo')
>>> l_copy
[['foo'], [], []]
>>> l
[['foo'], [], []]
The list is just an array of pointers to the contents, so a shallow copy just copies the pointers, and so you have two different lists, but they have the same contents. To make copies of the contents, you need a deep copy.
To make a deep copy of a list, in Python 2 or 3, use deepcopy
in the copy
module:
import copy
a_deep_copy = copy.deepcopy(a_list)
To demonstrate how this allows us to make new sub-lists:
>>> import copy
>>> l
[['foo'], [], []]
>>> l_deep_copy = copy.deepcopy(l)
>>> l_deep_copy[0].pop()
'foo'
>>> l_deep_copy
[[], [], []]
>>> l
[['foo'], [], []]
And so we see that the deep copied list is an entirely different list from the original. You could roll your own function - but don't. You're likely to create bugs you otherwise wouldn't have by using the standard library's deepcopy function.
eval
You may see this used as a way to deepcopy, but don't do it:
problematic_deep_copy = eval(repr(a_list))
In 64 bit Python 2.7:
>>> import timeit
>>> import copy
>>> l = range(10)
>>> min(timeit.repeat(lambda: copy.deepcopy(l)))
27.55826997756958
>>> min(timeit.repeat(lambda: eval(repr(l))))
29.04534101486206
on 64 bit Python 3.5:
>>> import timeit
>>> import copy
>>> l = list(range(10))
>>> min(timeit.repeat(lambda: copy.deepcopy(l)))
16.84255409205798
>>> min(timeit.repeat(lambda: eval(repr(l))))
34.813894678023644
One classic root cause for this message is:
git init lis4368/assignments
),Ie, if you don't have added and committed at least once, there won't be a local master
branch to push to.
Try first to create a commit:
git add .
) then git commit -m "first commit"
git commit --allow-empty -m "Initial empty commit"
And then try git push -u origin master
again.
See "Why do I need to explicitly push a new branch?" for more.
A solution without reference to a Bean:
<h:button value="login"
outcome="content/configuration.xhtml?i=1" />
In my project I needed this approach:
<h:commandButton value="login"
action="content/configuration.xhtml?faces-redirect=true&i=1" />
For future visitors.
As of now Android 4.2.2 platform includes Google Play services. Just use an emulator running Jelly Bean. Details can be found here:
Setup Google Play Services SDK
EDIT:
Another option is to use Genymotion (runs way faster)
EDIT 2:
As @gdw2 commented: "setting up the Google Play Services SDK does not install a working Google Play app -- it just enables certain services provided by the SDK"
After version 2.0 Genymotion does not come with Play Services by default, but it can be easily installed manually. Just download the right version from here and drag and drop into the virtual device (emulador).
I figured it out!!! Of course I would right after I hit post!
I had the repo set to use the HTTPS url, I changed it to the SSH address, and everything resumed working flawlessly.
ROWS UNBOUNDED PRECEDING
is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY
it defines the window on which the result is calculated.
Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.
Starting and ending rows might be fixed or relative to the current row based on the following keywords:
Possible kinds of calculation include:
So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING)
results in a Cumulative Sum or Running Total
11 -> 11
2 -> 11 + 2 = 13
3 -> 13 + 3 (or 11+2+3) = 16
44 -> 16 + 44 (or 11+2+3+44) = 60
Assuming SQL Server:
e.g. if you class special characters as anything NOT alphanumeric:
DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
Just add to other characters you don't class as special, inside the square brackets
Enable mod_headers in Apache2 to be able to use Header directive :
a2enmod headers
Looping through the array and inserting a key, value pair is about your best solution. You could use the 'map' function but it is just a matter of preference.
var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
arrOfObj.map(function (obj) {
obj.isActive = true;
});
To retrieve your image from byte to base64 string....
Model property:
public byte[] NomineePhoto { get; set; }
public string NomineePhoneInBase64Str
{
get {
if (NomineePhoto == null)
return "";
return $"data:image/png;base64,{Convert.ToBase64String(NomineePhoto)}";
}
}
IN view:
<img style="height:50px;width:50px" src="@item.NomineePhoneInBase64Str" />
You probably want kbhit();
//Example will loop until a key is pressed
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
while(1)
{
if(kbhit())
{
break;
}
}
}
this may not work on all environments. A portable way would be to create a monitoring thread and set some flag on getch();
And why not to use this ?
SELECT model, date FROM doc ORDER BY date DESC LIMIT 1
Add a given line at the beginning of a file in two commands:
cat <(echo "blablabla") input_file.txt > tmp_file.txt
mv tmp_file.txt input_file.txt
According to Collections Framework Overview you have two balanced tree implementations:
Another easy way to achieve this is to perform a fade using AlphaAnimation.
change your method to:
$scope.toggleChecked = function (index) {
$scope.checked.push($scope.items[index]);
$scope.items.splice(index, 1);
};
How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in
operator (or in your specific case, not in
). As mentioned in the documentation,
The operators
in
andnot in
test for membership.x in s
evaluates toTrue
ifx
is a member ofs
, andFalse
otherwise.x not in s
returns the negation ofx in s
.
Additionally,
The operator
not in
is defined to have the inverse true value ofin
.
y not in x
is logically the same as not y in x
.
Here are a few examples:
'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):
(1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS defines a __contains__()
method, in
will internally call it, as noted in the last paragraph of the Comparisons section of the docs.
...
in
andnot in
, are supported by types that are iterable or implement the__contains__()
method. For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in
short-circuits, so if your element is at the start of the list, in
evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options:
list.index
can be used to retrieve the index of an item. If that element does not exist, a ValueError
is raised.list.count
can be used if you want to count the occurrences.set
s?Ask yourself these questions:
hash
on them?If you answered "yes" to these questions, you should be using a set
instead. An in
membership test on list
s is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.
set
objects, on the other hand, hash their values for constant time membership check. The check is also done using in
:
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:
l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__
.
I had a similar problem. I was attempting to have a file written every time a user visits a website.
The problem ended up being twofold.
1: the permissions were not set correctly
2: I attempted to use
f = open(r"newfile.txt","w+")
(Wrong)
After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+")
(Right)
Your .gitignore file should look like this:
# Ignore Mac DS_Store files
.DS_Store
As long as you don't include a slash, it is matched against the file name in all directories. (from here)
wrap button inside <div class="text-xs-center">
<div class="text-xs-center">
<v-btn primary>
Signup
</v-btn>
</div>
Dev uses it in his examples.
For centering buttons in v-card-actions
we can add class="justify-center"
(note in v2 class is text-center
(so without xs
):
<v-card-actions class="justify-center">
<v-btn>
Signup
</v-btn>
</v-card-actions>
For more examples with regards to centering see here
For all the RxJava or RxAndroid or RxKotlin lovers out there
Observable.just(db)
.subscribeOn(Schedulers.io())
.subscribe { db -> // database operation }
The delete / drop option in operations is not present in my version.
Go to CPanel -> MySQLDatabase (icon next to PhPMyAdmin) -> check the DB to be delete -> delete.
Make's substitutions feature is nice and helped me to write
%.i: src/%.c $(INCLUDE)
gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@
You might find this useful, because it asks make
to check for changes in include folders too
If you are using MySQL there is the DATEDIFF function which calculate the days between two dates:
SELECT dtCreated
, bActive
, dtLastPaymentAttempt
, dtLastUpdated
, dtLastVisit
, DATEDIFF(dtLastUpdated, dtCreated) as Difference
FROM Customers
WHERE (bActive = 'true')
AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))
I believe in order to have auto-wiring work on your MyLauncher class (for myService), you will need to let Spring initialize it instead of calling the constructor, by auto-wiring myLauncher. Once that is being auto-wired (and myService is also getting auto-wired), Spring (1.4.0 and up) provides a @MockBean annotation you can put in your test. This will replace a matching single beans in context with a mock of that type. You can then further define what mocking you want, in a @Before method.
public class MyLauncherTest
@MockBean
private MyService myService;
@Autowired
private MyLauncher myLauncher;
@Before
private void setupMockBean() {
doNothing().when(myService).someVoidMethod();
doReturn("Some Value").when(myService).someStringMethod();
}
@Test
public void someTest() {
myLauncher.doSomething();
}
}
Your MyLauncher class can then remain unmodified, and your MyService bean will be a mock whose methods return values as you defined:
@Component
public class MyLauncher {
@Autowired
MyService myService;
public void doSomething() {
myService.someVoidMethod();
myService.someMethodThatCallsSomeStringMethod();
}
//other methods
}
A couple advantages of this over other methods mentioned is that:
You can use sdp size unit instead of dp size unit. The sdp size unit is relative to the screen size and therefor is often preferred for targeting multiple screen sizes.
Use it carefully! for example, in most cases you still need to design a different layout for tablets.
The "good node.js /event driven" way of doing this is to not wait.
Like almost everything else when working with event driven systems like node, your function should accept a callback parameter that will be invoked when then computation is complete. The caller should not wait for the value to be "returned" in the normal sense, but rather send the routine that will handle the resulting value:
function(query, callback) {
myApi.exec('SomeCommand', function(response) {
// other stuff here...
// bla bla..
callback(response); // this will "return" your value to the original caller
});
}
So you dont use it like this:
var returnValue = myFunction(query);
But like this:
myFunction(query, function(returnValue) {
// use the return value here instead of like a regular (non-evented) return value
});
With Guava, you can use Iterables.concat(Iterable<T> ...)
, it creates a live view of all the iterables, concatenated into one (if you change the iterables, the concatenated version also changes). Then wrap the concatenated iterable with Iterables.unmodifiableIterable(Iterable<T>)
(I hadn't seen the read-only requirement earlier).
From the Iterables.concat( .. )
JavaDocs:
Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in inputs. The input iterators are not polled until necessary. The returned iterable's iterator supports
remove()
when the corresponding input iterator supports it.
While this doesn't explicitly say that this is a live view, the last sentence implies that it is (supporting the Iterator.remove()
method only if the backing iterator supports it is not possible unless using a live view)
Sample Code:
final List<Integer> first = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 5, 6);
final List<Integer> third = Lists.newArrayList(7, 8, 9);
final Iterable<Integer> all =
Iterables.unmodifiableIterable(
Iterables.concat(first, second, third));
System.out.println(all);
third.add(9999999);
System.out.println(all);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9999999]
Edit:
By Request from Damian, here's a similar method that returns a live Collection View
public final class CollectionsX {
static class JoinedCollectionView<E> implements Collection<E> {
private final Collection<? extends E>[] items;
public JoinedCollectionView(final Collection<? extends E>[] items) {
this.items = items;
}
@Override
public boolean addAll(final Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
for (final Collection<? extends E> coll : items) {
coll.clear();
}
}
@Override
public boolean contains(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
@Override
public Iterator<E> iterator() {
return Iterables.concat(items).iterator();
}
@Override
public boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
int ct = 0;
for (final Collection<? extends E> coll : items) {
ct += coll.size();
}
return ct;
}
@Override
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(E e) {
throw new UnsupportedOperationException();
}
}
/**
* Returns a live aggregated collection view of the collections passed in.
* <p>
* All methods except {@link Collection#size()}, {@link Collection#clear()},
* {@link Collection#isEmpty()} and {@link Iterable#iterator()}
* throw {@link UnsupportedOperationException} in the returned Collection.
* <p>
* None of the above methods is thread safe (nor would there be an easy way
* of making them).
*/
public static <T> Collection<T> combine(
final Collection<? extends T>... items) {
return new JoinedCollectionView<T>(items);
}
private CollectionsX() {
}
}
A union query can only have one master ORDER BY
clause, IIRC. To get this, in each query making up the greater UNION
query, add a field that will be the one field you sort by for the UNION
's ORDER BY
.
For instance, you might have something like
SELECT field1, field2, '1' AS union_sort
UNION SELECT field1, field2, '2' AS union_sort
UNION SELECT field1, field2, '3' AS union_sort
ORDER BY union_sort
That union_sort
field can be anything you may want to sort by. In this example, it just happens to put results from the first table first, second table second, etc.
Short answer: No. Use WebM or Ogg instead.
This article covers just about everything you need to know about the <video>
element, including which browsers support which container formats and codecs.
This can be done in one line, there's no need for a loop, be it a for-loop or an apply. Use unlist() instead :
# testdata
Df <- data.frame(
x = as.factor(sample(1:5,30,r=TRUE)),
y = as.factor(sample(1:5,30,r=TRUE)),
z = as.factor(sample(1:5,30,r=TRUE)),
w = as.factor(sample(1:5,30,r=TRUE))
)
##
Df[,c("y","w")] <- as.numeric(as.character(unlist(Df[,c("y","w")])))
str(Df)
Edit : for your code, this becomes :
id <- c(1,3:ncol(stats)))
stats[,id] <- as.numeric(as.character(unlist(stats[,id])))
Obviously, if you have a one-column data frame and you don't want the automatic dimension reduction of R to convert it to a vector, you'll have to add the drop=FALSE
argument.
This answer extends on Jayson's excellent answer with some more opinionated guidance on the best approach for your use case:
Managing versions manually is probably the worst option. If you decide to manually switch versions, you can use this Bash code instead of Jayson's verbose code (code snippet from the homebrew-openjdk README:
jdk() {
version=$1
export JAVA_HOME=$(/usr/libexec/java_home -v"$version");
java -version
}
Jayson's answer provides the basic commands for SDKMAN and jenv. Here's more info on SDKMAN and more info on jenv if you'd like more background on these tools.
Fundamentally if you use it as part of a business then its commercial use - so its not a matter of whether the tools are directly generating income or not rather one of if they are being used in support of income generation directly or indirectly.
To take your specific example, if the purpose of the site is to sell or promote your paid services/product then its a commercial enterprise.
None of the above worked for me using JQM 1.2.0
This did work for me:
.ui-page.ui-body-c {
background: url(bg.png);
background-repeat:no-repeat;
background-position:center center;
background-size:cover;
}
int64
(from numpy) to int
.For example, if variable x
is a int64:
int(x)
If is array of int64:
map(int, x)
you will need to specify which branch and which remote when pushing:
? git init ./
? git add Readme.md
? git commit -m "Initial Commit"
? git remote add github <project url>
? git push github master
Will work as expected.
You can set this up by default by doing:
? git branch -u github/master master
which will allow you to do a git push
from master without specifying the remote or branch.
To make this easier to use, I wrote a generic extension:
public static string ToDescription<TEnum>(this TEnum EnumValue) where TEnum : struct
{
return Enumerations.GetEnumDescription((Enum)(object)((TEnum)EnumValue));
}
now I can write:
MyEnum my = MyEnum.HereIsAnother;
string description = my.ToDescription();
System.Diagnostics.Debug.Print(description);
Note: replace "Enumerations" above with your class name
You did it the wrong way around. You are meant to reset first, to unstage the file, then checkout, to revert local changes.
Try this:
$ git reset foo/bar.txt
$ git checkout foo/bar.txt
In Ruby, the Hash#select is a right option. If you work with Rails, you can use Hash#slice and Hash#slice!. e.g. (rails 3.2.13)
h1 = {:a => 1, :b => 2, :c => 3, :d => 4}
h1.slice(:a, :b) # return {:a=>1, :b=>2}, but h1 is not changed
h2 = h1.slice!(:a, :b) # h1 = {:a=>1, :b=>2}, h2 = {:c => 3, :d => 4}
You are not allowed to have a CNAME record for the domain, as the CNAME is an aliasing feature that covers all data types (regardless of whether the client looks for MX, NS or SOA records). CNAMEs also always refer to a new name, not an ip-address, so there are actually two errors in the single line
@ IN CNAME 88.198.38.XXX
Changing that CNAME to an A record should make it work, provided the ip-address you use is the correct one for your Heroku app.
The only correct way in DNS to make a simple domain.com
name work in the browser, is to point the domain to an IP-adress with an A record.
As others said, libreoffice
can convert xls files to csv. The problem for me was the sheet selection.
This libreoffice Python script does a fine job at converting a single sheet to CSV.
Usage is:
./libreconverter.py File.xls:"Sheet Name" output.csv
The only downside (on my end) is that --headless
doesn't seem to work. I have a LO window that shows up for a second and then quits.
That's OK with me, it's the only tool that does the job rapidly.
BLOB
primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB
intended to retain character-based data.
Try this or purpose will solve with lesser no of steps
for (int i = 0; i < a.length; i++)
{
for (int k = i+1; k < a.length; k++)
{
if (a[i] != a[k])
{
System.out.println(a[i]+"not the same with"+a[k]+"\n");
}
}
}
In Kibana 6.5, you can generate CSV under the Share Tab -> CSV Reports.
The request will be queued. Once the CSV is generated, it will be available for download under Management -> Reporting
In DOS you couldn't use environment variables on the command line, only in batch files, where they used the %
sign as a delimiter. If you wanted a literal %
sign in a batch file, e.g. in an echo
statement, you needed to double it.
This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your %
signs in a .cmd file.
A little OOC code to add:
#include <stdio.h>
struct Node {
int somevar;
};
void print() {
printf("Hello from an object-oriented C method!");
};
struct Tree {
struct Node * NIL;
void (*FPprint)(void);
struct Node *root;
struct Node NIL_t;
} TreeA = {&TreeA.NIL_t,print};
int main()
{
struct Tree TreeB;
TreeB = TreeA;
TreeB.FPprint();
return 0;
}
I use a library called ExcelDataReader, you can find it on NuGet. Be sure to install both ExcelDataReader and the ExcelDataReader.DataSet extension (the latter provides the required AsDataSet method referenced below).
I encapsulated everything in one function, you can copy it in your code directly. Give it a path to CSV file, it gets you a dataset with one table.
public static DataSet GetDataSet(string filepath)
{
var stream = File.OpenRead(filepath);
try
{
var reader = ExcelReaderFactory.CreateCsvReader(stream, new ExcelReaderConfiguration()
{
LeaveOpen = false
});
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
// Gets or sets a value indicating whether to set the DataColumn.DataType
// property in a second pass.
UseColumnDataType = true,
// Gets or sets a callback to determine whether to include the current sheet
// in the DataSet. Called once per sheet before ConfigureDataTable.
FilterSheet = (tableReader, sheetIndex) => true,
// Gets or sets a callback to obtain configuration options for a DataTable.
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
// Gets or sets a value indicating the prefix of generated column names.
EmptyColumnNamePrefix = "Column",
// Gets or sets a value indicating whether to use a row from the
// data as column names.
UseHeaderRow = true,
// Gets or sets a callback to determine which row is the header row.
// Only called when UseHeaderRow = true.
ReadHeaderRow = (rowReader) =>
{
// F.ex skip the first row and use the 2nd row as column headers:
//rowReader.Read();
},
// Gets or sets a callback to determine whether to include the
// current row in the DataTable.
FilterRow = (rowReader) =>
{
return true;
},
// Gets or sets a callback to determine whether to include the specific
// column in the DataTable. Called once per column after reading the
// headers.
FilterColumn = (rowReader, columnIndex) =>
{
return true;
}
}
});
return result;
}
catch (Exception ex)
{
return null;
}
finally
{
stream.Close();
stream.Dispose();
}
}
I have no idea how it can work automatically, but you can copy "], " together with new line and then use replace function.
chmod u+x program_name
. Then execute it.
If that does not work, copy the program from the USB device to a native volume on the system. Then chmod u+x program_name
on the local copy and execute that.
Unix and Unix-like systems generally will not execute a program unless it is marked with permission to execute. The way you copied the file from one system to another (or mounted an external volume) may have turned off execute permission (as a safety feature). The command chmod u+x name
adds permission for the user that owns the file to execute it.
That command only changes the permissions associated with the file; it does not change the security controls associated with the entire volume. If it is security controls on the volume that are interfering with execution (for example, a noexec
option may be specified for a volume in the Unix fstab
file, which says not to allow execute permission for files on the volume), then you can remount the volume with options to allow execution. However, copying the file to a local volume may be a quicker and easier solution.
For anyone still looking for an answer that works on both Linux and Windows:
Add this to the scripts
section in package.json
"build": "react-scripts build && mv build ../docs || move build ../docs",
with ../docs
is the relative folder you want to move the build folder to
The homebrew package for node.js now includes npm again, so this happened to me when I missed the homebrew package's message about removing the standalone version first.
Assuming, like me, you've already broken node/npm by attempting the upgrade before knowing to npm uninstall npm -g
first, you can rm -rf /usr/local/lib/node_modules/npm
and then brew link node
. This removes the standalone self-hosted npm package (rather than the one brew would like to install) and lets brew symlink its bundled one from Cellar.
You can simple read this way .
List<string> lines = System.IO.File.ReadLines(completePath).ToList();
public class FindDigitFromString
{
public static void main(String[] args)
{
String s=" Hi How Are You 11 ";
String s1=s.replaceAll("[^0-9]+", "");
//*replacing all the value of string except digit by using "[^0-9]+" regex.*
System.out.println(s1);
}
}
Output: 11
This is because you're using getActivity()
inside an inner class. Try using:
SherlockFragmentActivity.this.getActivity()
instead, though there's really no need for the getActivity()
part. In your case,
SherlockFragmentActivity .this
should suffice.
2 great ways to ADD:
But the first way is more cleaner, since for the second you have to add a space at the beginning. This is to avoid the class name from joining with the previous class.
element.classList.add("d-flex", "align-items-center");
element.className += " d-flex align-items-center";
Then to REMOVE use the cleaner way, by use of classList
element.classList.remove("d-grid", "bg-danger");
lines
is a list. re.findall()
doesn't take lists.
>>> import re
>>> f = open('README.md', 'r')
>>> lines = f.readlines()
>>> match = re.findall('[A-Z]+', lines)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 177, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer
>>> type(lines)
<type 'list'>
From help(file.readlines)
. I.e. readlines()
is for loops/iterating:
readlines(...)
readlines([size]) -> list of strings, each a line from the file.
To find all uppercase characters in your file:
>>> import re
>>> re.findall('[A-Z]+', open('README.md', 'r').read())
['S', 'E', 'A', 'P', 'S', 'I', 'R', 'C', 'I', 'A', 'P', 'O', 'G', 'P', 'P', 'T', 'V', 'W', 'V', 'D', 'A', 'L', 'U', 'O', 'I', 'L', 'P', 'A', 'D', 'V', 'S', 'M', 'S', 'L', 'I', 'D', 'V', 'S', 'M', 'A', 'P', 'T', 'P', 'Y', 'C', 'M', 'V', 'Y', 'C', 'M', 'R', 'R', 'B', 'P', 'M', 'L', 'F', 'D', 'W', 'V', 'C', 'X', 'S']
If you have epoch in milliseconds a possible solution is convert to seconds:
import time
time.ctime(milliseconds/1000)
For more time
functions: https://docs.python.org/3/library/time.html#functions
Concept:
To be very simple Type Safe like the meanings, it makes sure that type of the variable should be safe like
so it is all about the safety of the types of your storage in terms of variables.
I got same problem lot of time. Check your request url, if you are requesting on local server like 127.1.1/api or 192.168...., try to change it, make sure you are hitting cloud.
THE CORRECT WAY IS :
UPDATE test1
INNER JOIN test2 ON (test1.id = test2.id)
SET test1.data = test2.data
I had that problem, but it was because my images changed them manually from .JPG to .PNG, so I just changed them with PNG paint and solved the problem
require
loads a file from the $LOAD_PATH
. If you want to require a file relative to the currently executing file instead of from the $LOAD_PATH
, use require_relative
.
it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...)
That's not correct, and you will be unable to cite an authoriitative source for that claim. It should be changed whenever you make a change that is incompatible under the rules given in the Versioning of Serializable Objects section of the Object Serialization Specification, which specifically does not include additional fields or change of field order, and when you haven't provided readObject(), writeObject(),
and/or readResolve()
or /writeReplace()
methods and/or a serializableFields
declaration that could cope with the change.
I just had a similar situation and was looking for a solution that allows me to return an alternative default value without taking care of it at the caller side every time I need it. What we usually do in case Linq does not support what we want, is to write a new extension that takes care of it. That´s what I did. Here is what I came up with (not tested though):
public static class EnumerableExtensions
{
public static T FirstOrDefault<T>(this IEnumerable<T> items, T defaultValue)
{
foreach (var item in items)
{
return item;
}
return defaultValue;
}
public static T FirstOrDefault<T>(this IEnumerable<T> items, Func<T, bool> predicate, T defaultValue)
{
return items.Where(predicate).FirstOrDefault(defaultValue);
}
public static T LastOrDefault<T>(this IEnumerable<T> items, T defaultValue)
{
return items.Reverse().FirstOrDefault(defaultValue);
}
public static T LastOrDefault<T>(this IEnumerable<T> items, Func<T, bool> predicate, T defaultValue)
{
return items.Where(predicate).LastOrDefault(defaultValue);
}
}
This was occuring for me and it is such an easy fix.
if you have installed the correct software and it still occurs than goto
control panel
→ system
→ advanced system settings
for Windows 8 or
control panel
→ system and security
→ system
→ advanced system settings
for Windows 10.
<system variables>
_JAVA_OPTIONS
Variable Value: -Xmx512M
At least that is what worked for me.
Resize the image to fit the div size.
With CSS3 you can do this:
/* with CSS 3 */
#yourdiv {
background: url('bgimage.jpg') no-repeat;
background-size: 100%;
}
How Do you Stretch a Background Image in a Web Page:
About opacity
#yourdiv {
opacity: 0.4;
filter: alpha(opacity=40); /* For IE8 and earlier */
}
Or look at CSS Image Opacity / Transparency
In Kotlin you can do this:
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setTitle(R.string.title)
}
override fun onSupportNavigateUp() = true.also { onBackPressed() }
}
PUT => Set all new attributes for an existing resource.
PATCH => Partially update an existing resource (not all attributes required).
I know that some may want to smack me for re-opening old post, but if you feel so do it I just hope this may help someone else trying to set JDK 7 on Mac OS (using IntelliJ).
What I did to get this working on my machine is to:
try putting a delay on the last color fade.
$("p#44.test").delay(3000).css("background-color","red");
What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!
Drag and drop a Python file in the Ipython notebooks "home" notebooks table, click upload. This will create a new notebook with only one cell containing your .py file content
Else copy/paste from your favorite editor ;)
Another important fact is that reject()
DOES NOT terminate control flow like a return
statement does. In contrast throw
does terminate control flow.
Example:
new Promise((resolve, reject) => {_x000D_
throw "err";_x000D_
console.log("NEVER REACHED");_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
vs
new Promise((resolve, reject) => {_x000D_
reject(); // resolve() behaves similarly_x000D_
console.log("ALWAYS REACHED"); // "REJECTED" will print AFTER this_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
Just by looking at the image from the help pages, it makes a lot of sense.
So you have the blue boxes compileClasspath
and runtimeClassPath
.
The compileClasspath
is what is required to make a successful build when running gradle build
. The libraries that will be present on the classpath when compiling will be all libraries that are configured in your gradle build using either compileOnly
or implementation
.
Then we have the runtimeClasspath
and those are all packages that you added using either implementation
or runtimeOnly
. All those libraries will be added to the final build file (jar) that you deploy on the server.
As you also see in the image, if you want a library to be both used for compilation but you also want it added to the build file, then implementation
should be used.
An example of runtimeOnly
can be a database driver.
An example of compileOnly
can be servlet-api.
An example of implementation
can be spring-core.
If you want to jump directly to the desired position in a listView just use
listView.setSelection(int position);
and if you want to jump smoothly to the desired position in listView just use
listView.smoothScrollToPosition(int position);
Here is complete library with the widget: https://github.com/opprime/EditTextField
To use it you should add the dependency:
compile 'com.optimus:editTextField:0.2.0'
In the layout.xml file you can play with the widget settings:
xmlns:app="http://schemas.android.com/apk/res-auto"
app:clearButtonMode,can has such values: never always whileEditing unlessEditing
app:clearButtonDrawable
Sample in action:
In format function your can use timestamp_format function. Example, if the format is YYYYMMDD you can do it :
select TIMESTAMP_FORMAT(yourcolumnchar, 'YYYYMMDD') as YouTimeStamp
from yourtable
you can then adapt then format with elements format foundable here
// stringValue can be anything in which present any number
`const stringValue = 'last_15_days';
// /\d+/g is regex which is used for matching number in string
// match helps to find result according to regex from string and return match value
const result = stringValue.match(/\d+/g);
console.log(result);`
output will be 15
If You want to learn more about regex here are some links:
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm
Very Simple using jQuery... To check that selected element is type of input
$(".elementClass").is('input')
To check that selected element is type of textarea
$(".elementClass").is('textarea')
To check that selected element is type of Radio
$(".elementClass").is('input[type="radio"]')
To check that selected element is type of Checkbox
$(".elementClass").is('input[type="checkbox"]')
To check that selected element is type of Input type number
$(".elementClass").is('input[type="number"]')
To check that selected element is type of Input type password
$(".elementClass").is('input[type="password"]')
To check that selected element is type of Input type email
$(".elementClass").is('input[type="email"]')
.....
...
So Basically you can change selection and type to determine required input type
In the case you have no natural partition value and just want an ordered number regardless of the partition you can just do a row_number over a constant, in the following example i've just used 'X'. Hope this helps someone
select
ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1,
period_next_id, period_name_long
from
(
select distinct col1, period_name_long, 'X' as num
from {TABLE}
) as x
The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.
When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.
You can push data from the server to the browser via Server Side Events. This is essentially a unidirectional stream that a client can "subscribe" to from a browser. From here, you could just create new Notification
objects as SSEs stream into the browser:
var source = new EventSource('/events');
source.on('message', message => {
var notification = new Notification(message.title, {
body: message.body
});
});
A bit old, but this article by Eric Bidelman explains the basics of SSE and provides some server code examples as well.
Because you have multiple versions of NumPy installed.
Try pip uninstall numpy
and pip list | grep numpy
several times, until you see no output from pip list | grep numpy
.
Then pip install numpy
will get you the newest version of NumPy.
Let's say I have an array arr. When would the following not give the number of elements of the array:
sizeof(arr) / sizeof(arr[0])
?
In contexts where arr
is not actually the array (but instead a pointer to the initial element). Other answers explain how this happens.
I can thing of only one case: the array contains elements that are of different derived types of the type of the array.
This cannot happen (for, fundamentally, the same reason that Java arrays don't play nicely with generics). The array is statically typed; it reserves "slots" of memory that are sized for a specific type (the base type).
Sorry for the trivial question, I am a Java dev and I am rather new to C++.
C++ arrays are not first-class objects. You can use boost::array to make them behave more like Java arrays, but keep in mind that you will still have value semantics rather than reference semantics, just like with everything else. (In particular, this means that you cannot really declare a variable of type analogous to Foo[]
in Java, nor replace an array with another one of a different size; the array size is a part of the type.) Use .size()
with this class where you would use .length
in Java. (It also supplies iterators that provide the usual interface for C++ iterators.)
With the modification of a single line you could alter the fullcalendar.js script to allow a line break and put multiple information on the same line.
In FullCalendar.js on line ~3922 find htmlEscape(s) function and add .replace(/<br\s?/?>/g, '
') to the end of it.
function htmlEscape(s) {
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/\n/g, '<br />')
.replace(/<br\s?\/?>/g, '<br />');
}
This will allow you to have multiple lines for the title, separating the information. Example replace the event.title with title: 'All Day Event' + '<br />' + 'Other Description'
Answering only the first part. What is it?
Inversion of Control (IoC) means to create instances of dependencies first and latter instance of a class (optionally injecting them through constructor), instead of creating an instance of the class first and then the class instance creating instances of dependencies. Thus, inversion of control inverts the flow of control of the program. Instead of the callee controlling the flow of control (while creating dependencies), the caller controls the flow of control of the program.
Complementing rijul gupta answer:
String strSDCardPath = System.getenv("SECONDARY_STORAGE");
if ((strSDCardPath == null) || (strSDCardPath.length() == 0)) {
strSDCardPath = System.getenv("EXTERNAL_SDCARD_STORAGE");
}
//If may get a full path that is not the right one, even if we don't have the SD Card there.
//We just need the "/mnt/extSdCard/" i.e and check if it's writable
if(strSDCardPath != null) {
if (strSDCardPath.contains(":")) {
strSDCardPath = strSDCardPath.substring(0, strSDCardPath.indexOf(":"));
}
File externalFilePath = new File(strSDCardPath);
if (externalFilePath.exists() && externalFilePath.canWrite()){
//do what you need here
}
}
Maybe use atribute disabled:
<input disabled="disabled" id="fieldName" name="fieldName" type="text" class="text_box" />
Or just use label tag: ;)
<label>
set_include_path(get_include_path() . $_SERVER["DOCUMENT_ROOT"] . "/mysite/php/includes/");
Also this can help.See set_include_path()
You can place a text-box to the report and add an expression with the following value in it:
="Report generation date: " & Format(Globals!ExecutionTime,"dd/MM/yyyy h:mm:ss tt" )
zfill
.This function takes x
and converts it to a string, and adds zeros in the beginning only and only if the length is too short:
def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))<len else str(x) )
To sum it up - build-in: zfill
is good enough, but if someone is curious on how to implement this by hand, here is one more example.
A couple of things for ya:
The loading would be "better" like this:
with file('morsecodes.txt', 'rt') as f:
for line in f:
line = line.strip()
if len(line) > 0:
# do your stuff to parse the file
That way you don't need to close, and you don't need to manually load each line, etc., etc.
for letter in userInput:
if ValidateLetter(letter): # you need to define this
code = GetMorseCode(letter) # from my other answer
# do whatever you want
I wrote this one today while trying to recreate _.sortBy
in TypeScript, and thought I would leave it for anyone in need.
// ** Credits for getKeyValue at the bottom **
export const getKeyValue = <T extends {}, U extends keyof T>(key: U) => (obj: T) => obj[key]
export const sortBy = <T extends {}>(index: string, list: T[]): T[] => {
return list.sort((a, b): number => {
const _a = getKeyValue<keyof T, T>(index)(a)
const _b = getKeyValue<keyof T, T>(index)(b)
if (_a < _b) return -1
if (_a > _b) return 1
return 0
})
}
It expects an array of generic type T, hence the cast for <T extends {}>
, as well as typing the parameter and function return type with T[]
const x = [{ label: 'anything' }, { label: 'goes'}]
const sorted = sortBy('label', x)
** getByKey
fn found here
I would use a composite (multi-column) key.
CREATE TABLE INFO (
t1ID INT,
t2ID INT,
PRIMARY KEY (t1ID, t2ID)
)
This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.
this is how I do it
function run_ajax(obj) {
$.ajax({
type:"POST",
url: prefix,
data: obj.pdata,
dataType: 'json',
error: function(data) {
//do error stuff
},
success: function(data) {
if(obj.func){
obj.func(data);
}
}
});
}
alert_func(data){
//do what you want with data
}
var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);
Here's how I usually do it:
Just replace your query with this statement SELECT * FROM table WHERE 1
SELECT
CASE WHEN EXISTS
(
SELECT * FROM table WHERE 1
)
THEN 'TRUE'
ELSE 'FALSE'
END
Rather than provide you with a complete list of differences, I'll give you my view on the matter.
If you read carefully the wiki page you provide, you'll often see sentences like "Octave supports both, while MATLAB requires the first" etc. This shows that Octave's developers try to make Octave syntax "superior" to MATLAB's.
This attitude makes Octave lose its purpose completely. The idea behind Octave is (or has become, I should say, see comments below) to have an open source alternative to run m-code. If it tries to be "better", it thus tries to be different, which is not in line with the reasons most people use it for. In my experience, running stuff developed in MATLAB doesn't ever work in one go, except for the really simple, really short stuff -- For any sizable function, I always have to translate a lot of stuff before it works in Octave, if not re-write it from scratch. How this is better, I really don't see...
Also, if you learn Octave, there's a lot of syntax allowed in Octave that's not allowed in MATLAB. Meaning -- code written in Octave often does not work in MATLAB without numerous conversions. It's also not compatible the other way around!
I could go on: The MathWorks has many toolboxes for MATLAB, there's Simulink and its related products for which there really is no equivalent in Octave (yes, you'd have to pay for all that. But often your employer/school does that anyway, and well, it at least exists), proven compliance with several industry standards, testing tools, validation tools, requirement management systems, report generation, a much larger community & user base, etc. etc. etc. MATLAB is only a small part of something much larger. Octave is...just Octave.
So, my advice:
Why this last point? Because in the sciences, there are often large code bases entirely written in MATLAB. There are professors, engineers, students, professional coders, lots and lots of people who know all the intricate gory details of MATLAB, and not so much of Octave.
If you get a new job, and everyone in your new office speaks Spanish, it's kind of cocky to demand of everyone that they start speaking English from then on, simply because you don't speak/like Spanish. Same with MATLAB and Octave.
NB -- if all downvoters could just leave a comment with their arguments and reasons for disagreeing with me, that'd be great :)
Note: Octave can be run in "traditional mode" (by including the --traditional flag when starting Octave) which makes it give an error when certain Octave-only syntax is used.
Stop this error you have to follow this simple steps
Then Run the code by using Shortcut key Ctrl+f5
**Other wise it still show error when you run it direct
Try this:
public ActionResult CreatePerson(int id) //controller
window.location.href = "@Url.Action("CreatePerson", "Person")?Id='+Id+'";
it's working fine passing parameter.
I have used the Unity 3D game engine for developing games for the PC and mobile phone. We use C# in this development.
If the server doesn't have enough memory also will cause this problem. This is my personal experience with Godaddy VPS.
In mongodb 3.0 or above, we can specify database name to restore. Assuming that you are standing at the root directory that contains bson files
./
a.bson
b.metadata.bson
...
The script would be
for FILENAME in *; do mongorestore -d <db_name> -c "${FILENAME%.*}" $FILENAME; done
Best,
Just another way to do this:
=MID(A1, LEN(A1), 1)
Berkelium is a C++ tool for making chrome embeddable.
AwesomiumDotNet is a wrapper around both Berkelium and Awesomium
BTW, the link here to Awesomium appears to be more current.
Try this one:
var data = [{id: 1, text: 'First'}, {id: 2, text: 'Second'}, {...}];
$('select[name="my_select"]').empty().select2({
data: data
});
assertTrue()/assertFalse() : to use only to assert boolean result returned
assertTrue(Iterables.elementsEqual(argumentComponents, returnedComponents));
You want to use Assert.assertTrue()
or Assert.assertFalse()
as the method under test returns a boolean
value.
As the method returns a specific thing such as a List
that should contain some expected elements, asserting with assertTrue()
in this way : Assert.assertTrue(myActualList.containsAll(myExpectedList)
is an anti pattern.
It makes the assertion easy to write but as the test fails, it also makes it hard to debug because the test runner will only say to you something like :
expected
true
but actual isfalse
Assert.assertEquals(Object, Object)
in JUnit4 or Assertions.assertIterableEquals(Iterable, Iterable)
in JUnit 5 : to use only as both equals()
and toString()
are overrided for the classes (and deeply) of the compared objects
It matters because the equality test in the assertion relies on equals()
and the test failure message relies on toString()
of the compared objects.
As String
overrides both equals()
and toString()
, it is perfectly valid to assert the List<String>
with assertEquals(Object,Object)
.
And about this matter : you have to override equals()
in a class because it makes sense in terms of object equality, not only to make assertions easier in a test with JUnit.
To make assertions easier you have other ways (that you can see in the next points of the answer).
Is Guava a way to perform/build unit test assertions ?
Is Google Guava Iterables.elementsEqual() the best way, provided I have the library in my build path, to compare those two lists?
No it is not. Guava is not an library to write unit test assertions.
You don't need it to write most (all I think) of unit tests.
What's the canonical way to compare lists for unit tests?
As a good practice I favor assertion/matcher libraries.
I cannot encourage JUnit to perform specific assertions because this provides really too few and limited features : it performs only an assertion with a deep equals.
Sometimes you want to allow any order in the elements, sometimes you want to allow that any elements of the expected match with the actual, and so for...
So using a unit test assertion/matcher library such as Hamcrest or AssertJ is the correct way.
The actual answer provides a Hamcrest solution. Here is a AssertJ solution.
org.assertj.core.api.ListAssert.containsExactly()
is what you need : it verifies that the actual group contains exactly the given values and nothing else, in order as stated :
Verifies that the actual group contains exactly the given values and nothing else, in order.
Your test could look like :
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
@Test
void ofComponent_AssertJ() throws Exception {
MyObject myObject = MyObject.ofComponents("One", "Two", "Three");
Assertions.assertThat(myObject.getComponents())
.containsExactly("One", "Two", "Three");
}
A AssertJ good point is that declaring a List
as expected is needless : it makes the assertion straighter and the code more readable :
Assertions.assertThat(myObject.getComponents())
.containsExactly("One", "Two", "Three");
And if the test fails :
// Fail : Three was not expected
Assertions.assertThat(myObject.getComponents())
.containsExactly("One", "Two");
you get a very clear message such as :
java.lang.AssertionError:
Expecting:
<["One", "Two", "Three"]>
to contain exactly (and in same order):
<["One", "Two"]>
but some elements were not expected:
<["Three"]>
Assertion/matcher libraries are a must because these will really further
Suppose that MyObject
doesn't store String
s but Foo
s instances such as :
public class MyFooObject {
private List<Foo> values;
@SafeVarargs
public static MyFooObject ofComponents(Foo... values) {
// ...
}
public List<Foo> getComponents(){
return new ArrayList<>(values);
}
}
That is a very common need.
With AssertJ the assertion is still simple to write. Better you can assert that the list content are equal even if the class of the elements doesn't override equals()/hashCode()
while JUnit ways require that :
import org.assertj.core.api.Assertions;
import static org.assertj.core.groups.Tuple.tuple;
import org.junit.jupiter.api.Test;
@Test
void ofComponent() throws Exception {
MyFooObject myObject = MyFooObject.ofComponents(new Foo(1, "One"), new Foo(2, "Two"), new Foo(3, "Three"));
Assertions.assertThat(myObject.getComponents())
.extracting(Foo::getId, Foo::getName)
.containsExactly(tuple(1, "One"),
tuple(2, "Two"),
tuple(3, "Three"));
}
Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.
var closedStatusId = @(Model.ClosedStatusId);
if you want to add a global property, you can use:
var styleEl = document.createElement('style'), styleSheet;
document.head.appendChild(styleEl);
styleSheet = styleEl.sheet;
styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
I had a similar issue and noted that the default cmd on Windows Server 2012 was running the x64 one.
For Windows 7, Windows 8, Windows Server 2008 R2 or Windows Server 2012, run the following commands as Administrator:
x86
Open C:\Windows\SysWOW64\cmd.exe Run the command: powershell Set-ExecutionPolicy RemoteSigned
x64
Open C:\Windows\system32\cmd.exe Run the command powershell Set-ExecutionPolicy RemoteSigned
You can check mode using
In CMD: echo %PROCESSOR_ARCHITECTURE% In Powershell: [Environment]::Is64BitProcess
I hope this help you.
You may be looking for position: fixed
.
Works everywhere except IE6 and many mobile devices.
See this page for the solution! https://msdn.microsoft.com/en-us/library/7aw8zc76(v=vs.110).aspx
I was able to implement the Child
form inside the parent.
In the Example below Form2
should change to the name of your child form.
NewMDIChild.MdiParent=me
is the main form since the control that opens (shows) the child form is the parent or Me
.
NewMDIChild.Show()
is your child form since you associated your child form with Dim NewMDIChild As New Form2()
Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
Dim NewMDIChild As New Form2()
'Set the Parent Form of the Child window.
NewMDIChild.MdiParent = Me
'Display the new form.
NewMDIChild.Show()
End Sub
Simple and it works.
You can use operator.setitem
.
from operator import setitem
a = [5, 4, 3, 2, 1, 0]
ell = [0, 1, 3, 5]
m = [0, 0, 0, 0]
for b, c in zip(ell, m):
setitem(a, b, c)
>>> a
[0, 0, 3, 0, 1, 0]
Is it any more readable or efficient than your solution? I am not sure!
Take a look at cat /proc/stat
grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.
NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.
Current CPU usage can be potentially calculated with:
awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)
It's a lot more simple that you think. You've signed into both your mobile and Chrome on your desktop using the same Google account. Google simply expect you will have your mobile with you most of the time. They take the location data from your phone and assume the location of your current desktop session is the same.
I proved this by RDPing into my Windows machine at home from work and checking Google maps remotely. It show my location as the same as Chrome on Linux at work.
If you don't have a mobile that is signed into Google then all they can do is lookup GeoIP data for the IP address assigned by your ISP. It will typically be wildly inaccurate.
Fwiw, I had this problem when running check_nrpe on a system that had the zenoss monitoring system installed. To add to the confusion, it worked fine as root user but not as zenoss user.
I found out that the zenoss user had an LD_LIBRARY_PATH that caused it to use zenoss libraries, which issue these warnings. Ie:
root@monitoring:$ echo $LD_LIBRARY_PATH
su - zenoss
zenoss@monitoring:/root$ echo $LD_LIBRARY_PATH
/usr/local/zenoss/python/lib:/usr/local/zenoss/mysql/lib:/usr/local/zenoss/zenoss/lib:/usr/local/zenoss/common/lib::
zenoss@monitoring:/root$ /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq
/usr/lib/nagios/plugins/check_nrpe: /usr/local/zenoss/common/lib/libcrypto.so.0.9.8: no version information available (required by /usr/lib/libssl.so.0.9.8)
(...)
zenoss@monitoring:/root$ LD_LIBRARY_PATH= /usr/lib/nagios/plugins/check_nrpe -H 192.168.61.61 -p 6969 -c check_mq
(...)
So anyway, what I'm trying to say: check your variables like LD_LIBRARY_PATH, LD_PRELOAD etc as well.