What I do on my cloud instances is I redirect port 80 to port 3000 with this command:
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000
Then I launch my Node.js on port 3000. Requests to port 80 will get mapped to port 3000.
You should also edit your /etc/rc.local
file and add that line minus the sudo
. That will add the redirect when the machine boots up. You don't need sudo
in /etc/rc.local
because the commands there are run as root
when the system boots.
Use the forever module to launch your Node.js with. It will make sure that it restarts if it ever crashes and it will redirect console logs to a file.
Add your Node.js start script to the file you edited for port redirection, /etc/rc.local
. That will run your Node.js launch script when the system starts.
This not only applies to Linode, but Digital Ocean, AWS EC2 and other VPS providers as well. However, on RedHat based systems /etc/rc.local
is /ect/rc.d/local
.
Based on Roberts answer, here is my function. This works for me if the element or its parent have been faded out via jQuery, can either get inner or outer dimensions and also returns the offset values.
/edit1: rewrote the function. it's now smaller and can be called directly on the object
/edit2: the function will now insert the clone just after the original element instead of the body, making it possible for the clone to maintain inherited dimensions.
$.fn.getRealDimensions = function (outer) {
var $this = $(this);
if ($this.length == 0) {
return false;
}
var $clone = $this.clone()
.show()
.css('visibility','hidden')
.insertAfter($this);
var result = {
width: (outer) ? $clone.outerWidth() : $clone.innerWidth(),
height: (outer) ? $clone.outerHeight() : $clone.innerHeight(),
offsetTop: $clone.offset().top,
offsetLeft: $clone.offset().left
};
$clone.remove();
return result;
}
var dimensions = $('.hidden').getRealDimensions();
Most people recommend using notifyDataSetChanged()
, but I found this link pretty useful. In fact using clear
and add
you can accomplish the same goal using less memory footprint, and more responsibe app.
For example:
notesListAdapter.clear();
notes = new ArrayList<Note>();
notesListAdapter.add(todayNote);
if (birthdayNote != null) notesListAdapter.add(birthdayNote);
/* no need to refresh, let the adaptor do its job */
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
the "title"
attribute will be used as the text for tooltip by the browser, if you want to apply style to it consider using some plugins
I do it in a way that will cast any case insensitive version of the string "false" to the boolean FALSE, but will behave using the normal php casting rules for all other strings. I think this is the best way to prevent unexpected behavior.
$test_var = 'False';
$test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
$result = (boolean) $test_var;
Or as a function:
function safeBool($test_var){
$test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
return (boolean) $test_var;
}
Cache-Control: private
Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache, such as a proxy server.
Before 7.2, the cache is at C:\Users\username\.netbeans\7.0\var\cache
. Deleting this directory should clear the cache for you.
Unfortunately it does not work in Chrome or Edge, but it does work in FireFox:
$(document)
// uncheck it when clicked
.on("click","input[type='radio']", function(){ $(this).prop("checked",false); })
// re-check it if value is changed to this input
.on("change","input[type='radio']", function(){ $(this).prop("checked",true); });
You can use spring-rest-template-logger to log RestTemplate
HTTP traffic.
Add a dependency to your Maven project:
<dependency>
<groupId>org.hobsoft.spring</groupId>
<artifactId>spring-rest-template-logger</artifactId>
<version>2.0.0</version>
</dependency>
Then customize your RestTemplate
as follows:
RestTemplate restTemplate = new RestTemplateBuilder()
.customizers(new LoggingCustomizer())
.build()
Ensure that debug logging is enabled in application.properties
:
logging.level.org.hobsoft.spring.resttemplatelogger.LoggingCustomizer = DEBUG
Now all RestTemplate HTTP traffic will be logged to org.hobsoft.spring.resttemplatelogger.LoggingCustomizer
at debug level.
DISCLAIMER: I wrote this library.
I know this is really old, but this is the simplest way to query for Map.
Simply implement the ResultSetExtractor interface to define what type you want to return. Below is an example of how to use this. You'll be mapping it manually, but for a simple map, it should be straightforward.
jdbcTemplate.query("select string1,string2 from table where x=1", new ResultSetExtractor<Map>(){
@Override
public Map extractData(ResultSet rs) throws SQLException,DataAccessException {
HashMap<String,String> mapRet= new HashMap<String,String>();
while(rs.next()){
mapRet.put(rs.getString("string1"),rs.getString("string2"));
}
return mapRet;
}
});
This will give you a return type of Map that has multiple rows (however many your query returned) and not a list of Maps. You can view the ResultSetExtractor docs here: http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/jdbc/core/ResultSetExtractor.html
I didn't have any success with the header solution - they were never picked up in my ajaxSuccess / ajaxComplete method. I used Steg's answer with the custom response, but I modified the JS side some. I setup a method that I call in each function so I can use standard $.get
and $.post
methods.
function handleAjaxResponse(data, callback) {
//Try to convert and parse object
try {
if (jQuery.type(data) === "string") {
data = jQuery.parseJSON(data);
}
if (data.error) {
if (data.error == 'login') {
window.location.reload();
return;
}
else if (data.error.length > 0) {
alert(data.error);
return;
}
}
}
catch(ex) { }
if (callback) {
callback(data);
}
}
Example of it in use...
function submitAjaxForm(form, url, action) {
//Lock form
form.find('.ajax-submit').hide();
form.find('.loader').show();
$.post(url, form.serialize(), function (d) {
//Unlock form
form.find('.ajax-submit').show();
form.find('.loader').hide();
handleAjaxResponse(d, function (data) {
// ... more code for if auth passes ...
});
});
return false;
}
Removing print statements can also fix the problem.
Apart from loading images, this error also happens when your code is printing continuously at a high rate, which is causing the error "IOPub data rate exceeded". E.g. if you have a print statement in a for loop somewhere that is being called over 1000 times.
blak3r / Rushyo's solution works fine for everything except Windows 8. Running AT
on Windows 8 results in:
The AT command has been deprecated. Please use schtasks.exe instead.
The request is not supported.
(see screenshot #1) and will return %errorLevel%
1
.
So, I went searching for other commands that require elevated permissions. rationallyparanoid.com had a list of a few, so I ran each command on the two opposite extremes of current Windows OSs (XP and 8) in the hopes of finding a command that would be denied access on both OSs when run with standard permissions.
Eventually, I did find one - NET SESSION
. A true, clean, universal solution that doesn't involve:
FOR
loopsAT
(Windows 8 incompatible) or WHOAMI
(Windows XP incompatible). Each of which have their own security, usability, and portability issues.
I've independently confirmed that this works on:
(see screenshot #2)
So, to use this solution, simply do something like this:
@echo off
goto check_Permissions
:check_Permissions
echo Administrative permissions required. Detecting permissions...
net session >nul 2>&1
if %errorLevel% == 0 (
echo Success: Administrative permissions confirmed.
) else (
echo Failure: Current permissions inadequate.
)
pause >nul
Available here, if you're lazy: https://dl.dropbox.com/u/27573003/Distribution/Binaries/check_Permissions.bat
NET SESSION
is a standard command used to "manage server computer connections. Used without parameters, [it] displays information about all sessions with the local computer."
So, here's the basic process of my given implementation:
@echo off
goto check_Permissions
:check_Permissions
code blocknet session >nul 2>&1
STDOUT
) stream to nul
STDERR
) to the same destination as numeric handle 1if %errorLevel% == 0
%errorLevel%
) is 0
then this means that no errors have occurred and, therefore, the immediate previous command ran successfullyelse
%errorLevel%
) is not 0
then this means that errors have occurred and, therefore, the immediate previous command ran unsuccessfully
NET SESSION
on Windows XP x86 - Windows 8 x64:
Thank you, @Tilka, for changing your accepted answer to mine. :)
HTML already has a built-in horizontal divider called <hr/>
(short for "horizontal rule"). Bootstrap styles it like this:
hr {
margin-top: 1rem;
margin-bottom: 1rem;
border: 0;
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />_x000D_
<p>_x000D_
Some text_x000D_
<hr/>_x000D_
More text_x000D_
</p>
_x000D_
Best that works for me:
.left{
width:140px;
float:left;
height:100%;
}
.right{
margin-left:140px;
}
This might work:
^(\*|\d+(\.\d+){0,2}(\.\*)?)$
At the top level, "*" is a special case of a valid version number. Otherwise, it starts with a number. Then there are zero, one, or two ".nn" sequences, followed by an optional ".*". This regex would accept 1.2.3.* which may or may not be permitted in your application.
The code for retrieving the matched sequences, especially the (\.\d+){0,2}
part, will depend on your particular regex library.
It's the first result on Google: http://docs.python.org/library/stdtypes.html#string-formatting
See also the new format() function: http://docs.python.org/library/stdtypes.html#str.format
Actually Abstract Data Types is:
For example, lets see specifications of some Abstract Data Types,
Very, very late to answer this one, but I've just discovered that using a background-image that is encoded as a base64 URI in the CSS, rather than held as a separate image, continues to animate in IE8.
Bootstrap 3 now has Responsive tables out of the box. Hooray! :)
You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive
Add a <div class="table-responsive">
surrounding your table and you should be good to go:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
To make it work on all layouts you can do this:
.table-responsive
{
overflow-x: auto;
}
Normally you can use None
, but you can also use objc.NULL
, e.g.
import objc
val = objc.NULL
Especially useful when working with C code in Python.
Also see: Python objc.NULL Examples
Adding strings concatenates them:
> "1" + "1"
"11"
You have to parse them into numbers first:
/* parseFloat is used here.
* Because of it's not known that
* whether the number has fractional places.
*/
var a = parseFloat($('#a').val()),
b = parseFloat($('#b').val());
Also, you have to get the values from inside of the click handler:
$("submit").on("click", function() {
var a = parseInt($('#a').val(), 10),
b = parseInt($('#b').val(), 10);
});
Otherwise, you're using the values of the textboxes from when the page loads.
We need a JSON file which we need to export in the controller of angularjs and we should be able to call from the HTML file. We will look at both. But before we start, we need to first add two files in our angular library. Those two files are json-export-excel.js and filesaver.js. Moreover, we need to include the dependency in the angular module. So the first two steps can be summarised as follows -
1) Add json-export.js and filesaver.js in your angular library.
2) Include the dependency of ngJsonExportExcel in your angular module.
var myapp = angular.module('myapp', ['ngJsonExportExcel'])
Now that we have included the necessary files we can move on to the changes which need to be made in the HTML file and the controller. We assume that a json is being created on the controller either manually or by making a call to the backend.
HTML :
Current Page as Excel
All Pages as Excel
In the application I worked, I brought paginated results from the backend. Therefore, I had two options for exporting to excel. One for the current page and one for all data. Once the user selects an option, a call goes to the controller which prepares a json (list). Each object in the list forms a row in the excel.
Read more at - https://www.oodlestechnologies.com/blogs/Export-to-excel-using-AngularJS
The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):
$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );
So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:
$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );
Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,
The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.
That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.
I just give it a shot:
In [9]: s = Series([True, True, True, False])
In [10]: s
Out[10]:
0 True
1 True
2 True
3 False
In [11]: -s
Out[11]:
0 False
1 False
2 False
3 True
Use a directive which adds to both the $formatters and $parsers collections to ensure that the transformation is performed in both directions.
See this other answer for more details including a link to jsfiddle.
After trying all the other solutions posted here (Skype, updates to C++ Redistributable), I found that another process was using port 80. The culprit was Microsoft Internet Information Server (IIS). You can stop the service from the command line on Windows 7/Vista:
net stop was /y
Or set the service to not start automatically by going to Services: click Start, click Control Panel, click Performance and Maintenance, click Administrative Tools, and then double-click Services. There, locate "WAS Service" and "World Wide Web Publication Service" and set them to manual or deactivate them completely.
Then restart the WAMP server.
More info: http://www.sitepoint.com/unblock-port-80-on-windows-run-apache/
To set your App or any individual activity display in Full Screen mode, insert the code
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
in AndroidManifest.xml, under application or activity tab.
If someone having same problem i solved it by enabling Byte-Range support on my server. It appears that Safari requires Byte range requests. In my case i use NGINX and i had to add proxy_force_ranges on;
to my config file. Thanks to this answer!
It happens when $ret
hasn't been defined. The solution is simple. Right above $tags = get_tags();
, add the following line:
$ret = array();
There are several ways. Read The String Formatters of Manor Farm for an in-depth comparison.
Here is one common problem I haven't seen addressed in the other comments: is your host running a cache of some sort? If they are automatically caching results in some fashion you would get this sort of behavior.
Isn't this a much simpler solution, if I correctly understand the question, of course.
I want to load email addresses that are in a table called "spam" into a variable.
select email from spam
produces the following list, say:
.accountant
.bid
.buiilldanything.com
.club
.cn
.cricket
.date
.download
.eu
To load into the variable @list:
declare @list as varchar(8000)
set @list += @list (select email from spam)
@list may now be INSERTed into a table, etc.
I hope this helps.
To use it for a .csv file or in VB, spike the code:
declare @list as varchar(8000)
set @list += @list (select '"'+email+',"' from spam)
print @list
and it produces ready-made code to use elsewhere:
".accountant,"
".bid,"
".buiilldanything.com,"
".club,"
".cn,"
".cricket,"
".date,"
".download,"
".eu,"
One can be very creative.
Thanks
Nico
If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
Note- position really matters add google() before jcenter()
And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
check these links below for more details-
To do the same trick described below for Windows in OS X, create this shell script
#!/bin/bash
cd $(dirname "$0") && pwd
ipython notebook
Call it ipython-notebook.command and make it executable.
Put it in the directory you want to work in, then double-click it.
You should have one listview in your mainlist.xml
file with id as @android:id/list
<ListView
android:id="@android:id/list"
android:layout_height="wrap_content"
android:layout_height="fill_parent"/>
From the accepted answer, it looks like your desired behaviour is to turn
skip 0
skip 1
skip 2
skip 3
"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636
into
2012,06,23,03,09,13.23,4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,NAN,-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636
If that's right, then I think something like
import csv
with open("test.dat", "rb") as infile, open("test.csv", "wb") as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile, quoting=False)
for i, line in enumerate(reader):
if i < 4: continue
date = line[0].split()
day = date[0].split('-')
time = date[1].split(':')
newline = day + time + line[1:]
writer.writerow(newline)
would be a little simpler than the reps
stuff.
The well-accepted answer helped me a lot but I wanted to pass HttpStatusCode in my middleware to manage error status code at runtime.
According to this link I got some idea to do the same. So I merged the Andrei Answer with this. So my final code is below:
1. Base class
public class ErrorDetails
{
public int StatusCode { get; set; }
public string Message { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
2. Custom Exception Class Type
public class HttpStatusCodeException : Exception
{
public HttpStatusCode StatusCode { get; set; }
public string ContentType { get; set; } = @"text/plain";
public HttpStatusCodeException(HttpStatusCode statusCode)
{
this.StatusCode = statusCode;
}
public HttpStatusCodeException(HttpStatusCode statusCode, string message)
: base(message)
{
this.StatusCode = statusCode;
}
public HttpStatusCodeException(HttpStatusCode statusCode, Exception inner)
: this(statusCode, inner.ToString()) { }
public HttpStatusCodeException(HttpStatusCode statusCode, JObject errorObject)
: this(statusCode, errorObject.ToString())
{
this.ContentType = @"application/json";
}
}
3. Custom Exception Middleware
public class CustomExceptionMiddleware
{
private readonly RequestDelegate next;
public CustomExceptionMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await next(context);
}
catch (HttpStatusCodeException ex)
{
await HandleExceptionAsync(context, ex);
}
catch (Exception exceptionObj)
{
await HandleExceptionAsync(context, exceptionObj);
}
}
private Task HandleExceptionAsync(HttpContext context, HttpStatusCodeException exception)
{
string result = null;
context.Response.ContentType = "application/json";
if (exception is HttpStatusCodeException)
{
result = new ErrorDetails()
{
Message = exception.Message,
StatusCode = (int)exception.StatusCode
}.ToString();
context.Response.StatusCode = (int)exception.StatusCode;
}
else
{
result = new ErrorDetails()
{
Message = "Runtime Error",
StatusCode = (int)HttpStatusCode.BadRequest
}.ToString();
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
return context.Response.WriteAsync(result);
}
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
string result = new ErrorDetails()
{
Message = exception.Message,
StatusCode = (int)HttpStatusCode.InternalServerError
}.ToString();
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return context.Response.WriteAsync(result);
}
}
4. Extension Method
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)
{
app.UseMiddleware<CustomExceptionMiddleware>();
}
5. Configure Method in startup.cs
app.ConfigureCustomExceptionMiddleware();
app.UseMvc();
Now my login method in Account controller :
try
{
IRepository<UserMaster> obj
= new Repository<UserMaster>(_objHeaderCapture, Constants.Tables.UserMaster);
var result = obj.Get()
.AsQueryable()
.Where(sb => sb.EmailId.ToLower() == objData.UserName.ToLower()
&& sb.Password == objData.Password.ToEncrypt()
&& sb.Status == (int)StatusType.Active)
.FirstOrDefault();
if (result != null)//User Found
return result;
else // Not Found
throw new HttpStatusCodeException(HttpStatusCode.NotFound,
"Please check username or password");
}
catch (Exception ex)
{
throw ex;
}
Above you can see if i have not found the user then raising the HttpStatusCodeException in which i have passed HttpStatusCode.NotFound status and a custom message
In middleware
catch (HttpStatusCodeException ex)
blocked will be called which will pass control to
private Task HandleExceptionAsync(HttpContext context, HttpStatusCodeException exception) method
But what if i got runtime error before? For that i have used try catch block which throw exception and will be catched in catch (Exception exceptionObj) block and will pass control to
Task HandleExceptionAsync(HttpContext context, Exception exception)
method.
I have used a single ErrorDetails class for uniformity.
Its worked for me
$start_time = date_create_from_format('Y-m-d H:i:s', $start_time);
$current_date = new DateTime();
$diff = $start_time->diff($current_date);
$aa = (string)$diff->format('%R%a');
echo gettype($aa);
If you're using bindings you can do
val headerView = binding.navView.getHeaderView(0)
val headerBinding = NavDrawerHeaderBinding.bind(headerView)
headerBinding.textView.text = "Your text here"
This font is not standard on all devices. It is installed by default on some Macs, but rarely on PCs and mobile devices.
To use this font on all devices, use a @font-face declaration in your CSS to link to it on your domain if you wish to use it.
@font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); }
@font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf'); }
Taken from css3.info
There are 2 possible use of php code:
in case 1. the closing tag is totally unusefull, also I would like to see just 1 (one) php open tag and NO (zero) closing tag in such a case. This is a good practice as it make code clean and separate logic from presentation. For presentation case (2.) some found it is natural to close all tags (even the PHP-processed ones), that leads to confution, as the PHP has in fact 2 separate use case, that should not be mixed: logic/calculus and presentation
You should really use a Post Redirect Get pattern for handling this but if you've somehow ended up in a position where PRG isn't viable (e.g. the form itself is in an include, preventing redirects) you can hash some of the request parameters to make a string based on the content and then check that you haven't sent it already.
//create digest of the form submission:
$messageIdent = md5($_POST['name'] . $_POST['email'] . $_POST['phone'] . $_POST['comment']);
//and check it against the stored value:
$sessionMessageIdent = isset($_SESSION['messageIdent'])?$_SESSION['messageIdent']:'';
if($messageIdent!=$sessionMessageIdent){//if its different:
//save the session var:
$_SESSION['messageIdent'] = $messageIdent;
//and...
do_your_thang();
} else {
//you've sent this already!
}
Another good option is, to pass a renderTo HTML reference. If it is a string, the element by that id is used. Otherwise you can do:
chart: {
renderTo: document.getElementById('container')
},
or with jquery:
chart: {
renderTo: $('#container')[0]
},
Further information can be found here: https://api.highcharts.com/highstock/chart.renderTo
DBMS stands for "Database Management Systems" it includes all Databases. RDBMS are a special Type of DMBS . R in RDBMS implies that the database uses the Relational model. a collection of related tables in the relational model makes up a database.DBMS is used for simple and small application while RDBMS is used for applications with a huge database.DBMS are for smaller organizations where security is not concerned(i.e. DBMS does not impose any constraints) while RDBMS is quitely opposite( RDBMS define the integrity constraint for the purpose of holding ACID PROPERTY).
An another way, you can do it easily with CMD on Windows
Put your installed version (mine is 11).
cd C:\Program Files\PostgreSQL\11\bin\
and run simple query
psql -U <postgre_username> -d <db_name> < <C:\path\data_dump.sql>
enter password then wait the final console message.
You're looking for itertools.compress
:
>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] #winner
100000 loops, best of 3: 1.98 us per loop
>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil)) #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop
>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil)) #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
100 loops, best of 3: 7.65 ms per loop
Don't use filter
as a variable name, it is a built-in function.
If it's the HttpRequest.QueryString then you can copy the collection into a writable collection and have your way with it.
NameValueCollection filtered = new NameValueCollection(request.QueryString);
filtered.Remove("Language");
the simple answer is:
branch: the current branch pointer moves with every commit to the repository
but
tag: the commit that a tag points doesn't change, in fact the tag is a snapshot of that commit.
It's compiling because printf
isn't type safe, since it uses variable arguments in the C sense1. printf
has no option for std::string
, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.
The easiest way to fix this, since you're using C++, is printing it normally with std::cout
, since std::string
supports that through operator overloading:
std::cout << "Follow this command: " << myString;
If, for some reason, you need to extract the C-style string, you can use the c_str()
method of std::string
to get a const char *
that is null-terminated. Using your example:
#include <iostream>
#include <string>
#include <stdio.h>
int main()
{
using namespace std;
string myString = "Press ENTER to quit program!";
cout << "Come up and C++ me some time." << endl;
printf("Follow this command: %s", myString.c_str()); //note the use of c_str
cin.get();
return 0;
}
If you want a function that is like printf
, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format
.
[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf
, that means a string with encoded type information like %d
meaning int
. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.
The best way to check for named elements is to use exist()
, however the above answers are not using the function properly. You need to use the where
argument to check for the variable within the list.
foo <- list(a=42, b=NULL)
exists('a', where=foo) #TRUE
exists('b', where=foo) #TRUE
exists('c', where=foo) #FALSE
each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.
For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.
http:..../somelink?componentId=123
would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123
The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.
It prints true
on my machine. And it should, otherwise nothing in Java would work as expected. (This is explained in the JLS: 4.3.4 When Reference Types Are the Same)
Do you have multiple classloaders in place?
Ah, and in response to this comment:
I realise I have a typo in my question. I should be like this:
MyImplementedObject obj = new MyImplementedObject ();
if(obj.getClass() == MyObjectInterface.class) System.out.println("true");
MyImplementedObject implements MyObjectInterface So in other words, I am comparing it with its implemented objects.
OK, if you want to check that you can do either:
if(MyObjectInterface.class.isAssignableFrom(obj.getClass()))
or the much more concise
if(obj instanceof MyobjectInterface)
Utilize the output of built-in repr
to deal with \r\n\t
and process the output of re.escape
is what you want:
re.escape(repr(a)[1:-1]).replace('\\\\', '\\')
Assuming that start_date is before end_date,
interval [start_date..end_date] NOT BETWEEN two dates simply means that either it starts before 2009-12-15 or it ends after 2010-01-02.
Then you can simply do
start_date<CAST('2009-12-15' AS DATE) or end_date>CAST('2010-01-02' AS DATE)
on debian :
apt list --upgradable
gives the list with package, version to be upgraded, and actual version of the package.
result :
base-files/stable 8+deb8u8 amd64 [upgradable from: 8+deb8u7]
bind9-host/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]
ca-certificates/stable 20141019+deb8u3 all [upgradable from: 20141019+deb8u2]
certbot/jessie-backports 0.10.2-1~bpo8+1 all [upgradable from: 0.8.1-2~bpo8+1]
dnsutils/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]
If your testing requires pulling quasi-real credit reports from the bureaus, the inactive SSNs of other answers won't work and you'll need designated test numbers.
I found this site Which appears to contain test social security numbers with associated test names and credit card numbers.
Transunion has a test environment you can link and send data to, including associated dummy credit reports. Sending a SSN to them with certain numbers in certain positions will automatically route the inquiry to their test environment Other credit bureaus will have similar systems in place.
You can use Floern's solution. You may also want to disable the input while you set the color to gray. http://www.w3schools.com/tags/att_input_disabled.asp
Assuming that the user you are using in phpmyadmin has the necessary privileges, you can run this query to change the root password:
UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;
@Html.DropDownList("ddl",Model.Select(item => new SelectListItem
{
Value = item.RecordID.ToString(),
Text = item.Name.ToString(),
Selected = "select" == item.RecordID.ToString()
}))
DECLARE @uuid VARCHAR(50)
SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010'
SELECT CAST(
SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' +
SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12)
AS UNIQUEIDENTIFIER)
Or for multiple ignores on the next line, string the rules using commas
// eslint-disable-next-line class-methods-use-this, no-unused-vars
For Ubuntu 12.04:
sudo apt-get install python-qt4
virtualenv .env --no-site-packages
source .env/bin/activate
easy_install -U distribute
ln -s /usr/lib/python2.7/dist-packages/PyQt4 .
ln -s /usr/lib/python2.7/dist-packages/sip.so .
pip install matplotlib
Here's a solution that doesn't use negative margins or calc
. Run the snippet below to see the final result.
Explanation
We give the header and the footer a fixed height of 30px
and position them absolutely at the top and bottom, respectively. To prevent the content from falling underneath, we use two classes: below-header
and above-footer
to pad the div above and below with 30px
.
All of the content is wrapped in a position: relative
div so that the header and footer are at the top/bottom of the content and not the window.
We use the classes fit-to-parent
and min-fit-to-parent
to make the content fill out the page. This gives us a sticky footer which is at least as low as the window, but hidden if the content is longer than the window.
Inside the header and footer, we use the display: table
and display: table-cell
styles to give the header and footer some vertical padding without disrupting the shrink-wrap quality of the page. (Giving them real padding can cause the total height of the page to be more than 100%
, which causes a scroll bar to appear when it isn't really needed.)
.fit-parent {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
.min-fit-parent {_x000D_
min-height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
.below-header {_x000D_
padding-top: 30px;_x000D_
}_x000D_
.above-footer {_x000D_
padding-bottom: 30px;_x000D_
}_x000D_
.header {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
height: 30px;_x000D_
width: 100%;_x000D_
}_x000D_
.footer {_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
height: 30px;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
/* helper classes */_x000D_
_x000D_
.padding-lr-small {_x000D_
padding: 0 5px;_x000D_
}_x000D_
.relative {_x000D_
position: relative;_x000D_
}_x000D_
.auto-scroll {_x000D_
overflow: auto;_x000D_
}_x000D_
/* these two classes work together to create vertical centering */_x000D_
.valign-outer {_x000D_
display: table;_x000D_
}_x000D_
.valign-inner {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<html class='fit-parent'>_x000D_
<body class='fit-parent'>_x000D_
<div class='min-fit-parent auto-scroll relative' style='background-color: lightblue'>_x000D_
<div class='header valign-outer' style='background-color: black; color: white;'>_x000D_
<div class='valign-inner padding-lr-small'>_x000D_
My webpage_x000D_
</div>_x000D_
</div>_x000D_
<div class='fit-parent above-footer below-header'>_x000D_
<div class='fit-parent' id='main-inner'>_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
</div>_x000D_
</div>_x000D_
<div class='footer valign-outer' style='background-color: white'>_x000D_
<div class='valign-inner padding-lr-small'>_x000D_
© 2005 Old Web Design_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.
Settings can be configured using built-in configuration sections such as connectionStrings
or appSettings
. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.
Web applications typically have a web.config, while Windows GUI/service applications have an app.config file.
Application-level config files inherit settings from global configuration files, e.g. the machine.config.
Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyKey"
connectionString="Data Source=localhost;Initial Catalog=ABC;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Once you have defined your app.config, you can read it in code using the ConfigurationManager class. Don't be intimidated by the verbose MSDN examples; it's actually quite simple.
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
Frequently changing the *.config files is usually not a good idea, but it sounds like you only want to perform one-time setup.
See: Change connection string & reload app.config at run time which describes how to update the connectionStrings
section of the *.config file at runtime.
Note that ideally you would perform such configuration changes from a simple installer.
Q: Suppose I manually change some <value>
in app.config, save it and then close it. Now when I go to my bin folder and launch the .exe file from here, why doesn't it reflect the applied changes?
A: When you compile an application, its app.config is copied to the bin directory1 with a name that matches your exe. For example, if your exe was named "test.exe", there should be a "text.exe.config" in your bin directory. You can change the configuration without a recompile, but you will need to edit the config file that was created at compile time, not the original app.config.
1: Note that web.config files are not moved, but instead stay in the same location at compile and deployment time. One exception to this is when a web.config is transformed.
New configuration options were introduced with .NET Core. The way that *.config files works does not appear to have changed, but developers are free to choose new, more flexible configuration paradigms.
I found an excellent Chart.js
plugin that does exactly what you want:
https://github.com/emn178/Chart.PieceLabel.js
moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.
function momentTest() {
var varDate = "2018-01-19 18:05:01.423";
var myDate = moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
var todayDate = moment().format("DD-MM-YYYY");
var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");
var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");
alert(todayDate);
if (myDate == todayDate) {
alert("date is today");
} else if (myDate == yesterdayDate) {
alert("date is yesterday");
} else if (myDate == tomorrowDate) {
alert("date is tomorrow");
} else {
alert("It's not today, tomorrow or yesterday!");
}
}
The -maxdepth
option should be before the -name
option, like below.,
find . -maxdepth 1 -name "string" -print
If you want to run angular app ported from another machine without ng
command
then edit package.json
as follows
"scripts": {
"ng": "ng",
"start": "node node_modules/.bin/ng serve",
"build": "node node_modules/.bin/ng build",
"test": "node node_modules/.bin/ng test",
"lint": "node node_modules/.bin/ng lint",
"e2e": "node node_modules/.bin/ng e2e"
}
Finally run usual npm start
command to start build server.
Wouldn't List<ArrayList<String>> 2dlist = new ArrayList<ArrayList<String>>();
be a better (more efficient) implementation?
In socket.io 2.0: you can use:
socket.conn.transport.socket._socket.remoteAddress
works with transports: ['websocket']
A1 A2
Toronto<b> is nice =LEFT(A1,(FIND("<",A1,1)-1))
Not sure if the syntax is correct but the forumla in A2 will work for you,
An xmlns
is a unique identifier within the document - it doesn't have to be a URI to the schema:
XML namespaces provide a simple method for qualifying element and attribute names used in Extensible Markup Language documents by associating them with namespaces identified by URI references.
xsi:schemaLocation
is supposed to give a hint as to the actual schema location:
can be used in a document to provide hints as to the physical location of schema documents which may be used for assessment.
Try the following script:
Exec sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
GO
Also
I prefer(After a long search) to use the following script, it contains @fillfactor
determines how much percentage of the space on each leaf-level page is filled with data.
DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))+'.' + QUOTENAME(name) AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO
for more info, check the following link:
and if you want to Check Index Fragmentation on Indexes in a Database, try the following script:
SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
ORDER BY indexstats.avg_fragmentation_in_percent desc
For more information, Check the following link:
You can use TimerTask for Cronjobs.
Main.java
public class Main{
public static void main(String[] args){
Timer t = new Timer();
MyTask mTask = new MyTask();
// This task is scheduled to run every 10 seconds
t.scheduleAtFixedRate(mTask, 0, 10000);
}
}
MyTask.java
class MyTask extends TimerTask{
public MyTask(){
//Some stuffs
}
@Override
public void run() {
System.out.println("Hi see you after 10 seconds");
}
}
Alternative You can also use ScheduledExecutorService.
How about $_SERVER
?
if (get_magic_quotes_gpc() === 1) {
$_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
$_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);
$_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);
$_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);
$_SERVER = json_decode( stripslashes(json_encode($_SERVER,JSON_HEX_APOS)), true);
}
When it is on server side, use web services - maybe RESTful with JSON.
When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.
Below is example from documentation. Look at methodReturningString
.
Java code:
public class MethodInvocation extends Applet {
public void noArgMethod() { ... }
public void someMethod(String arg) { ... }
public void someMethod(int arg) { ... }
public int methodReturningInt() { return 5; }
public String methodReturningString() { return "Hello"; }
public OtherClass methodReturningObject() { return new OtherClass(); }
}
public class OtherClass {
public void anotherMethod();
}
Web page and JavaScript code:
<applet id="app"
archive="examples.jar"
code="MethodInvocation" ...>
</applet>
<script language="javascript">
app.noArgMethod();
app.someMethod("Hello");
app.someMethod(5);
var five = app.methodReturningInt();
var hello = app.methodReturningString();
app.methodReturningObject().anotherMethod();
</script>
In service class within OnStart method don't do huge operation, OS expect short amount of time to run service, run your method using thread start:
protected override void OnStart(string[] args)
{
Thread t = new Thead(new ThreadStart(MethodName)); // e.g.
t.Start();
}
Order Collection Limit :
$orderCollection = Mage::getResourceModel('sales/order_collection');
$orderCollection->getSelect()->limit(10);
foreach ($orderCollection->getItems() as $order) :
$orderModel = Mage::getModel('sales/order');
$order = $orderModel->load($order['entity_id']);
echo $order->getId().'<br>';
endforeach;
Using reduce, you can do this in one Array.prototype function. This will fetch all even numbers from an array.
var arr = [1,2,3,4,5,6,7,8];_x000D_
_x000D_
var brr = arr.reduce((c, n) => {_x000D_
if (n % 2 !== 0) {_x000D_
return c;_x000D_
}_x000D_
c.push(n);_x000D_
return c;_x000D_
}, []);_x000D_
_x000D_
document.getElementById('mypre').innerHTML = brr.toString();
_x000D_
<h1>Get all even numbers</h1>_x000D_
<pre id="mypre"> </pre>
_x000D_
You can use the same method and generalize it for your objects, like this.
var arr = options.reduce(function(c,n){
if(somecondition) {return c;}
c.push(n);
return c;
}, []);
arr
will now contain the filtered objects.
I have also noticed that cordova has a "serve" command that Phonegap doesn't. This command launches a local server on port 8000. This is handy for running your app in Chrome and using the Ripple emulator.
I got the same error for pandas latest version. Then saw this warning
FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.
This shall work for you.
% draw simple vector from pt a to pt b
% wtr : with respect to
scale=0;%for drawin vectors with true scale
a = [10 20 30];% wrt origine O(0,0,0)
b = [10 10 20];% wrt origine O(0,0,0)
starts=a;% a now is the origine of my vector to draw (from a to b) so we made a translation from point O to point a = to vector a
c = b-a;% c is the new coordinates of b wrt origine a
ends=c;%
plot3(a(1),a(2),a(3),'*b')
hold on
plot3(b(1),b(2),b(3),'*g')
quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3),scale);% Use scale = 0 to plot the vectors without the automatic scaling.
% axis equal
hold off
None of these worked for me, they all introduced errors.
The following worked for me:
Yes, when you invoke e.extractAll(foo)
, Python munges that into extractAll(e, foo)
.
From http://docs.python.org/tutorial/classes.html
the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.
Emphasis added.
In a bootstrap environment none of the top answers helped, but applying the following removed all borders:
.noBorder {
border:none !important;
}
Applied as:
<td class="noBorder">
The Perl documentation comes with a nice collection of FAQs. Your question is frequently asked:
% perldoc -q duplicate
The answer, copy and pasted from the output of the command above, appears below:
Found in /usr/local/lib/perl5/5.10.0/pods/perlfaq4.pod How can I remove duplicate elements from a list or array? (contributed by brian d foy) Use a hash. When you think the words "unique" or "duplicated", think "hash keys". If you don't care about the order of the elements, you could just create the hash then extract the keys. It's not important how you create that hash: just that you use "keys" to get the unique elements. my %hash = map { $_, 1 } @array; # or a hash slice: @hash{ @array } = (); # or a foreach: $hash{$_} = 1 foreach ( @array ); my @unique = keys %hash; If you want to use a module, try the "uniq" function from "List::MoreUtils". In list context it returns the unique elements, preserving their order in the list. In scalar context, it returns the number of unique elements. use List::MoreUtils qw(uniq); my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7 my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7 You can also go through each element and skip the ones you've seen before. Use a hash to keep track. The first time the loop sees an element, that element has no key in %Seen. The "next" statement creates the key and immediately uses its value, which is "undef", so the loop continues to the "push" and increments the value for that key. The next time the loop sees that same element, its key exists in the hash and the value for that key is true (since it's not 0 or "undef"), so the next skips that iteration and the loop goes to the next element. my @unique = (); my %seen = (); foreach my $elem ( @array ) { next if $seen{ $elem }++; push @unique, $elem; } You can write this more briefly using a grep, which does the same thing. my %seen = (); my @unique = grep { ! $seen{ $_ }++ } @array;
Two arrays can be easily added or union without chaning their original indexing by + operator. This will be very help full in laravel and codeigniter select dropdown.
$empty_option = array(
''=>'Select Option'
);
$option_list = array(
1=>'Red',
2=>'White',
3=>'Green',
);
$arr_option = $empty_option + $option_list;
Output will be :
$arr_option = array(
''=>'Select Option'
1=>'Red',
2=>'White',
3=>'Green',
);
Bootstrap 3 has been released since this question was originally answered in January, so if you are a BS3 user, please refer to the BS3 documentation. For those still on BS2, the original answer still applies. If you are interested in switching from 2 to 3, see the migration guide.
From the bootstrap 2 docs:
Make any row "fluid" by changing .row to .row-fluid. The column classes stay the exact same, making it easy to flip between fixed and fluid grids.
Code
<div class="row-fluid">
<div class="span4">...</div>
<div class="span8">...</div>
</div>
This, in conjunction with setting the width of your container to a fluid value, should allow you to get your desired layout.
You can use TEXT
type, which is not limited to 64KB.
Rather than using Ctrl + K, X you can also just type prop
and then hit Tab twice.
You can use jQuery UI Dialog.
These libraries create HTML elements that look and behave like a dialog box, allowing you to put anything you want (including form elements or video) in the dialog.
To update a subset of fields, you can use update_fields
:
survey.save(update_fields=["active"])
The update_fields
argument was added in Django 1.5. In earlier versions, you could use the update()
method instead:
Survey.objects.filter(pk=survey.pk).update(active=True)
I think this solution may not be efficient but it serves the purpose and adds flexibility with the border width.
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="40dp"
android:layout_gravity="center"
card_view:cardBackgroundColor="@color/some_color"
card_view:cardCornerRadius="20dp"
card_view:contentPadding="5dp"> <!-- Change it to customize the border width -->
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
card_view:cardCornerRadius="20dp"
card_view:contentPadding="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Add your UI elements -->
</RelativeLayout>
</android.support.v7.widget.CardView>
</android.support.v7.widget.CardView>
If you mean you want to fetch everything from the beginning up to a particular point, Charles Bailey's answer is perfect. If you want to do the reverse and retrieve a subset of the history going back from the current date, you can use git clone --depth [N]
where N is the number of revs of history you want. However:
--depth
Create a shallow clone with a history truncated to the specified number of revisions. A shallow repository has a number of limitations (you cannot clone or fetch from it, nor push from nor into it), but is adequate if you are only interested in the recent history of a large project with a long history, and would want to send in fixes as patches.
I just tried the same in EF6 (code first entity rename). I simply renamed the class and added a migration using the package manager console and voila, a migration using RenameTable(...) was automatically generated for me. I have to admit that I made sure the only change to the entity was renaming it so no new columns or renamed columns so I cannot be certain if this is an EF6 thing or just that EF was (always) able to detect such simple migrations.
To me the key thing about this is: an InterruptedException is not anything going wrong, it is the thread doing what you told it to do. Therefore rethrowing it wrapped in a RuntimeException makes zero sense.
In many cases it makes sense to rethrow an exception wrapped in a RuntimeException when you say, I don't know what went wrong here and I can't do anything to fix it, I just want it to get out of the current processing flow and hit whatever application-wide exception handler I have so it can log it. That's not the case with an InterruptedException, it's just the thread responding to having interrupt() called on it, it's throwing the InterruptedException in order to help cancel the thread's processing in a timely way.
So propagate the InterruptedException, or eat it intelligently (meaning at a place where it will have accomplished what it was meant to do) and reset the interrupt flag. Note that the interrupt flag gets cleared when the InterruptedException gets thrown; the assumption the Jdk library developers make is that catching the exception amounts to handling it, so by default the flag is cleared.
So definitely the first way is better, the second posted example in the question is not useful unless you don't expect the thread to actually get interrupted, and interrupting it amounts to an error.
Here's an answer I wrote describing how interrupts work, with an example. You can see in the example code where it is using the InterruptedException to bail out of a while loop in the Runnable's run method.
Just send xml bytes directly:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests
xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text
{
"origin": "x.x.x.x",
"files": {},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "48",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
"Host": "httpbin.org",
"Content-Type": "application/xml"
},
"json": null,
"data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
You could use the ceiling
function; this portion of SQL code :
select ceiling(45.01), ceiling(45.49), ceiling(45.99);
will get you "46" each time.
For your update, so, I'd say :
Update product SET price = ceiling(45.01)
BTW : On MySQL, ceil
is an alias to ceiling
; not sure about other DB systems, so you might have to use one or the other, depending on the DB you are using...
Quoting the documentation :
CEILING(X)
Returns the smallest integer value not less than X.
And the given example :
mysql> SELECT CEILING(1.23);
-> 2
mysql> SELECT CEILING(-1.23);
-> -1
You can get the count by the below query (without * or any column names).
select from table_name;
So you want a stroke around the textview? Unfortunately there is no simple way to do it with the styling. You'll have to create another view and place your textview over-top, making the parent view (the one it's on top of) just a few pixels bigger - this should create an outline.
The second argument Title does not mean Title of the page - It is more of a definition/information for the state of that page
But we can still change the title using onpopstate event, and passing the title name not from the second argument, but as an attribute from the first parameter passed as object
Reference: http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/
update: Copied material that was on the R wiki at http://rwiki.sciviews.org/doku.php?id=tips:graphics-base:2yaxes, link now broken: also available from the wayback machine
(some material originally by Daniel Rajdl 2006/03/31 15:26)
Please note that there are very few situations where it is appropriate to use two different scales on the same plot. It is very easy to mislead the viewer of the graphic. Check the following two examples and comments on this issue (example1, example2 from Junk Charts), as well as this article by Stephen Few (which concludes “I certainly cannot conclude, once and for all, that graphs with dual-scaled axes are never useful; only that I cannot think of a situation that warrants them in light of other, better solutions.”) Also see point #4 in this cartoon ...
If you are determined, the basic recipe is to create your first plot, set par(new=TRUE)
to prevent R from clearing the graphics device, creating the second plot with axes=FALSE
(and setting xlab
and ylab
to be blank – ann=FALSE
should also work) and then using axis(side=4)
to add a new axis on the right-hand side, and mtext(...,side=4)
to add an axis label on the right-hand side. Here is an example using a little bit of made-up data:
set.seed(101)
x <- 1:10
y <- rnorm(10)
## second data set on a very different scale
z <- runif(10, min=1000, max=10000)
par(mar = c(5, 4, 4, 4) + 0.3) # Leave space for z axis
plot(x, y) # first plot
par(new = TRUE)
plot(x, z, type = "l", axes = FALSE, bty = "n", xlab = "", ylab = "")
axis(side=4, at = pretty(range(z)))
mtext("z", side=4, line=3)
twoord.plot()
in the plotrix
package automates this process, as does doubleYScale()
in the latticeExtra
package.
Another example (adapted from an R mailing list post by Robert W. Baer):
## set up some fake test data
time <- seq(0,72,12)
betagal.abs <- c(0.05,0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(0,1000,2000,3000,4000,5000,6000)
## add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 6) + 0.1)
## Plot first set of data and draw its axis
plot(time, betagal.abs, pch=16, axes=FALSE, ylim=c(0,1), xlab="", ylab="",
type="b",col="black", main="Mike's test data")
axis(2, ylim=c(0,1),col="black",las=1) ## las=1 makes horizontal labels
mtext("Beta Gal Absorbance",side=2,line=2.5)
box()
## Allow a second plot on the same graph
par(new=TRUE)
## Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15, xlab="", ylab="", ylim=c(0,7000),
axes=FALSE, type="b", col="red")
## a little farther out (line=4) to make room for labels
mtext("Cell Density",side=4,col="red",line=4)
axis(4, ylim=c(0,7000), col="red",col.axis="red",las=1)
## Draw the time axis
axis(1,pretty(range(time),10))
mtext("Time (Hours)",side=1,col="black",line=2.5)
## Add Legend
legend("topleft",legend=c("Beta Gal","Cell Density"),
text.col=c("black","red"),pch=c(16,15),col=c("black","red"))
Similar recipes can be used to superimpose plots of different types – bar plots, histograms, etc..
using https://github.com/nicfit/eyeD3
import eyed3
import os
for root, dirs, files in os.walk(folderp):
for file in files:
try:
if file.find(".mp3") < 0:
continue
path = os.path.abspath(os.path.join(root , file))
t = eyed3.load(path)
print(t.tag.title , t.tag.artist)
#print(t.getArtist())
except Exception as e:
print(e)
continue
Don't use the word "click" as the function name. It's a reserved keyword in JavaScript. In the bellow code I’ve used "hello" function instead of "click"
<html>
<head>
<title>Space Clicker</title>
</head>
<body>
<script type="text/javascript">
var clicks = 0;
function hello() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onclick="hello()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
</body></html>
I found the following commands will all return the full path of the parent directory of a Python 3.6 script.
Python 3.6 Script:
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
from pathlib import Path
#Get the absolute path of a Python3.6 script
dir1 = Path().resolve() #Make the path absolute, resolving any symlinks.
dir2 = Path().absolute() #See @RonKalian answer
dir3 = Path(__file__).parent.absolute() #See @Arminius answer
print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}')
Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()
This may be too basic (and perhaps assumable), but -
Fedora users can use:
sudo dnf install python-scipy
and then (For python3.x):
pip3 install scipy
or (For python2.7):
pip2 install scipy
Check this out,
body {
background-color: black;
background: url(img/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
You can have it go to the same page without specifying the url:
window.open('?','_self');
I'll just post the code to do this using the fluent API mapping.
public class User {
public int UserID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public ICollection<UserEmail> UserEmails { get; set; }
}
public class Email {
public int EmailID { get; set; }
public string Address { get; set; }
public ICollection<UserEmail> UserEmails { get; set; }
}
public class UserEmail {
public int UserID { get; set; }
public int EmailID { get; set; }
public bool IsPrimary { get; set; }
}
On your DbContext
derived class you could do this:
public class MyContext : DbContext {
protected override void OnModelCreating(DbModelBuilder builder) {
// Primary keys
builder.Entity<User>().HasKey(q => q.UserID);
builder.Entity<Email>().HasKey(q => q.EmailID);
builder.Entity<UserEmail>().HasKey(q =>
new {
q.UserID, q.EmailID
});
// Relationships
builder.Entity<UserEmail>()
.HasRequired(t => t.Email)
.WithMany(t => t.UserEmails)
.HasForeignKey(t => t.EmailID)
builder.Entity<UserEmail>()
.HasRequired(t => t.User)
.WithMany(t => t.UserEmails)
.HasForeignKey(t => t.UserID)
}
}
It has the same effect as the accepted answer, with a different approach, which is no better nor worse.
i wanted to ask if Android Devices uses the network time protocol (ntp) to synchronize the time.
For general time synchronization, devices with telephony capability, where the wireless provider provides NITZ information, will use NITZ. My understanding is that NTP is used in other circumstances: NITZ-free wireless providers, WiFi-only, etc.
Your cited blog post suggests another circumstance: on-demand time synchronization in support of GPS. That is certainly conceivable, though I do not know whether it is used or not.
Yes, you can do it by:
-- Install Atom
-- Install Python on your system. Atom requires the latest version of Python (currently 3.8.5). Note that Anaconda sometimes may not have this version, and depending on how you installed it, it may not have been added to the PATH. Install Python via https://www.python.org/ and make sure to check the option of "Add to PATH"
-- Install "scripts" on Atom via "Install packages"
-- Install any other autocomplete package like Kite on Atom if you want that feature.
-- Run it
I tried the normal way (I had Python installed via Anaconda) but Atom did not detect it & gave me an error when I tried to run Python. This is the way around it.
You are correct here:
Integer i = 0;
i = i + 1; // <- I think that this is somehow creating a new object!
First: Integer is immutable.
Second: the Integer class is not overriding the +
operator, there is autounboxing and autoboxing involved at that line (In older versions of Java you would get an error on the above line).
When you write i + 1
the compiler first converts the Integer to an (primitive) int
for performing the addition: autounboxing. Next, doing i = <some int>
the compiler converts from int
to an (new) Integer: autoboxing.
So +
is actually being applied to primitive int
s.
Make Sure You're Not Closing Database By using db_close() Before To Running Your Query:
If you're using multiple queries in a script even you're including other pages which contains queries or database connection, then it might be possible that at any place you use db_close() that would close your database connection so make sure you're not doing this mistake in your scripts.
For renaming the columns here is the simple one which will work for both Default(0,1,2,etc;)
and existing columns but not much useful for a larger data sets(having many columns).
For a larger data set we can slice the columns that we need and apply the below code:
df.columns = ['new_name','new_name1','old_name']
I think the best way to do this would be:
git diff remotes/origin/HEAD
Assuming that you have the this refspec registered. You should if you have cloned the repository, otherwise (i.e., if the repo was created de novo locally, and pushed to the remote), you need to add the refspec explicitly.
$last = count($arr_nav) - 1;
foreach ($arr_nav as $i => $row)
{
$isFirst = ($i == 0);
$isLast = ($i == $last);
echo ... $row['name'] ... $row['url'] ...;
}
Try:
import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(500);
}
Note:
Don't forget to include permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.VIBRATE"/>
I created a button...
This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button
element instead, you wouldn't have this problem:
<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
Connect
</button>
If you are going to continue using an a
element instead, at the very least you should give it a role
attribute set to "button"
and drop the href
attribute altogether:
<a role="button" ...>
Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault()
- here with event
being your click event.
I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.
Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.
(x + (x >> 31)) ^ (x >> 31);
This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.
export
is used to set environment variables. For example:
export EDITOR=pico
Will set your default text editor to be the pico
command.
I've found with 1.5 components that abstracting the styling from the DOM to work best in my async situation.
Example:
<div ng-style="{ 'background': $ctrl.backgroundUrl }"></div>
And in the controller, something likes this:
this.$onChanges = onChanges;
function onChanges(changes) {
if (changes.value.currentValue){
$ctrl.backgroundUrl = setBackgroundUrl(changes.value.currentValue);
}
}
function setBackgroundUrl(value){
return 'url(' + value.imgUrl + ')';
}
Either allocate the string on the stack on the caller side and pass it to your function:
void getStr(char *wordd, int length) {
...
}
int main(void) {
char wordd[10 + 1];
getStr(wordd, sizeof(wordd) - 1);
...
}
Or make the string static in getStr
:
char *getStr(void) {
static char wordd[10 + 1];
...
return wordd;
}
Or allocate the string on the heap:
char *getStr(int length) {
char *wordd = malloc(length + 1);
...
return wordd;
}
Config is written to .npmrc
files so just delete it. NPM looks up config in this order, setting in the next overwrites the previous one. So make sure there might be global config that usually is overwritten in per-project that becomes active after you have deleted the per-project config file. npm config list
will allways list the active config.
/path/to/npm/npmrc
)$PREFIX/etc/npmrc
)$HOME/.npmrc
)/path/to/my/project/.npmrc
)I have same problem but CleanUp eclipse option doesn't work for me.
1) install TortoiseSVN
2) Go to windows explorer and right click on your project directory
3 Choice CleanUp option (by checking break lock option)
It's works.
Hope this helps someone.
There is a substring function in XSLT. Example here.
This does work for a specific delimiter for a specific amount of characters between the delimiter. I had many issues attempting to use this in a for each loop where the position changed but the delimiter was the same. For example I was using the backslash as the delimiter and wanted to only use everything to the right of the backslash. The issue was that once the position was defined (71 characters from the beginning) it would use $pos as 71 every time regardless of where the delimiter actually was in the script. I found another method of using a delimiter and .split to break things up then used the split variable to call the sections For instance the first section was $variable[0] and the second section was $variable[1].
Code for your reference:
#include <iomanip>
#include <sstream>
...
string intToHexString(int intValue) {
string hexStr;
/// integer value to hex-string
std::stringstream sstream;
sstream << "0x"
<< std::setfill ('0') << std::setw(2)
<< std::hex << (int)intValue;
hexStr= sstream.str();
sstream.clear(); //clears out the stream-string
return hexStr;
}
Ack! Constant strings:
const char *strings[] = {"one","two","three"};
If I remember correctly.
Oh, and you want to use strcpy for assignment, not the = operator. strcpy_s is safer, but it's neither in C89 nor in C99 standards.
char arr[MAX_NUMBER_STRINGS][MAX_STRING_SIZE];
strcpy(arr[0], "blah");
Update: Thomas says strlcpy
is the way to go.
I have struggled on this same issue for several days. It can be solved by modifying the security user access properties of the file system folder on which your site is mapped. But IIS_IUSRS is not the only account you must authorize.
OR
Try this in your main js file:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method"
);
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
res.header("Allow", "GET, POST, OPTIONS, PUT, DELETE");
next();
});
This should solve your problem
Hope this can help you!
<input type="button" id="left" value="left" />
<input type="button" id="right" value="right" />
<img src="https://www.google.com/images/srpr/logo3w.png" id="image">
<script>
var angle = 0;
$('#left').on('click', function () {
angle -= 90;
$("#image").rotate(angle);
});
$('#right').on('click', function () {
angle += 90;
$("#image").rotate(angle);
});
</script>
Besides the solution of m79lkm above, my 2 cents on this topic is not to directly pipe the result in gzip but first dump it as a .sql file, and then gzip it. (Use && instead of | )
The dump itself will be faster. (for what I tested it was double as fast)
Otherwise you tables will be locked longer and the downtime/slow-responding of your application can bother the users. The mysqldump command is taking a lot of resources from your server.
So I would go for "&& gzip" instead of "| gzip"
Important: check for free disk space first with df -h
since you will need more then piping | gzip.
mysqldump -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql
-> which will also result in 1 file called dumpfilename.sql.gz
Furthermore the option --single-transaction
prevents the tables being locked but still result in a solid backup. So you might consider to use that option. See docs here
mysqldump --single-transaction -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql
Watch out!
If you have several script tags and your're searching an information in tag attributes for example, you have to use .length property with a for loop because it isn't a simple array but an HTMLCollection object.
https://developer.mozilla.org/en/DOM/HTMLCollection
If you use the foreach statement for(var i in yourList) it will return proterties and methods of the HTMLCollection in most browsers!
var scriptTags = document.getElementsByTagName("script");
for(var i = 0; i < scriptTags.length; i++)
alert(i); // Will print all your elements index (you can get src attribute value using scriptTags[i].attributes[0].value)
for(var i in scriptTags)
alert(i); // Will print "length", "item" and "namedItem" in addition to your elements!
Even if getElementsByTagName should return a NodeList, most browser are returning an HTMLCollection: https://developer.mozilla.org/en/DOM/document.getElementsByTagName
According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.
Here are the options in question :
-T seconds
--timeout=seconds
Set the network timeout to seconds seconds. This is equivalent to specifying
--dns-timeout
,--connect-timeout
, and--read-timeout
, all at the same time.
And for those three options :
--dns-timeout=seconds
Set the DNS lookup timeout to seconds seconds.
DNS lookups that don't complete within the specified time will fail.
By default, there is no timeout on DNS lookups, other than that implemented by system libraries.
--connect-timeout=seconds
Set the connect timeout to seconds seconds.
TCP connections that take longer to establish will be aborted.
By default, there is no connect timeout, other than that implemented by system libraries.
--read-timeout=seconds
Set the read (and write) timeout to seconds seconds.
The "time" of this timeout refers to idle time: if, at any point in the download, no data is received for more than the specified number of seconds, reading fails and the download is restarted.
This option does not directly affect the duration of the entire download.
I suppose using something like
wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run
should make sure there is no timeout before longer than the duration of your script.
(Yeah, that's probably the most brutal solution possible ^^ )
Locale locale = new Locale(langCode);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.locale = locale;
preferences.setLocalePref(langCode);
context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
Here, langCode is the required language code. You can save the language code as string in sharedPreferences. and you can call this code super.onCreate(savedInstanceState)
in onCreate
.
I've also been successful with this URL structure:
Base URL:
https://calendar.google.com/calendar/r/eventedit?
And let's say this is my event details:
Title: Event Title
Description: Example of some description. See more at https://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
Location: 123 Some Place
Date: February 22, 2020
Start Time: 10:00am
End Time: 11:30am
Timezone: America/New York (GMT -5)
I'd convert my details into these parameters (URL encoded):
text=Event%20Title
details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar
location=123%20Some%20Place%2C%20City
dates=20200222T100000/20200222T113000
ctz=America%2FNew_York
Example link:
Please note that since I've specified a timezone with the "ctz" parameter, I used the local times for the start and end dates. Alternatively, you can use UTC dates and exclude the timezone parameter, like this:
dates=20200222T150000Z/20200222T163000Z
Example link:
<a href="http://www.starfall.com/" target="_blank">Starfall</a>
Whether it opens in a tab or another window though is up to how a user has configured her browser.
Try the following:
....
character(len=30) :: filename ! length depends on expected names
integer :: inuit
....
do i=1,n
write(filename,'("output",i0,".txt")') i
open(newunit=iunit,file=filename,...)
....
close(iunit)
enddo
....
Where "..." means other appropriate code for your purpose.
Take a look at Serialization, a technique to "convert" an entire object to a byte stream. You may send it to the network or write it into a file and then restore it back to an object later.
$("#element").validate().valid()
You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.
Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };
JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);
This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.
Try CSS.
If you want to remove Horizontal
overflow-x: hidden;
And if you want to remove Vertical
overflow-y: hidden;
I got the same problem, but things got complicated when I added few other libraries like appcompat.v7, recyclerView, CardView.
Removing appcompat.v4 from lib did not work for me.
I had to create project from start and first step I did is to remove appcompat.v4 from libs folder, and this worked.
I had just started the project so creating a new project wasn't a big issue for me!!!
Try this...
<div class="row">
<div class="col-xs-3">
Menu
</div>
<div class="col-xs-9">
<div class="row">
<div class="col-sm-4 col-sm-push-8">
Right content
</div>
<div class="col-sm-8 col-sm-pull-4">
Content
</div>
</div>
</div>
</div>
In my case the issue didn't resolve by following any of the above methods. I had all the paths in my package config correct and the dll's were in place as referred, I was still getting run time error for System.Web.WebPages.Razor. I changed the localhost port number and this worked
I am not sure of why I had the issue and why changing the port number resolved it. Just posting this as I feel this might be useful for someone out there.
Here is more info. First you are dealing with a frozen distribution (frozen in this case means its parameters are set to specific values). To create a frozen distribution:
import scipy.stats
scipy.stats.norm(loc=100, scale=12)
#where loc is the mean and scale is the std dev
#if you wish to pull out a random number from your distribution
scipy.stats.norm.rvs(loc=100, scale=12)
#To find the probability that the variable has a value LESS than or equal
#let's say 113, you'd use CDF cumulative Density Function
scipy.stats.norm.cdf(113,100,12)
Output: 0.86066975255037792
#or 86.07% probability
#To find the probability that the variable has a value GREATER than or
#equal to let's say 125, you'd use SF Survival Function
scipy.stats.norm.sf(125,100,12)
Output: 0.018610425189886332
#or 1.86%
#To find the variate for which the probability is given, let's say the
#value which needed to provide a 98% probability, you'd use the
#PPF Percent Point Function
scipy.stats.norm.ppf(.98,100,12)
Output: 124.64498692758187
In Selenium Python it is:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
def get_selected_value_from_drop_down(self):
try:
select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
return select.first_selected_option.get_attribute("value")
except NoSuchElementException, e:
print "Element not found "
print e
If your using maven,
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<profiles>
<profile>dev</profile>
</profiles>
</configuration>
</plugin>
</plugins>
</build>
this set dev as active profile
./mvnw spring-boot:run
will have dev as active profile.
This might work for you
public void save(String fileName) throws FileNotFoundException {
FileOutputStream fout= new FileOutputStream (fileName);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(clubs);
fout.close();
}
To read back you can have
public void read(String fileName) throws FileNotFoundException {
FileInputStream fin= new FileInputStream (fileName);
ObjectInputStream ois = new ObjectInputStream(fin);
clubs= (ArrayList<Clubs>)ois.readObject();
fin.close();
}
i guess you're concatenating something in the loop, like
foreach($a as $b)
$string .= $b . ',';
much better is to collect items in an array and then join it with a delimiter you need
foreach($a as $b)
$result[] = $b;
$result = implode(',', $result);
this solves trailing and double delimiter problems that usually occur with concatenation
Easiest way excpecially if you don't know images widths is to put the caption in it's own div element an define it to be cleared:both !
...
<div class="pics">
<img class="marq" src="pic_1.jpg" />
<div class="caption">My image 1</div>
</div>
<div class="pics">
<img class="marq" src="pic_2.jpg" />
<div class="caption">My image 2</div>
</div>
...
and in style-block define
div.caption: {
float: left;
clear: both;
}
Alternatively, you can use np.shape(...)
For instance:
import numpy as np
a=[1,2,3]
and np.shape(a)
will give an output of (3,)
If you have vps or dedicated server, You can code your own module using C programming.
para.h
/*
* File: para.h
* Author: rahul
*
* Created on 10 February, 2016, 11:24 AM
*/
#ifndef PARA_H
#define PARA_H
#ifdef __cplusplus
extern "C" {
#endif
#define From "<[email protected]>"
#define To "<[email protected]>"
#define From_header "Rahul<[email protected]>"
#define TO_header "Mini<[email protected]>"
#define UID "smtp server account ID"
#define PWD "smtp server account PWD"
#define domain "dfgdfgdfg.com"
#ifdef __cplusplus
}
#endif
#endif
/* PARA_H */
main.c
/*
* File: main.c
* Author: rahul
*
* Created on 10 February, 2016, 10:29 AM
*/
#include <my_global.h>
#include <mysql.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "time.h"
#include "para.h"
/*
*
*/
my_bool SendEmail_init(UDF_INIT *initid,UDF_ARGS *arg,char *message);
void SendEmail_deinit(UDF_INIT *initid __attribute__((unused)));
char* SendEmail(UDF_INIT *initid, UDF_ARGS *arg,char *result,unsigned long *length, char *is_null,char* error);
/*
* base64
*/
int Base64encode_len(int len);
int Base64encode(char * coded_dst, const char *plain_src,int len_plain_src);
int Base64decode_len(const char * coded_src);
int Base64decode(char * plain_dst, const char *coded_src);
/* aaaack but it's fast and const should make it shared text page. */
static const unsigned char pr2six[256] =
{
/* ASCII table */
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
};
int Base64decode_len(const char *bufcoded)
{
int nbytesdecoded;
register const unsigned char *bufin;
register int nprbytes;
bufin = (const unsigned char *) bufcoded;
while (pr2six[*(bufin++)] <= 63);
nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
nbytesdecoded = ((nprbytes + 3) / 4) * 3;
return nbytesdecoded + 1;
}
int Base64decode(char *bufplain, const char *bufcoded)
{
int nbytesdecoded;
register const unsigned char *bufin;
register unsigned char *bufout;
register int nprbytes;
bufin = (const unsigned char *) bufcoded;
while (pr2six[*(bufin++)] <= 63);
nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
nbytesdecoded = ((nprbytes + 3) / 4) * 3;
bufout = (unsigned char *) bufplain;
bufin = (const unsigned char *) bufcoded;
while (nprbytes > 4) {
*(bufout++) =
(unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
*(bufout++) =
(unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
*(bufout++) =
(unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
bufin += 4;
nprbytes -= 4;
}
/* Note: (nprbytes == 1) would be an error, so just ingore that case */
if (nprbytes > 1) {
*(bufout++) =
(unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
}
if (nprbytes > 2) {
*(bufout++) =
(unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
}
if (nprbytes > 3) {
*(bufout++) =
(unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
}
*(bufout++) = '\0';
nbytesdecoded -= (4 - nprbytes) & 3;
return nbytesdecoded;
}
static const char basis_64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int Base64encode_len(int len)
{
return ((len + 2) / 3 * 4) + 1;
}
int Base64encode(char *encoded, const char *string, int len)
{
int i;
char *p;
p = encoded;
for (i = 0; i < len - 2; i += 3) {
*p++ = basis_64[(string[i] >> 2) & 0x3F];
*p++ = basis_64[((string[i] & 0x3) << 4) |
((int) (string[i + 1] & 0xF0) >> 4)];
*p++ = basis_64[((string[i + 1] & 0xF) << 2) |
((int) (string[i + 2] & 0xC0) >> 6)];
*p++ = basis_64[string[i + 2] & 0x3F];
}
if (i < len) {
*p++ = basis_64[(string[i] >> 2) & 0x3F];
if (i == (len - 1)) {
*p++ = basis_64[((string[i] & 0x3) << 4)];
*p++ = '=';
}
else {
*p++ = basis_64[((string[i] & 0x3) << 4) |
((int) (string[i + 1] & 0xF0) >> 4)];
*p++ = basis_64[((string[i + 1] & 0xF) << 2)];
}
*p++ = '=';
}
*p++ = '\0';
return p - encoded;
}
/*
end of base64
*/
const char* GetIPAddress(const char* target_domain) {
const char* target_ip;
struct in_addr *host_address;
struct hostent *raw_list = gethostbyname(target_domain);
int i = 0;
for (i; raw_list->h_addr_list[i] != 0; i++) {
host_address = raw_list->h_addr_list[i];
target_ip = inet_ntoa(*host_address);
}
return target_ip;
}
char * MailHeader(const char* from, const char* to, const char* subject, const char* mime_type, const char* charset) {
time_t now;
time(&now);
char *app_brand = "Codevlog Test APP";
char* mail_header = NULL;
char date_buff[26];
char Branding[6 + strlen(date_buff) + 2 + 10 + strlen(app_brand) + 1 + 1];
char Sender[6 + strlen(from) + 1 + 1];
char Recip[4 + strlen(to) + 1 + 1];
char Subject[8 + 1 + strlen(subject) + 1 + 1];
char mime_data[13 + 1 + 3 + 1 + 1 + 13 + 1 + strlen(mime_type) + 1 + 1 + 8 + strlen(charset) + 1 + 1 + 2];
strftime(date_buff, (33), "%a , %d %b %Y %H:%M:%S", localtime(&now));
sprintf(Branding, "DATE: %s\r\nX-Mailer: %s\r\n", date_buff, app_brand);
sprintf(Sender, "FROM: %s\r\n", from);
sprintf(Recip, "To: %s\r\n", to);
sprintf(Subject, "Subject: %s\r\n", subject);
sprintf(mime_data, "MIME-Version: 1.0\r\nContent-type: %s; charset=%s\r\n\r\n", mime_type, charset);
int mail_header_length = strlen(Branding) + strlen(Sender) + strlen(Recip) + strlen(Subject) + strlen(mime_data) + 10;
mail_header = (char*) malloc(mail_header_length);
memcpy(&mail_header[0], &Branding, strlen(Branding));
memcpy(&mail_header[0 + strlen(Branding)], &Sender, strlen(Sender));
memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender)], &Recip, strlen(Recip));
memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender) + strlen(Recip)], &Subject, strlen(Subject));
memcpy(&mail_header[0 + strlen(Branding) + strlen(Sender) + strlen(Recip) + strlen(Subject)], &mime_data, strlen(mime_data));
return mail_header;
}
my_bool SendEmail_init(UDF_INIT *initid,UDF_ARGS *arg,char *message){
if (!(arg->arg_count == 2)) {
strcpy(message, "Expected two arguments");
return 1;
}
arg->arg_type[0] = STRING_RESULT;// smtp server address
arg->arg_type[1] = STRING_RESULT;// email body
initid->ptr = (char*) malloc(2050 * sizeof (char));
memset(initid->ptr, '\0', sizeof (initid->ptr));
return 0;
}
void SendEmail_deinit(UDF_INIT *initid __attribute__((unused))){
if (initid->ptr) {
free(initid->ptr);
}
}
char* SendEmail(UDF_INIT *initid, UDF_ARGS *arg,char *result,unsigned long *length, char *is_null,char* error){
char *header = MailHeader(From_header, TO_header, "Hello Its a test Mail from Codevlog", "text/plain", "US-ASCII");
int connected_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
struct sockaddr_in addr;
memset(&addr, 0, sizeof (addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(25);
if (inet_pton(AF_INET, GetIPAddress(arg->args[0]), &addr.sin_addr) == 1) {
connect(connected_fd, (struct sockaddr*) &addr, sizeof (addr));
}
if (connected_fd != -1) {
int recvd = 0;
const char recv_buff[4768];
int sdsd;
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char buff[1000];
strcpy(buff, "EHLO "); //"EHLO sdfsdfsdf.com\r\n"
strcat(buff, domain);
strcat(buff, "\r\n");
send(connected_fd, buff, strlen(buff), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd2[1000];
strcpy(_cmd2, "AUTH LOGIN\r\n");
int dfdf = send(connected_fd, _cmd2, strlen(_cmd2), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd3[1000];
Base64encode(&_cmd3, UID, strlen(UID));
strcat(_cmd3, "\r\n");
send(connected_fd, _cmd3, strlen(_cmd3), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd4[1000];
Base64encode(&_cmd4, PWD, strlen(PWD));
strcat(_cmd4, "\r\n");
send(connected_fd, _cmd4, strlen(_cmd4), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd5[1000];
strcpy(_cmd5, "MAIL FROM: ");
strcat(_cmd5, From);
strcat(_cmd5, "\r\n");
send(connected_fd, _cmd5, strlen(_cmd5), 0);
char skip[1000];
sdsd = recv(connected_fd, skip, sizeof (skip), 0);
char _cmd6[1000];
strcpy(_cmd6, "RCPT TO: ");
strcat(_cmd6, To); //
strcat(_cmd6, "\r\n");
send(connected_fd, _cmd6, strlen(_cmd6), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd7[1000];
strcpy(_cmd7, "DATA\r\n");
send(connected_fd, _cmd7, strlen(_cmd7), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
send(connected_fd, header, strlen(header), 0);
send(connected_fd, arg->args[1], strlen(arg->args[1]), 0);
char _cmd9[1000];
strcpy(_cmd9, "\r\n.\r\n.");
send(connected_fd, _cmd9, sizeof (_cmd9), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
recvd += sdsd;
char _cmd10[1000];
strcpy(_cmd10, "QUIT\r\n");
send(connected_fd, _cmd10, sizeof (_cmd10), 0);
sdsd = recv(connected_fd, recv_buff + recvd, sizeof (recv_buff) - recvd, 0);
memcpy(initid->ptr, recv_buff, strlen(recv_buff));
*length = recvd;
}
free(header);
close(connected_fd);
return initid->ptr;
}
To configure your project go through this video: https://www.youtube.com/watch?v=Zm2pKTW5z98 (Send Email from MySQL on Linux) It will work for any mysql version (5.5, 5.6, 5.7)
I will resolve if any error appear in above code, Just Inform in comment
Thread.Sleep(50);
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.
This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
Thread.Join
A little helper function I use with some header checking safeguards to handle it all:
def appendDFToCSV_void(df, csvFilePath, sep=","):
import os
if not os.path.isfile(csvFilePath):
df.to_csv(csvFilePath, mode='a', index=False, sep=sep)
elif len(df.columns) != len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns):
raise Exception("Columns do not match!! Dataframe has " + str(len(df.columns)) + " columns. CSV file has " + str(len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns)) + " columns.")
elif not (df.columns == pd.read_csv(csvFilePath, nrows=1, sep=sep).columns).all():
raise Exception("Columns and column order of dataframe and csv file do not match!!")
else:
df.to_csv(csvFilePath, mode='a', index=False, sep=sep, header=False)
you should use fmod(a,b)
While abs(x%y) < abs(y) is true
mathematically, for floats
it may not be true numerically due to roundoff
.
For example, and assuming a platform on which a Python float
is an IEEE 754
double-precision number, in order that -1e-100 % 1e100
have the same sign as 1e100
, the computed result is -1e-100 + 1e100
, which is numerically exactly equal to 1e100
.
Function fmod()
in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100
in this case. Which approach is more appropriate depends on the application.
where x = a%b
is used for integer modulo
To import classes on the fly :
On OSX press Alt(Option) + Enter.
Get the same error while sending from outlook because of ssl. Tried setting EnableSSL = false resolved the issue.
example:
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("[email protected]", "xxxxx")
};
$sql = "SELECT count(*) FROM `table` WHERE foo = ?";
$result = $con->prepare($sql);
$result->execute([$bar]);
$number_of_rows = $result->fetchColumn();
Not the most elegant way to do it, plus it involves an extra query.
PDO has PDOStatement::rowCount()
, which apparently does not work in MySql. What a pain.
From the PDO Doc:
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
EDIT: The above code example uses a prepared statement, which is in many cases is probably unnecessary for the purpose of counting rows, so:
$nRows = $pdo->query('select count(*) from blah')->fetchColumn();
echo $nRows;
Just a side note for similar problem (If we don't want to loop through):
How to lookup a dictionary using a variable key within Jinja template?
Here is an example:
{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}
It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)
Alternatively, you can simply do
{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}
But it will spit an error when no key is found. So better to use get
in Jinja.
CMake 3.13 on Ubuntu 16.04
This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:
$ cat CMakeLists.txt
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE )
message("MY_VARIABLE evaluates to True")
endif()
$ mkdir build && cd build
$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
To enable this app-wide, I created a category on UIWindow:
@implementation UIWindow (Utils)
- (BOOL)canBecomeFirstResponder
{
return YES;
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake) {
// Do whatever you want here...
}
}
@end
Two very different types of Pipes Angular - Pipes and RxJS - Pipes
A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.
import { Component } from '@angular/core';
@Component({
selector: 'app-hero-birthday',
template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988
}
Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.
import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';
const source$: Observable<number> = range(0, 10);
source$.pipe(
map(x => x * 2),
filter(x => x % 3 === 0)
).subscribe(x => console.log(x));
The output for this in the console would be the following:
0
6
12
18
For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.
So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.
Use strptime to parse the time, and call time() on it to get the Unix timestamp.
You can't. Full stop.
switch
is only for integral types, if you want to branch depending on a string you need to use if/else
.
You need select privileges on All_users view
There's a BeyondCompare plugin as well. It opens the 2 files in a BeyondCompare
window. Pretty convenient to open files from the sublime window.
You will need BC3 installation present in the system. After installing the plugin, you will have to provide the path to the installation.
Example:
{
//Define a custom path to beyond compare
"beyond_compare_path": "G:/Softwares/Beyond Compare 3/BCompare.exe"
}
All the setting are stored in .metadata file in your workspace delete this and you are good to go
"If you start an android Service with startService(..)
that Service will remain running until you explicitly invoke stopService(..)
.
There are two reasons that a service can be run by the system. If someone calls Context.startService()
then the system will retrieve the service (creating it and calling its onCreate()
method if needed) and then call its onStartCommand(Intent, int, int)
method with the arguments supplied by the client. The service will at this point continue running until Context.stopService()
or stopSelf()
is called. Note that multiple calls to Context.startService()
do not nest (though they do result in multiple corresponding calls to onStartCommand()
), so no matter how many times it is started a service will be stopped once Context.stopService()
or stopSelf()
is called; however, services can use their stopSelf(int)
method to ensure the service is not stopped until started intents have been processed.
Clients can also use Context.bindService()
to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate()
while doing so), but does not call onStartCommand()
. The client will receive the IBinder
object that the service returns from its onBind(Intent)
method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the Service's IBinder
). Usually the IBinder
returned is for a complex interface that has been written in AIDL.
A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE
flag. Once neither of these situations hold, the Service's onDestroy()
method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy()
."
I suggest you to read the Enumeration: Traversing a Collection’s Elements part of the Collections Programming Guide for Cocoa. There is a sample code for your need.
This helped and it supports a BLOB/TEXT columns.
CREATE TEMPORARY TABLE temp_table
AS
SELECT * FROM source_table WHERE id=2;
UPDATE temp_table SET id=NULL WHERE id=2;
INSERT INTO source_table SELECT * FROM temp_table;
DROP TEMPORARY TABLE temp_table;
USE source_table;
spark-csv is part of core Spark functionality and doesn't require a separate library. So you could just do for example
df = spark.read.format("csv").option("header", "true").load("csvfile.csv")
In scala,(this works for any format-in delimiter mention "," for csv, "\t" for tsv etc)
val df = sqlContext.read.format("com.databricks.spark.csv")
.option("delimiter", ",")
.load("csvfile.csv")
In dplyr 0.3 this can be easily achieved using the distinct()
method.
Here is an example:
distinct_df = df %>% distinct(field1)
You can get a vector of the distinct values with:
distinct_vector = distinct_df$field1
You can also select a subset of columns at the same time as you perform the distinct()
call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:
distinct_df = df %>% distinct(field1) %>% select(field1)
distinct_vector = distinct_df$field1
Well, the basic premise here is: no, it is not secure yet.
Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.
The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.
As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.
Either that, or if you need that sort of security, and you need local storage, create a custom application...
You can do a relative redirect:
window.location.href = '../'; //one level up
or
window.location.href = '/path'; //relative to domain
JAX-WS - is Java API for the XML-Based Web Services - a standard way to develop a Web- Services in SOAP notation (Simple Object Access Protocol).
Calling of the Web Services is performed via remote procedure calls. For the exchange of information between the client and the Web Service is used SOAP protocol. Message exchange between the client and the server performed through XML- based SOAP messages.
Clients of the JAX-WS Web- Service need a WSDL file to generate executable code that the clients can use to call Web- Service.
JAX-RS - Java API for RESTful Web Services. RESTful Web Services are represented as resources and can be identified by Uniform Resource Identifiers (URI). Remote procedure call in this case is represented a HTTP- request and the necessary data is passed as parameters of the query. Web Services RESTful - more flexible, can use several different MIME- types. Typically used for XML data exchange or JSON (JavaScript Object Notation) data exchange...
In my case ; what solved my issue was.....
You may had json like this, the keys without " double quotations....
{ name: "test", phone: "2324234" }
So try any online Json Validator to make sure you have right syntax...
// Use this version to capture the full extended desktop (i.e. multiple screens)
Bitmap screenshot = new Bitmap(SystemInformation.VirtualScreen.Width,
SystemInformation.VirtualScreen.Height,
PixelFormat.Format32bppArgb);
Graphics screenGraph = Graphics.FromImage(screenshot);
screenGraph.CopyFromScreen(SystemInformation.VirtualScreen.X,
SystemInformation.VirtualScreen.Y,
0,
0,
SystemInformation.VirtualScreen.Size,
CopyPixelOperation.SourceCopy);
screenshot.Save("Screenshot.png", System.Drawing.Imaging.ImageFormat.Png);
I had all the correct packages and usings, but had to built first before I could get GetOwinContext()
to work.
You can use Perl::Tidy for Perl.
This happens because the .xib has got a stale link to the old App Delegate which does not exist anymore. I fixed it like thus:
This a simple loop to tokenise with only standard library files
#include <iostream.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <conio.h>
class word
{
public:
char w[20];
word()
{
for(int j=0;j<=20;j++)
{w[j]='\0';
}
}
};
void main()
{
int i=1,n=0,j=0,k=0,m=1;
char input[100];
word ww[100];
gets(input);
n=strlen(input);
for(i=0;i<=m;i++)
{
if(context[i]!=' ')
{
ww[k].w[j]=context[i];
j++;
}
else
{
k++;
j=0;
m++;
}
}
}
Use the range's NumberFormat
property to force the format of the range like this:
Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
In mongodb _id field is reserved for primary key. Mongodb use an internal ObjectId value if you don't define it in your object and also create an index to ensure performance.
But you can put your own unique value for _id and Mongodb will use it instead of making one for you. And even if you want to use multiple field as primary key you can use an object:
{ _id : { a : 1, b: 1} }
Just be careful when creating these ids that the order of keys (a and b in the example) matters, if you swap them around, it is considered a different object.
I can suggest this -hack- ;).
select
left(txt, abs(len(txt + ',') - 2))
from
t;
into Chrome, right click -> Inspect Element. Go to the tab active tracking of resources and if you have not already. Now the left hand sidebar thingy down until you see "Cookies", click below your domain name and to remove a cookie just right-click on it and "Delete"
That would work depending on what client.get does when passed undefined as its first parameter.
Something like this would be safer:
app.get('/:key?', function(req, res, next) {
var key = req.params.key;
if (!key) {
next();
return;
}
client.get(key, function(err, reply) {
if(client.get(reply)) {
res.redirect(reply);
}
else {
res.render('index', {
link: null
});
}
});
});
There's no problem in calling next() inside the callback.
According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.
Great news, the fix is coming in March 2018, see this link: https://developers.google.com/web/updates/2018/01/devtools
"Local Overrides let you make changes in DevTools, and keep those changes across page loads. Previously, any changes that you made in DevTools would be lost when you reloaded the page. Local Overrides work for most file types
How it works:
To set up Local Overrides:
UPDATE (March 19, 2018): It's live, detailed explanations here: https://developers.google.com/web/updates/2018/01/devtools#overrides
yes - the engine will throw different exceptions for different conditions.
you will change this part to catch the exception and do something different
EXCEPTION
WHEN OTHERS THEN
here is a reference
http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/07_errs.htm
There aren't many JavaScript decoders.
There is one at http://www.webqr.com/index.html
The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.
if you used vue-cli and webpack when you created your project.
you can use just
npm run build command in command line, and it will create dist folder in your project. Just upload content of this folder to your ftp and done.
Using webpack CLI: (--version, -v Show version number [boolean])
webpack --version
or:
webpack -v
Using npm list command:
npm list webpack
Results in name@version-range
:
<projectName>@<projectVersion> /path/to/project
+-- webpack@<version-range>
Using yarn list command:
yarn list webpack
Webpack 2 introduced Configuration Types.
Instead of exporting a configuration object, you may return a function which accepts an environment as argument. When running webpack, you may specify build environment keys via
--env
, such as--env.production
or--env.platform=web
.
We will use a build environment key called --env.version
.
webpack --env.version $(webpack --version)
or:
webpack --env.version $(webpack -v)
For this to work we will need to do two things:
Change our webpack.config.js
file and use DefinePlugin.
The DefinePlugin allows you to create global constants which can be configured at compile time.
-module.exports = {
+module.exports = function(env) {
+ return {
plugins: [
new webpack.DefinePlugin({
+ WEBPACK_VERSION: JSON.stringify(env.version) //<version-range>
})
]
+ };
};
Now we can access the global constant like so:
console.log(WEBPACK_VERSION);
Using npm view command will return the latest version available on the registry:
npm view [<@scope>/]<name>[@<version>] [<field>[.<subfield>]...]
For webpack use:
npm view webpack version
Try resetting your network settings
Settings -> General -> Reset -> Reset Network Settings
And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".
http://support.apple.com/kb/ts2529
This one worked for me.
actually this depends on what DBMS you are using but in regular SQL convert(varchar,DateColumn,101)
will change the DATETIME format to date (one day)
so:
SELECT
sum(amount)
FROM
sales
GROUP BY
convert(varchar,created,101)
the magix number 101
is what date format it is converted to