I had this issue with offline mode enable. I disabled offline mode and synced.
File > Settings
.Build, Execution, Deployment > Gradle
.Offline work
.Annotations come from the support's library
which are packaged in android.support.annotation
.
As another option you can use @NonNull
annotation which denotes that a parameter, field or method return value can never be null.
It is imported from import android.support.annotation.NonNull;
It works, when you use both lines:
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"
Use
$(document).ready(function() {
$('#createFormId').on('show.bs.modal', function(event) {
$("#cafeId").val($(event.relatedTarget).data('id'));
});
});
From your code
<input type=button value="Select" onClick="sendValue(this.form.details);"
Im not sure that your this.form.details
valid or not.
IF it's valid, have a look in window.opener.document.getElementById('details').value = selvalue;
I can't found an input's id contain details
I'm just found only id=sku1
(recommend you to add "
like id="sku1"
).
And from your id it's hardcode. Let's see how to do with dynamic when a child has callback to update some textbox on the parent Take a look at here.
<html>
<head>
<script>
function callFromDialog(id,data){ //for callback from the dialog
document.getElementById(id).value = data;
// do some thing other if you want
}
function choose(id){
var URL = "secondPage.html?id=" + id + "&dummy=avoid#";
window.open(URL,"mywindow","menubar=1,resizable=1,width=350,height=250")
}
</script>
</head>
<body>
<input id="tbFirst" type="text" /> <button onclick="choose('tbFirst')">choose</button>
<input id="tbSecond" type="text" /> <button onclick="choose('tbSecond')">choose</button>
</body>
</html>
Look in function choose
I'm sent an id of textbox to the popup window (don't forget to add dummy data at last of URL param like &dummy=avoid#
)
<html>
<head>
<script>
function goSelect(data){
var idFromCallPage = getUrlVars()["id"];
window.opener.callFromDialog(idFromCallPage,data); //or use //window.opener.document.getElementById(idFromCallPage).value = data;
window.close();
}
function getUrlVars(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
</head>
<body>
<a href="#" onclick="goSelect('Car')">Car</a> <br />
<a href="#" onclick="goSelect('Food')">Food</a> <br />
</body>
</html>
I have add function getUrlVars for get URL param that the parent has pass to child.
Okay, when select data in the popup, for this case it's will call function goSelect
In that function will get URL param to sent back.
And when you need to sent back to the parent just use window.opener and the name of function like window.opener.callFromDialog
By fully is window.opener.callFromDialog(idFromCallPage,data);
Or if you want to use window.opener.document.getElementById(idFromCallPage).value = data;
It's ok too.
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
If you want to get unix timestamp, then you need to use:
timestamp=$(date +%s)
%T
will give you just the time; same as %H:%M:%S
(via http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/)
Assuming you use Python 2.7 (not 3):
print "I have", card.price
(as mentioned above).
print "I have %s" % card.price
(using string formatting)
print " ".join(map(str, ["I have", card.price]))
(by joining lists)
There are a lot of ways to do the same, actually. I would prefer the second one.
You can try this
func getTime() -> (hour:Int, min:Int, sec:Int) {
let currentDateTime = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour,.Minute,.Second], fromDate: currentDateTime)
let hour = components.hour
let min = components.minute
let sec = components.second
return (hour,min,sec)
}
Now call that method and receive the date with hour,min and second
let currentTime = self.getTime()
print("Hour: \(currentTime.hour) Min: \(currentTime.min) Sec: \(currentTime.sec))")
Just had a look at the DOM (document.scripts[1].attributes) of this page that uses google analytics. I can tell you that google is using async="".
[type="text/javascript", async="", src="http://www.google-analytics.com/ga.js"]
Modify the batch file to START
both programs, instead of START
ing one and CALL
ing another
start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1"
start "" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow
If you run it like this, no CMD window will stay open after starting the program.
Example downloader class without Alamofire:
class Downloader {
class func load(URL: NSURL) {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("Success: \(statusCode)")
// This is your file-variable:
// data
}
else {
// Failure
println("Failure: %@", error.localizedDescription);
}
})
task.resume()
}
}
This is how to use it in your own code:
class Foo {
func bar() {
if var URL = NSURL(string: "http://www.mywebsite.com/myfile.pdf") {
Downloader.load(URL)
}
}
}
Swift 3 Version
Also note to download large files on disk instead instead in memory. see `downloadTask:
class Downloader {
class func load(url: URL, to localUrl: URL, completion: @escaping () -> ()) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = try! URLRequest(url: url, method: .get)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Success: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
completion()
} catch (let writeError) {
print("error writing file \(localUrl) : \(writeError)")
}
} else {
print("Failure: %@", error?.localizedDescription);
}
}
task.resume()
}
}
Package mlr
includes createDummyFeatures
for this purpose:
library(mlr)
df <- data.frame(var = sample(c("A", "B", "C"), 10, replace = TRUE))
df
# var
# 1 B
# 2 A
# 3 C
# 4 B
# 5 C
# 6 A
# 7 C
# 8 A
# 9 B
# 10 C
createDummyFeatures(df, cols = "var")
# var.A var.B var.C
# 1 0 1 0
# 2 1 0 0
# 3 0 0 1
# 4 0 1 0
# 5 0 0 1
# 6 1 0 0
# 7 0 0 1
# 8 1 0 0
# 9 0 1 0
# 10 0 0 1
createDummyFeatures
drops original variable.
https://www.rdocumentation.org/packages/mlr/versions/2.9/topics/createDummyFeatures
.....
A solution (for WPF) without WaitOne because it can cause an AbandonedMutexException. This solution uses the Mutex constructor that returns the createdNew boolean to check if the mutex is already created. It also uses the GetType().GUID so renaming an executable doesn't allow multiple instances.
Global vs local mutex see note in: https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8
private Mutex mutex;
private bool mutexCreated;
public App()
{
string mutexId = $"Global\\{GetType().GUID}";
mutex = new Mutex(true, mutexId, out mutexCreated);
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (!mutexCreated)
{
MessageBox.Show("Already started!");
Shutdown();
}
}
Because Mutex implements IDisposable it is released automatically but for completeness call dispose:
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
mutex.Dispose();
}
Move everything into a base class and add the allowEveryoneRule from the accepted answer. Also added ReleaseMutex though it doesn't look like it's really needed because it is released automatically by the OS (what if the application crashes and never calls ReleaseMutex would you need to reboot?).
public class SingleApplication : Application
{
private Mutex mutex;
private bool mutexCreated;
public SingleApplication()
{
string mutexId = $"Global\\{GetType().GUID}";
MutexAccessRule allowEveryoneRule = new MutexAccessRule(
new SecurityIdentifier(WellKnownSidType.WorldSid, null),
MutexRights.FullControl,
AccessControlType.Allow);
MutexSecurity securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
// initiallyOwned: true == false + mutex.WaitOne()
mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings);
}
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
if (mutexCreated)
{
try
{
mutex.ReleaseMutex();
}
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
mutex.Dispose();
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (!mutexCreated)
{
MessageBox.Show("Already started!");
Shutdown();
}
}
}
You would want to replace all spaces with
(non-breaking space) and all new lines \n
with <br>
(line break in html). This should achieve the result you're looking for.
body = body.replace(' ', ' ').replace('\n', '<br>');
Something of that nature.
subprocess.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
import subprocess
command = "ntpq -p" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
#Launch the shell command:
output = process.communicate()
print output[0]
In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:
command = ["ntpq", "-p"] # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)
If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:
import subprocess
command = "ntpq -p" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
#Launch the shell command:
output, error = process.communicate()
Exact same thing, just omit the -c
option. Apache's docs on it here.
htpasswd /etc/apache2/.htpasswd newuser
Also, htpasswd
typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).
Its easy go to File - Data Modeler - Import - Data Dictionary - DB connection - OK
One of the best online tools currently available to extract pdf fonts is http://www.pdfconvertonline.com/extract-pdf-fonts-online.html
Normally, you do something like this:
def myFunction(a,b,c):
if not isinstance(a, int):
raise TypeError("Expected int, got %s" % (type(a),))
if b <= 0 or b >= 10:
raise ValueError("Value %d out of range" % (b,))
if not c:
raise ValueError("String was empty")
# Rest of function
Unfortunately there is nothing like this in TypeScript (more details here: https://github.com/Microsoft/TypeScript/issues/467)
But to get around this you can change your params to be an interface:
export interface IErrorParams {
message: string;
title?: string;
autoHideAfter?: number;
}
export interface INotificationService {
error(params: IErrorParams);
}
//then to call it:
error({message: 'msg', autoHideAfter: 42});
I use:
from pathlib import Path
import platform
import tempfile
tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())
This is because on MacOS, i.e. Darwin, tempfile.gettempdir()
and os.getenv('TMPDIR')
return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'
; it is one that I do not always want.
Your second example does not work because there is no operator +
for two string literals. Note that a string literal is not of type string
, but instead is of type const char *
. Your second example will work if you revise it like this:
const string message = string("Hello") + ",world" + exclam;
Based on Evil Trout's answer you might wanna create a category to make it easier to use across multiple applications.
Header file:
@interface UITextField (PaddingText)
-(void) setLeftPadding:(int) paddingValue;
-(void) setRightPadding:(int) paddingValue;
@end
Implementation file:
#import "UITextField+PaddingText.h"
@implementation UITextField (PaddingText)
-(void) setLeftPadding:(int) paddingValue
{
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, paddingValue, self.frame.size.height)];
self.leftView = paddingView;
self.leftViewMode = UITextFieldViewModeAlways;
}
-(void) setRightPadding:(int) paddingValue
{
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, paddingValue, self.frame.size.height)];
self.rightView = paddingView;
self.rightViewMode = UITextFieldViewModeAlways;
}
@end
Usage Example
#import "UITextField+PaddingText.h"
[self.YourTextField setLeftPadding:20.0f];
Hope it helps you out guys
Cheers
int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
Difference in works. If you use click(), you can add several functions, but if you use an attribute, only one function will be executed - the last one.
HTML
<span id="JQueryClick">Click #JQuery</span> </br>
<span id="JQueryAttrClick">Click #Attr</span> </br>
JavaScript
$('#JQueryClick').click(function(){alert('1')})
$('#JQueryClick').click(function(){alert('2')})
$('#JQueryAttrClick').attr('onClick'," alert('1')" ) //This doesn't work
$('#JQueryAttrClick').attr('onClick'," alert('2')" )
If we are talking about performance, in any case directly using is always faster, but using of an attribute, you will be able to assign only one function.
There are several good answers here, so let me provide a terrible one:
: you can type in anything below, doesnt have to match anything
yum whatprovides "me with a life"
: result of the above (some liberties taken with spacing):
Loaded plugins: fastestmirror
base | 3.6 kB 00:00
extras | 3.4 kB 00:00
updates | 3.4 kB 00:00
(1/4): extras/7/x86_64/primary_db | 166 kB 00:00
(2/4): base/7/x86_64/group_gz | 155 kB 00:00
(3/4): updates/7/x86_64/primary_db | 9.1 MB 00:04
(4/4): base/7/x86_64/primary_db | 5.3 MB 00:05
Determining fastest mirrors
* base: mirrors.xmission.com
* extras: mirrors.xmission.com
* updates: mirrors.xmission.com
base/7/x86_64/filelists_db | 6.2 MB 00:02
extras/7/x86_64/filelists_db | 468 kB 00:00
updates/7/x86_64/filelists_db | 5.3 MB 00:01
No matches found
: the key result above is that "primary_db" files were downloaded
: filelists are downloaded EVEN IF you have keepcache=0 in your yum.conf
: note you can limit this to "primary_db.sqlite" if you really want
find /var/cache/yum -name '*.sqlite'
: if you download/install a new repo, run the exact same command again
: to get the databases for the new repo
: if you know sqlite you can stop reading here
: if not heres a sample command to dump the contents
echo 'SELECT packages.name, GROUP_CONCAT(files.name, ", ") AS files FROM files JOIN packages ON (files.pkgKey = packages.pkgKey) GROUP BY packages.name LIMIT 10;' | sqlite3 -line /var/cache/yum/x86_64/7/base/gen/primary_db.sqlite
: remove "LIMIT 10" above for the whole list
: format chosen for proof-of-concept purposes, probably can be improved a lot
If you want to get whole response in JSON format, try this:
I have tried a new way to get whole response from server in JSON format without creating any model class. I am not using any model class to get data from server because I don't know what response I will get or it may change according to requirements.
this is JSON response:
{"contacts": [
{
"id": "c200",
"name": "sunil",
"email": "[email protected]",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "[email protected]",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
.
.
.
]}
In your API interface change the parameter
public interface ApiInterface {
@POST("/index.php/User/login")//your api link
@FormUrlEncoded
Call<Object> getmovies(@Field("user_email_address") String title,
@Field("user_password") String body);
}
in your main activity where you are calling this
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call call = apiService.getmovies("[email protected]","123456");
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.e("TAG", "response 33: "+new Gson().toJson(response.body()) );
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("TAG", "onFailure: "+t.toString() );
// Log error here since request failed
}
});
after that you can normally get parameter using JSON object and JSON array
You don't need to use array_push() function, you can assign new value with new key directly to the array like..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
function chunkArrayInGroups(arr, size) {
var newArr=[];
for (var i=0; i < arr.length; i+= size){
newArr.push(arr.slice(i,i+size));
}
return newArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);
You can use the following code.
public static class TimeSpanExtensions
{
public static String Verbose(this TimeSpan timeSpan)
{
var hours = timeSpan.Hours;
var minutes = timeSpan.Minutes;
if (hours > 0) return String.Format("{0} hours {1} minutes", hours, minutes);
return String.Format("{0} minutes", minutes);
}
}
Even if that topic is quite old, I'd like to add something.
If you overwrite equals
for you classes, so it compares your getId
, you can use:
customer = new Customer(id);
customers.get(customers.indexOf(customer));
Of course, you'd have to check for an IndexOutOfBounds
-Exception, which oculd be translated into a null pointer or a custom CustomerNotFoundException
.
A common use of mysqldump is for making a backup of an entire database:
shell> mysqldump db_name > backup-file.sql
You can load the dump file back into the server like this:
UNIX
shell> mysql db_name < backup-file.sql
The same in Windows command prompt:
mysql -p -u [user] [database] < backup-file.sql
PowerShell
C:\> cmd.exe /c "mysql -u root -p db_name < backup-file.sql"
MySQL command line
mysql> use db_name;
mysql> source backup-file.sql;
I like to use form model binding
so I can easily populate a form's fields with corresponding value, so I follow this approach (using a user
model for example):
@if(isset($user))
{{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
@else
{{ Form::open(['route' => 'createroute']) }}
@endif
{{ Form::text('fieldname1', Input::old('fieldname1')) }}
{{ Form::text('fieldname2', Input::old('fieldname2')) }}
{{-- More fields... --}}
{{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}
So, for example, from a controller, I basically use the same form for creating and updating, like:
// To create a new user
public function create()
{
// Load user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate');
}
// To update an existing user (load to edit)
public function edit($id)
{
$user = User::find($id);
// Load user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate')->with('user', $user);
}
This answer could be really late, but its useful.
You can play youtube videos in the app itself using android-youtube-player.
Some code snippets:
To play a youtube video that has a video id in the url, you simply call the OpenYouTubePlayerActivity
intent
Intent intent = new Intent(null, Uri.parse("ytv://"+v), this,
OpenYouTubePlayerActivity.class);
startActivity(intent);
where v is the video id.
Add the following permissions in the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
and also declare this activity in the manifest file:
<activity
android:name="com.keyes.youtube.OpenYouTubePlayerActivity"></activity>
Further information can be obtained from the first portions of this code file.
Hope that helps anyone!
In my case the error was:
Error CS1617 Invalid option 'latest' for /langversion; must be ISO-1, ISO-2, Default or an integer in range 1 to 6.
I opened my .csproj file with notepad and I saw this line:
<PropertyGroup>
<LangVersion>latest</LangVersion>
</PropertyGroup>
I changed the latest for an integer in range 1 to 6
<LangVersion>6</LangVersion>
The error disappeared!
Try writing it in a new file..
f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()
Just use novalidate in your form.
<form name="myForm" role="form" novalidate class="form-horizontal" ng-hide="formMain">
Cheers!!!
It is possible to do this, but most likely your host implemented mod_security
for a reason. Be sure they approve of you disabling it for your own site.
That said, this should do it;
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
If ds is the DataSet, you can access the CustomerID column of the first row in the first table with something like:
DataRow dr = ds.Tables[0].Rows[0];
Console.WriteLine(dr["CustomerID"]);
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server
argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
Open port 9418 on your firewall - it's a custom port that Git uses to communicate on and it's often not open on a corporate or private firewall.
header.php has the title tag set to <title>%TITLE%</title>;
the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later. then, you use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
For more reference, click PHP - how to change title of the page AFTER including header.php?
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
The way I often deal with the situation you describe is to use the .to_csv()
method and write to stdout:
import sys
df.to_csv(sys.stdout)
Update: it should now be possible to just use None
instead of sys.stdout
with similar effect!
This should dump the whole dataframe, including the entirety of any strings. You can use the to_csv parameters to configure column separators, whether the index is printed, etc. It will be less pretty than rendering it properly though.
I posted this originally in answer to the somewhat-related question at Output data from all columns in a dataframe in pandas
We can directly subtract dates to get difference in Days.
SET SERVEROUTPUT ON ;
DECLARE
V_VAR NUMBER;
BEGIN
V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
DBMS_OUTPUT.PUT_LINE(V_VAR);
END;
I believe the main benefit of using the literal form (ie, "foo" rather than new String("foo")) is that all String literals are 'interned' by the VM. In other words it is added to a pool such that any other code that creates the same string will use the pooled String rather than creating a new instance.
To illustrate, the following code will print true for the first line, but false for the second:
System.out.println("foo" == "foo");
System.out.println(new String("bar") == new String("bar"));
I was looking for a list multiplied by itself with only unique combinations, which is provided as this function.
import itertools
itertools.combinations(list, n_times)
Here as an excerpt from the Python docs on itertools
That might help you find what your looking for.
Combinatoric generators:
Iterator | Results
-----------------------------------------+----------------------------------------
product(p, q, ... [repeat=1]) | cartesian product, equivalent to a
| nested for-loop
-----------------------------------------+----------------------------------------
permutations(p[, r]) | r-length tuples, all possible
| orderings, no repeated elements
-----------------------------------------+----------------------------------------
combinations(p, r) | r-length tuples, in sorted order, no
| repeated elements
-----------------------------------------+----------------------------------------
combinations_with_replacement(p, r) | r-length tuples, in sorted order,
| with repeated elements
-----------------------------------------+----------------------------------------
product('ABCD', repeat=2) | AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations('ABCD', 2) | AB AC AD BA BC BD CA CB CD DA DB DC
combinations('ABCD', 2) | AB AC AD BC BD CD
combinations_with_replacement('ABCD', 2) | AA AB AC AD BB BC BD CC CD DD
Here's a short means I used to reduce the size of Images that have a high byteCount
(basically pixels)
fun resizeImage(image: Bitmap): Bitmap {
val width = image.width
val height = image.height
val scaleWidth = width / 10
val scaleHeight = height / 10
if (image.byteCount <= 1000000)
return image
return Bitmap.createScaledBitmap(image, scaleWidth, scaleHeight, false)
}
This returns a scaled Bitmap that is over 10 times smaller than the Bitmap
passed as a parameter. Might not be the most ideal solution but it works.
Install Body Parser by below command
$ npm install --save body-parser
Configure Body Parser
const bodyParser = require('body-parser');
app.use(bodyParser);
app.use(bodyParser.json()); //Make sure u have added this line
app.use(bodyParser.urlencoded({ extended: false }));
var1 and var2 is an Instance variables of ClassA. Create an Instance of ClassB and when calling the methodA it will check the methodA in Child class (ClassB) first, If methodA is not present in ClassB you need to invoke the ClassA by using the super() method which will get you all the methods implemented in ClassA. Now, you can access all the methods and attributes of ClassB.
class ClassA(object):
def __init__(self):
self.var1 = 1
self.var2 = 2
def methodA(self):
self.var1 = self.var1 + self.var2
return self.var1
class ClassB(ClassA):
def __init__(self):
super().__init__()
print("var1",self.var1)
print("var2",self.var2)
object1 = ClassB()
sum = object1.methodA()
print(sum)
# Let's add key:value to a dictionary, the functional way
# Create your dictionary class
class my_dictionary(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
# Main Function
dict_obj = my_dictionary()
limit = int(input("Enter the no of key value pair in a dictionary"))
c=0
while c < limit :
dict_obj.key = input("Enter the key: ")
dict_obj.value = input("Enter the value: ")
dict_obj.add(dict_obj.key, dict_obj.value)
c += 1
print(dict_obj)
In python 3 or above, math class has the following functions
import math
math.log2(x)
math.log10(x)
math.log1p(x)
or you can generally use math.log(x, base)
for any base you want.
In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command
Select multiple lines by clicking first line then holding shift and clicking last line. Then press:
CTRL+SHIFT+L
or on MAC: CMD+SHIFT+L (as per comments)
Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.
Now you can edit multiple lines, move cursors etc. for all selected lines.
Yet another answer (in January 2018) to the old question (in January 2009).
The specification of Java properties file is described in the JavaDoc of java.util.Properties.load(java.io.Reader)
. One problem is that the specification is a bit complicated than the first impression we may have. Another problem is that some answers here arbitrarily added extra specifications - for example, ;
and '
are regarded as starters of comment lines but they should not be. Double/single quotations around property values are removed but they should not be.
The following are points to be considered.
\n
, \r
, \r\n
or the end of the stream.\
.
, \u0020
), tab (\t
, \u0009
) and form feed (\f
, \u000C
).=
is used as the separator between a key and a value.:
is used as the separator between a key and a value, too.#
or !
as its first non-white space characters, meaning leading white spaces before #
or !
are allowed.\
.=
, :
and white spaces can be embedded in a key if they are escaped by backslashes.\r
and \n
escape sequences.\uxxxx
is used to represent a Unicode character.So, for example, if test.properties
has the following content:
# A comment line that starts with '#'.
# This is a comment line having leading white spaces.
! A comment line that starts with '!'.
key1=value1
key2 : value2
key3 value3
key\
4=value\
4
\u006B\u0065\u00795=\u0076\u0061\u006c\u0075\u00655
\k\e\y\6=\v\a\lu\e\6
\:\ \= = \\colon\\space\\equal
it should be interpreted as the following key-value pairs.
+------+--------------------+
| KEY | VALUE |
+------+--------------------+
| key1 | value1 |
| key2 | value2 |
| key3 | value3 |
| key4 | value4 |
| key5 | value5 |
| key6 | value6 |
| : = | \colon\space\equal |
+------+--------------------+
PropertiesLoader
class in Authlete.Authlete NuGet package can interpret the format of the specification. The example code below:
using System;
using System.IO;
using System.Collections.Generic;
using Authlete.Util;
namespace MyApp
{
class Program
{
public static void Main(string[] args)
{
string file = "test.properties";
IDictionary<string, string> properties;
using (TextReader reader = new StreamReader(file))
{
properties = PropertiesLoader.Load(reader);
}
foreach (var entry in properties)
{
Console.WriteLine($"{entry.Key} = {entry.Value}");
}
}
}
}
will generate this output:
key1 = value1
key2 = value2
key3 = value3
key4 = value4
key5 = value5
key6 = value6
: = = \colon\space\equal
An equivalent example in Java is as follows:
import java.util.*;
import java.io.*;
public class Program
{
public static void main(String[] args) throws IOException
{
String file = "test.properties";
Properties properties = new Properties();
try (Reader reader = new FileReader(file))
{
properties.load(reader);
}
for (Map.Entry<Object, Object> entry : properties.entrySet())
{
System.out.format("%s = %s\n", entry.getKey(), entry.getValue());
}
}
}
The source code, PropertiesLoader.cs
, can be found in authlete-csharp. xUnit tests for PropertiesLoader
are written in PropertiesLoaderTest.cs
.
You can cast an integer to a string in this way
intval::text
and so in your case
SELECT * FROM table WHERE <some integer>::text = 'string of numbers'
3306
and change it to 3307
I prefer this one-liner:
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "dismissKeyboardFromView:"))
Just put that in the override viewDidLoad function in whichever subclassed UIViewController you want it to occur, and then put the following code in a new empty file in your project called "UIViewController+dismissKeyboard.swift":
import UIKit
extension UIViewController {
// This function is called when the tap is recognized
func dismissKeyboardFromView(sender: UITapGestureRecognizer?) {
let view = sender?.view
view?.endEditing(true)
}
}
Also make sure that the name of the variable is not some kind of a language keyword. For instance, the following produces the same type of error:
var history = [];
history.push("what a mess");
replacing it for:
var history123 = [];
history123.push("pray for a better language");
works as expected.
Do you want to keep your database on mobile? Use sqlite instead of mysql.
If the idea is to keep database on server and access from mobile. Use a webservice to fetch/ modify data.
My case was different but it might be the same case for others
for those who still couldn't find a solution and tried everything above, if you're using the adapter inside fragment then the reason it's not working fragment could be recreating so the adapter is recreating everytime the fragment recreate
you should verify if the adapter and objects list are null before initializing
if(adapter == null){_x000D_
adapter = new CustomListAdapter(...);_x000D_
}_x000D_
..._x000D_
_x000D_
if(objects == null){_x000D_
objects = new ArrayList<>();_x000D_
}
_x000D_
You can convert your .ui files to an executable python file using the below command..
pyuic4 -x form1.ui > form1.py
Now you can straightaway execute the python file as
python3(whatever version) form1.py
You can import this file and you can use it.
Collected ideas from multiple C++ sources and put it into a nice, still quite simple example for getters/setters in C++:
class Canvas { public:
void resize() {
cout << "resize to " << width << " " << height << endl;
}
Canvas(int w, int h) : width(*this), height(*this) {
cout << "new canvas " << w << " " << h << endl;
width.value = w;
height.value = h;
}
class Width { public:
Canvas& canvas;
int value;
Width(Canvas& canvas): canvas(canvas) {}
int & operator = (const int &i) {
value = i;
canvas.resize();
return value;
}
operator int () const {
return value;
}
} width;
class Height { public:
Canvas& canvas;
int value;
Height(Canvas& canvas): canvas(canvas) {}
int & operator = (const int &i) {
value = i;
canvas.resize();
return value;
}
operator int () const {
return value;
}
} height;
};
int main() {
Canvas canvas(256, 256);
canvas.width = 128;
canvas.height = 64;
}
Output:
new canvas 256 256
resize to 128 256
resize to 128 64
You can test it online here: http://codepad.org/zosxqjTX
PS: FO Yvette <3
For anyone looking to style child elements of a :host
here is an example of how to use ::ng-deep
:host::ng-deep <child element>
e.g :host::ng-deep span { color: red; }
As others said /deep/
is deprecated
okay, thx a lot now i use sth like this:
public static String[] removeElements(String[] input, String deleteMe) {
if (input != null) {
List<String> list = new ArrayList<String>(Arrays.asList(input));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(deleteMe)) {
list.remove(i);
}
}
return list.toArray(new String[0]);
} else {
return new String[0];
}
}
You can use checkedTextView instead.
http://developer.android.com/reference/android/widget/CheckedTextView.html
I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or similar software) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).
Sparse checkouts are now in Git 1.7.
Also see the question “Is it possible to do a sparse checkout without checking out the whole repository first?”.
Note that sparse checkouts still require you to download the whole repository, even though some of the files Git downloads won't end up in your working tree.
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
Finally, I had to delete the .android
folder and create new one. It seems that the files got corrupted
You would need to use the following markup. If you want to float any menu items to the right, create a separate <ul class="nav navbar-nav">
with navbar-right
class to it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Project name</a>_x000D_
</div>_x000D_
<div class="collapse navbar-collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li class="active"><a href="#">Home</a></li>_x000D_
<li><a href="#about">About</a></li>_x000D_
_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="#contact">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
System.IO.Stream stream = new System.IO.MemoryStream();
You can verify where your Setting.xml
is by pressing shortcut Ctrl+3
, you will see Quick Access
on top right side of Eclipse
, then search setting.xml
in searchbox. If you got setting.xml it will show up in search. Click that, and it will open the window showing directory path wherever it is stored. Your Maven Global Settings should be as such:
Global Setting
C:\maven\apache-maven-3.5.0\conf\settings.xml
User Setting
%userprofile%\\.m2\setting.xml
You can use global setting usually and leave the second option user setting
untouched. Store your setting.xml in Global Setting
If you really want to avoid touching this code, you can use Powermockito (PowerMock for Mockito).
With this, amongst many other things, you can mock the construction of new objects in a very easy way.
The general methodology would be to iterate through the ArrayList
, and insert the values into the HashMap
. An example is as follows:
HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
productMap.put(product.getProductCode(), product);
}
I changed a bit but the result is beautiful.
.child {
width: 0px;
height: 0px;
opacity: 0;
}
.parent:hover child {
width: 150px;
height: 300px;
opacity: .9;
}
Thank you to everyone.
Some "Advanced" features
If you only want to fetch the Google user id, name and picture for a visitor of your web app - here is my pure PHP service side solution for the year 2020 with no external libraries used -
If you read the Using OAuth 2.0 for Web Server Applications guide by Google (and beware, Google likes to change links to its own documentation), then you have to perform only 2 steps:
One of the returned tokens is called "id_token" and contains the user id, name and photo of the visitor.
Here is the PHP code of a web game by me. Initially I was using Javascript SDK, but then I have noticed that fake user data could be passed to my web game, when using client side SDK only (especially the user id, which is important for my game), so I have switched to using PHP on the server side:
<?php
const APP_ID = '1234567890-abcdefghijklmnop.apps.googleusercontent.com';
const APP_SECRET = 'abcdefghijklmnopq';
const REDIRECT_URI = 'https://the/url/of/this/PHP/script/';
const LOCATION = 'Location: https://accounts.google.com/o/oauth2/v2/auth?';
const TOKEN_URL = 'https://oauth2.googleapis.com/token';
const ERROR = 'error';
const CODE = 'code';
const STATE = 'state';
const ID_TOKEN = 'id_token';
# use a "random" string based on the current date as protection against CSRF
$CSRF_PROTECTION = md5(date('m.d.y'));
if (isset($_REQUEST[ERROR]) && $_REQUEST[ERROR]) {
exit($_REQUEST[ERROR]);
}
if (isset($_REQUEST[CODE]) && $_REQUEST[CODE] && $CSRF_PROTECTION == $_REQUEST[STATE]) {
$tokenRequest = [
'code' => $_REQUEST[CODE],
'client_id' => APP_ID,
'client_secret' => APP_SECRET,
'redirect_uri' => REDIRECT_URI,
'grant_type' => 'authorization_code',
];
$postContext = stream_context_create([
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($tokenRequest)
]
]);
# Step #2: send POST request to token URL and decode the returned JWT id_token
$tokenResult = json_decode(file_get_contents(TOKEN_URL, false, $postContext), true);
error_log(print_r($tokenResult, true));
$id_token = $tokenResult[ID_TOKEN];
# Beware - the following code does not verify the JWT signature!
$userResult = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', $id_token)[1]))), true);
$user_id = $userResult['sub'];
$given_name = $userResult['given_name'];
$family_name = $userResult['family_name'];
$photo = $userResult['picture'];
if ($user_id != NULL && $given_name != NULL) {
# print your web app or game here, based on $user_id etc.
exit();
}
}
$userConsent = [
'client_id' => APP_ID,
'redirect_uri' => REDIRECT_URI,
'response_type' => 'code',
'scope' => 'profile',
'state' => $CSRF_PROTECTION,
];
# Step #1: redirect user to a the Google page asking for user consent
header(LOCATION . http_build_query($userConsent));
?>
You could use a PHP library to add additional security by verifying the JWT signature. For my purposes it was unnecessary, because I trust that Google will not betray my little web game by sending fake visitor data.
Also, if you want to get more personal data of the visitor, then you need a third step:
const USER_INFO = 'https://www.googleapis.com/oauth2/v3/userinfo?access_token=';
const ACCESS_TOKEN = 'access_token';
# Step #3: send GET request to user info URL
$access_token = $tokenResult[ACCESS_TOKEN];
$userResult = json_decode(file_get_contents(USER_INFO . $access_token), true);
Or you could get more permissions on behalf of the user - see the long list at the OAuth 2.0 Scopes for Google APIs doc.
Finally, the APP_ID and APP_SECRET constants used in my code - you get it from the Google API console:
React-Redux connect
is used to update store for every actions.
import { connect } from 'react-redux';
const AppContainer = connect(
mapStateToProps,
mapDispatchToProps
)(App);
export default AppContainer;
It's very simply and clearly explained in this blog.
You can clone github project or copy paste the code from that blog to understand the Redux connect.
Most of you are wrong. If you want to close existing activity stack regardless of what's in there and create new root, correct set of flags is the following:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
public static final int FLAG_ACTIVITY_CLEAR_TASK
Added in API level 11If set in an Intent passed to
Context.startActivity()
, this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction withFLAG_ACTIVITY_NEW_TASK
.
I think this is what you want, I already tested this code and works
The tools used are: (all these tools can be downloaded as Nuget packages)
http://fluentassertions.codeplex.com/
http://autofixture.codeplex.com/
https://nuget.org/packages/AutoFixture.AutoMoq
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
var sut = fixture.CreateAnonymous<Transfer>();
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
.Throws<System.IO.IOException>();
sut.Invoking(x =>
x.TransferFiles(
myInterface.Object,
It.IsAny<string>(),
It.IsAny<string>()
))
.ShouldThrow<System.IO.IOException>();
Edited:
Let me explain:
When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer
So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code
When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs
In this case your external dependency is IFileConnection
so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected
var fixture = new Fixture().Customize(new AutoMoqCustomization());
: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
: This freezes the IFileConnection
dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object
var sut = fixture.CreateAnonymous<Transfer>();
: Here AutoFixture is creating the SUT for us
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>();
Here you are configuring the dependency to throw an exception whenever the Get
method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception
sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();
: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles
real method from the SUT and as parameters it receives the mocked IFileConnection
so whenever you call the IFileConnection.Get
in the normal flow of your SUT TransferFiles
method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>()
(from the FluentAssertions library)
References recommended:
http://martinfowler.com/articles/mocksArentStubs.html
http://misko.hevery.com/code-reviewers-guide/
http://misko.hevery.com/presentations/
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.
LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());
This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:
In LinkedListNode:
public String toString(){
return "LinkedListNode with data: " + getData();
}
In LinkedList:
public int size(){
int currentSize = 0;
LinkedListNode current = head;
while(current != null){
currentSize = currentSize + 1;
current = current.getNext();
}
return currentSize;
}
public String toString(){
return "LinkedList with " + size() + "elements.";
}
public void printList(){
System.out.println("Contents of " + toString());
LinkedListNode current = head;
while(current != null){
System.out.println(current.toString());
current = current.getNext();
}
}
We experienced the SecurityError: The operation is insecure when a user disabled their cookies prior to visiting our site, any subsequent XHR requests trying to use the session would obviously fail and cause this error.
Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?
You need to only grab the element with an appropriate jQuery selector and then the .val()
method to get the string contained in the input textbox and then call the .length
on that string.
$('input:text').val().length
However, be warned that if the selector matches multiple inputs, .val()
will only return the value of the first textbox. You can also change the selector to get a more specific element but keep the :text
to ensure it's an input textbox.
On another note, to get the length of a string contained in another, non-input element, you can use the .text()
function to get the string and then use .length
on that string to find its length.
There is a good stackoverflow answer here by Mark Rajcok:
AngularJS directive controllers requiring parent directive controllers?
with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/
<div ng-controller="MyCtrl">
<div screen>
<div component>
<div widget>
<button ng-click="widgetIt()">Woo Hoo</button>
</div>
</div>
</div>
</div>
JavaScript
var myApp = angular.module('myApp',[])
.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomethingScreeny = function() {
alert("screeny!");
}
}
}
})
.directive('component', function() {
return {
scope: true,
require: '^screen',
controller: function($scope) {
this.componentFunction = function() {
$scope.screenCtrl.doSomethingScreeny();
}
},
link: function(scope, element, attrs, screenCtrl) {
scope.screenCtrl = screenCtrl
}
}
})
.directive('widget', function() {
return {
scope: true,
require: "^component",
link: function(scope, element, attrs, componentCtrl) {
scope.widgetIt = function() {
componentCtrl.componentFunction();
};
}
}
})
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
Using match()
and Number()
to return a number
variable:
Number(("data-123").match(/\d+$/));
// strNum = 123
Here's what the statement above does...working middle-out:
str.match(/\d+$/)
- returns an array containing matches to any length of numbers at the end of str
. In this case it returns an array containing a single string item ['123']
.Number()
- converts it to a number type. Because the array returned from .match()
contains a single element Number()
will return the number.Typing q
starts macro recording, and the recording stops when the user hits q
again.
As Joey Adams mentioned, to disable recording, add the following line to .vimrc
in your home directory:
map q <Nop>
<div *ngFor="let celeb of singers">
<p [ngClass]="{
'text-success':celeb.country === 'USA',
'text-secondary':celeb.country === 'Canada',
'text-danger':celeb.country === 'Puorto Rico',
'text-info':celeb.country === 'India'
}">{{ celeb.artist }} ({{ celeb.country }})
</p>
</div>
There is one way to implement multiple interface.
Just extend one interface from another or create interface that extends predefined interface Ex:
public interface PlnRow_CallBack extends OnDateSetListener {
public void Plan_Removed();
public BaseDB getDB();
}
now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces
public class Calculator extends FragmentActivity implements PlnRow_CallBack {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
@Override
public void Plan_Removed() {
}
@Override
public BaseDB getDB() {
}
}
hope this helps
Pulling data type from information_schema
is possible, but not convenient (requires joining several columns with a case
statement). Alternatively one can use format_type
built-in function to do that, but it works on internal type identifiers that are visible in pg_attribute
but not in information_schema
. Example
SELECT a.attname as column_name, format_type(a.atttypid, a.atttypmod) AS data_type
FROM pg_attribute a JOIN pg_class b ON a.attrelid = b.relfilenode
WHERE a.attnum > 0 -- hide internal columns
AND NOT a.attisdropped -- hide deleted columns
AND b.oid = 'my_table'::regclass::oid; -- example way to find pg_class entry for a table
Based on https://gis.stackexchange.com/a/97834.
MD5 has its weaknesses (see Wikipedia), so there are some projects, which try to precompute Hashes. Wikipedia does also hint at some of these projects. One I know of (and respect) is ophrack. You can not tell the user their own password, but you might be able to tell them a password that works. But i think: Just mail thrm a new password in case they forgot.
The following function works for textfiles and binary files (returns only position in byte-count though), it does have the benefit to find strings even if they would overlap a line or buffer and would not be found when searching line- or buffer-wise.
def fnd(fname, s, start=0):
with open(fname, 'rb') as f:
fsize = os.path.getsize(fname)
bsize = 4096
buffer = None
if start > 0:
f.seek(start)
overlap = len(s) - 1
while True:
if (f.tell() >= overlap and f.tell() < fsize):
f.seek(f.tell() - overlap)
buffer = f.read(bsize)
if buffer:
pos = buffer.find(s)
if pos >= 0:
return f.tell() - (len(buffer) - pos)
else:
return -1
The idea behind this is:
I used something like this to find signatures of files inside larger ISO9660 files, which was quite fast and did not use much memory, you can also use a larger buffer to speed things up.
SELECT * from
(
SELECT yr as YEAR, COUNT(title) as TCOUNT
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr
order by TCOUNT desc
) res
where rownum < 2
should call the function properly; like- Fibonacci:input
Try
SELECT table.* FROM table
WHERE otherField = 'otherValue'
GROUP BY table.fieldWantedToBeDistinct
limit x
See man git merge (HOW TO RESOLVE CONFLICTS):
After seeing a conflict, you can do two things:
Decide not to merge. The only clean-ups you need are to reset the index file to the HEAD commit to reverse 2. and to clean up working tree changes made by 2. and 3.; git-reset --hard can be used for this.
Resolve the conflicts. Git will mark the conflicts in the working tree. Edit the files into shape and git add them to the index. Use git commit to seal the deal.
And under TRUE MERGE (to see what 2. and 3. refers to):
When it is not obvious how to reconcile the changes, the following happens:
The HEAD pointer stays the same.
The MERGE_HEAD ref is set to point to the other branch head.
Paths that merged cleanly are updated both in the index file and in your working tree.
...
So: use git reset --hard
if you want to remove the stash changes from your working tree, or git reset
if you want to just clean up the index and leave the conflicts in your working tree to merge by hand.
Under man git stash (OPTIONS, pop) you can read in addition:
Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards.
As many people have noted, the average case performance for quicksort is faster than mergesort. But this is only true if you are assuming constant time to access any piece of memory on demand.
In RAM this assumption is generally not too bad (it is not always true because of caches, but it is not too bad). However if your data structure is big enough to live on disk, then quicksort gets killed by the fact that your average disk does something like 200 random seeks per second. But that same disk has no trouble reading or writing megabytes per second of data sequentially. Which is exactly what mergesort does.
Therefore if data has to be sorted on disk, you really, really want to use some variation on mergesort. (Generally you quicksort sublists, then start merging them together above some size threshold.)
Furthermore if you have to do anything with datasets of that size, think hard about how to avoid seeks to disk. For instance this is why it is standard advice that you drop indexes before doing large data loads in databases, and then rebuild the index later. Maintaining the index during the load means constantly seeking to disk. By contrast if you drop the indexes, then the database can rebuild the index by first sorting the information to be dealt with (using a mergesort of course!) and then loading it into a BTREE datastructure for the index. (BTREEs are naturally kept in order, so you can load one from a sorted dataset with few seeks to disk.)
There have been a number of occasions where understanding how to avoid disk seeks has let me make data processing jobs take hours rather than days or weeks.
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
I had this issue, but with the timestamps
function. It was autogenerating an index on updated_at that exceeded the 63 character limit:
def change
create_table :toooooooooo_loooooooooooooooooooooooooooooong do |t|
t.timestamps
end
end
Index name 'index_toooooooooo_loooooooooooooooooooooooooooooong_on_updated_at' on table 'toooooooooo_loooooooooooooooooooooooooooooong' is too long; the limit is 63 characters
I tried to use timestamps
to specify the index name:
def change
create_table :toooooooooo_loooooooooooooooooooooooooooooong do |t|
t.timestamps index: { name: 'too_loooooooooooooooooooooooooooooong_updated_at' }
end
end
However, this tries to apply the index name to both the updated_at
and created_at
fields:
Index name 'too_long_updated_at' on table 'toooooooooo_loooooooooooooooooooooooooooooong' already exists
Finally I gave up on timestamps
and just created the timestamps the long way:
def change
create_table :toooooooooo_loooooooooooooooooooooooooooooong do |t|
t.datetime :updated_at, index: { name: 'too_long_on_updated_at' }
t.datetime :created_at, index: { name: 'too_long_on_created_at' }
end
end
This works but I'd love to hear if it's possible with the timestamps
method!
you can try this function for multi-purpose
function ManageData($table_name='',$condition=array(),$udata=array(),$is_insert=false){
$resultArr = array();
$ci = & get_instance();
if($condition && count($condition))
$ci->db->where($condition);
if($is_insert)
{
$ci->db->insert($table_name,$udata);
return 0;
}
else
{
$ci->db->update($table_name,$udata);
return 1;
}
}
List installed dependencies:
composer show -i
composer show -i -t
-i
short for --installed
.
-t
short for --tree
.
I like @sjr's answer however I prefer xargs vs -exec. I find xargs more versatile. For example with -P we can take advantage of multiple CPUs when it makes sense to do so.
find . -name '*.pdf' | xargs -P 5 -I % pdftotext % - | grep --with-filename --label="{}" --color "pattern"
All these solutions are absolutely horrid. Just convert your SVG to a PNG and use the vanilla <Image/>
component. The fact that react-native still does not support SVG images in the Image
component is a joke. You should never install an additional library for such a simple task. Use https://svgtopng.com/
"sqllite" dosn't have "TRUNCATE " order like than mysql, then we have to get other way... this function (reset_table) frist delete all data in table and then reset AUTOINCREMENT key in table.... now you can use this function every where you want...
example :
private SQLiteDatabase mydb;
private final String dbPath = "data/data/your_project_name/databases/";
private final String dbName = "your_db_name";
public void reset_table(String table_name){
open_db();
mydb.execSQL("Delete from "+table_name);
mydb.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE name='"+table_name+"';");
close_db();
}
public void open_db(){
mydb = SQLiteDatabase.openDatabase(dbPath + dbName + ".db", null, SQLiteDatabase.OPEN_READWRITE);
}
public void close_db(){
mydb.close();
}
You can pass it like this
let param: any = {'userId': 2};
this.http.get(`${ApiUrl}`, {params: param})
To get the current route based on the URL (more reliable in case of forwards):
public function getCurrentRoute(Request $request)
{
$pathInfo = $request->getPathInfo();
$routeParams = $this->router->match($pathInfo);
$routeName = $routeParams['_route'];
if (substr($routeName, 0, 1) === '_') {
return;
}
unset($routeParams['_route']);
$data = [
'name' => $routeName,
'params' => $routeParams,
];
return $data;
}
The only issue I see are relative links and templates not being properly loaded because of this.
from the docs regarding HTML5 mode
Relative links
Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (
<base href="/my-base">
) or you must use absolute urls (starting with/
) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.
In your case you can add a forward slash /
in href
attributes ($location.path
does this automatically) and also to templateUrl
when configuring routes. This avoids routes like example.com/tags/another
and makes sure templates load properly.
Here's an example that works:
<div>
<a href="/">Home</a> |
<a href="/another">another</a> |
<a href="/tags/1">tags/1</a>
</div>
<div ng-view></div>
And
app.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.when('/tags/:tagId', {
templateUrl: '/partials/template2.html',
controller: 'ctrl2'
})
.when('/another', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.otherwise({ redirectTo: '/' });
});
If using Chrome you will need to run this from a server.
I know this question is ancient and has an accepted answer, but I found a better solution to the problem. I am posting it here so I don't create a duplicate question, and the solution is still available to others.
Switch the order of the elements. Use the :before
pseudo-element for the content that should be underneath, and adjust margins to compensate. The margin cleanup can be messy, but the desired z-index
will be preserved.
I've tested this with IE8 and FF3.6 successfully.
unsorted_list.sort(key=lambda x: x[3])
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
use join()
, don't rely on the ,
for formatting, and also print
automatically puts the cursor on a newline every time, so no need of adding another '\n'
in your print
.
In [24]: for x in board:
print " ".join(map(str,x))
....:
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 3 2 1 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
You can give this a try using recursion. This will download them in sync, one after another until it completes downloading the whole list.
var queue = ['url/links/go/here'];
ProcessScripts(function() { // All done do what ever you want
}, 0);
function ProcessScripts(cb, index) {
getScript(queue[index], function() {
index++;
if (index === queue.length) { // Reached the end
cb();
} else {
return ProcessScripts(cb, index);
}
});
}
function getScript(script, callback) {
$.getScript(script, function() {
callback();
});
}
If you are using NodeJS, you can use the build-in util function:
import * as util from "util";
util.format('My string: %s', 'foo');
Document can be found here: https://nodejs.org/api/util.html#util_util_format_format_args
if name in ("Jesse", "jesse"):
would be the correct way to do it.
Although, if you want to use or
, the statement would be
if name == 'Jesse' or name == 'jesse':
>>> ("Jesse" or "jesse")
'Jesse'
evaluates to 'Jesse'
, so you're essentially not testing for 'jesse'
when you do if name == ("Jesse" or "jesse")
, since it only tests for equality to 'Jesse'
and does not test for 'jesse'
, as you observed.
round(..)
function returning a floatThat float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)
See the discussion here for details.
The following is my understanding var reading answer above and google.
# coding:utf-8
r"""
@update: 2017-01-09 14:44:39
@explain: str, unicode, bytes in python2to3
#python2 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 7: ordinal not in range(128)
#1.reload
#importlib,sys
#importlib.reload(sys)
#sys.setdefaultencoding('utf-8') #python3 don't have this attribute.
#not suggest even in python2 #see:http://stackoverflow.com/questions/3828723/why-should-we-not-use-sys-setdefaultencodingutf-8-in-a-py-script
#2.overwrite /usr/lib/python2.7/sitecustomize.py or (sitecustomize.py and PYTHONPATH=".:$PYTHONPATH" python)
#too complex
#3.control by your own (best)
#==> all string must be unicode like python3 (u'xx'|b'xx'.encode('utf-8')) (unicode 's disappeared in python3)
#see: http://blog.ernest.me/post/python-setdefaultencoding-unicode-bytes
#how to Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence
#http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence
"""
from __future__ import print_function
import json
a = {"b": u"??"} # add u for python2 compatibility
print('%r' % a)
print('%r' % json.dumps(a))
print('%r' % (json.dumps(a).encode('utf8')))
a = {"b": u"??"}
print('%r' % json.dumps(a, ensure_ascii=False))
print('%r' % (json.dumps(a, ensure_ascii=False).encode('utf8')))
# print(a.encode('utf8')) #AttributeError: 'dict' object has no attribute 'encode'
print('')
# python2:bytes=str; python3:bytes
b = a['b'].encode('utf-8')
print('%r' % b)
print('%r' % b.decode("utf-8"))
print('')
# python2:unicode; python3:str=unicode
c = b.decode('utf-8')
print('%r' % c)
print('%r' % c.encode('utf-8'))
"""
#python2
{'b': u'\u4e2d\u6587'}
'{"b": "\\u4e2d\\u6587"}'
'{"b": "\\u4e2d\\u6587"}'
u'{"b": "\u4e2d\u6587"}'
'{"b": "\xe4\xb8\xad\xe6\x96\x87"}'
'\xe4\xb8\xad\xe6\x96\x87'
u'\u4e2d\u6587'
u'\u4e2d\u6587'
'\xe4\xb8\xad\xe6\x96\x87'
#python3
{'b': '??'}
'{"b": "\\u4e2d\\u6587"}'
b'{"b": "\\u4e2d\\u6587"}'
'{"b": "??"}'
b'{"b": "\xe4\xb8\xad\xe6\x96\x87"}'
b'\xe4\xb8\xad\xe6\x96\x87'
'??'
'??'
b'\xe4\xb8\xad\xe6\x96\x87'
"""
This is a direct string representation techniques : I see a lot of solutions mentioned, but I think most are looking at split. Split however does it at every occurrence of "." . What you would rather be looking for is partition.
string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]
You can use textract module in python
Textract
for install
pip install textract
for read pdf
import textract
text = textract.process('path/to/pdf/file', method='pdfminer')
For detail Textract
Some times appeared if you declare a constant in the header file without static notation. like this
const int k = 10;
it should be:
static const int k = 10;
You don't need to override onBackPressed()
- it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed()
whenever you want to "programatically press" the back button.
That would only result to finish()
being called, though ;)
I think you're confused with what the back button does. By default, it's just a call to finish()
, so it just exits the current activity. If you have something behind that activity, that screen will show.
What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.
I think that LINQ join clause isn't the correct solution to this problem, because of join clause purpose isn't to accumulate data in such way as required for this task solution. The code to merge created separate collections becomes too complicated, maybe it is OK for learning purposes, but not for real applications. One of the ways how to solve this problem is in the code below:
class Program
{
static void Main(string[] args)
{
List<FirstName> firstNames = new List<FirstName>();
firstNames.Add(new FirstName { ID = 1, Name = "John" });
firstNames.Add(new FirstName { ID = 2, Name = "Sue" });
List<LastName> lastNames = new List<LastName>();
lastNames.Add(new LastName { ID = 1, Name = "Doe" });
lastNames.Add(new LastName { ID = 3, Name = "Smith" });
HashSet<int> ids = new HashSet<int>();
foreach (var name in firstNames)
{
ids.Add(name.ID);
}
foreach (var name in lastNames)
{
ids.Add(name.ID);
}
List<FullName> fullNames = new List<FullName>();
foreach (int id in ids)
{
FullName fullName = new FullName();
fullName.ID = id;
FirstName firstName = firstNames.Find(f => f.ID == id);
fullName.FirstName = firstName != null ? firstName.Name : string.Empty;
LastName lastName = lastNames.Find(l => l.ID == id);
fullName.LastName = lastName != null ? lastName.Name : string.Empty;
fullNames.Add(fullName);
}
}
}
public class FirstName
{
public int ID;
public string Name;
}
public class LastName
{
public int ID;
public string Name;
}
class FullName
{
public int ID;
public string FirstName;
public string LastName;
}
If real collections are large for HashSet formation instead foreach loops can be used the code below:
List<int> firstIds = firstNames.Select(f => f.ID).ToList();
List<int> LastIds = lastNames.Select(l => l.ID).ToList();
HashSet<int> ids = new HashSet<int>(firstIds.Union(LastIds));//Only unique IDs will be included in HashSet
There is a library for this BarCode PHP. You just need to include a few files:
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
You can generate many types of barcodes, namely 1D or 2D. Add the required library:
require_once('class/BCGcode39.barcode.php');
Generate the colours:
// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);
After you have added all the codes, you will get this way:
Example
Since several have asked for an example here is what I was able to do to get it done
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
require_once('class/BCGcode128.barcode.php');
header('Content-Type: image/png');
$color_white = new BCGColor(255, 255, 255);
$code = new BCGcode128();
$code->parse('HELLO');
$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
If you want to actually create the image file so you can save it then change
$drawing = new BCGDrawing('', $color_white);
to
$drawing = new BCGDrawing('image.png', $color_white);
If you are using a named instance, the port you using likely is 1434, instead of 1433, so please check that out using telnet or netstat aforementioned too.
This may be a really late response but here is a solution that works. This line only recognizes th existance of files! It will not give you a false positive if directories exist.
if find /path/to/check/* -maxdepth 0 -type f | read
then echo "Files Exist"
fi
Here's another two examples.
To output the day, month, and year, you can use:
select STR_TO_DATE('14/02/2015', '%d/%m/%Y');
Which produces:
2015-02-14
To also output the time, you can use:
select STR_TO_DATE('14/02/2017 23:38:12', '%d/%m/%Y %T');
Which produces:
2017-02-14 23:38:12
I came by the same error on an old 2010 Exchange Server. A service(Exchange mailbox replication service) was giving out the above error and the migration process could not be continued. Searching through the internet, i came by this link which stated the below:
The Exchange GRE fails to open when installed for the first time or if any changes are made to the IIS server. It fails with snap-in error and when you try to open the snap-in page, the following content is displayed:
This collection already contains an address with scheme http. There can be at most one address per scheme in this collection. If your service is being hosted in IIS you can fix the problem by setting 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' to true or specifying 'system.serviceModel/serviceHostingEnvironment/baseAddressPrefixFilters'."
Cause: This error occurs because http port number 443 is already in use by another application and the IIS server is not configured to handle multiple binding to the same port.
Solution: Configure IIS server to handle multiple port bindings. Contact the vendor (Microsoft) to configure it.
Since these services were offered from an IIS Web Server, checking the Bindings on the Root Site fixed the problem. Someone had messed up the Site Bindings, defining rules that were overlapping themselves and messed up the services.
Fixing the correct Bindings resolved the problem, in my case, and i did not have to configure the Web.Config.
'self.webView.scrollView.bounces = NO;'
Just add this one line in the 'viewDidLoad' of the mainViewController.m file of your application. you can open it in the Xcode and add it .
This should make the page without any rubberband bounces still enabling the scroll in the app view.
I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
You have 2 options: Redirect the output of the script to a file, Introduce a log file in the script and
Here you assume that the script outputs all necessary info, including warning and error messages. You can then redirect the output to a file of your choice.
./runTests &> output.log
The above command redirects both the standard output and the error output to your log file.
Using this approach you don't have to introduce a log file in the script, and so the logic is a tiny bit easier.
In your script add a log file either by hard coding it:
logFile='./path/to/log/file.log'
or passing it by a parameter:
logFile="${1}" # This assumes the first parameter to the script is the log file
It's a good idea to add the timestamp at the time of execution to the log file at the top of the script:
date '+%Y%-m%d-%H%M%S' >> "${logFile}"
You can then redirect your error messages to the log file
if [ condition ]; then
echo "Test cases failed!!" >> "${logFile}";
fi
This will append the error to the log file and continue execution. If you want to stop execution when critical errors occur, you can exit
the script:
if [ condition ]; then
echo "Test cases failed!!" >> "${logFile}";
# Clean up if needed
exit 1;
fi
Note that exit 1
indicates that the program stop execution due to an unspecified error. You can customize this if you like.
Using this approach you can customize your logs and have a different log file for each component of your script.
If you have a relatively small script or want to execute somebody else's script without modifying it to the first approach is more suitable.
If you always want the log file to be at the same location, this is the better option of the 2. Also if you have created a big script with multiple components then you may want to log each part differently and the second approach is your only option.
you can use ![ ](any link of image)
Also I would suggest to use https://stackedit.io/ for markdown formating and wring it is much easy than remembering all the markdown syntax
if(isset($_GET['id']))
{
// Do something
}
You want something like that
If the 2nd company is happy for you to access their content in an IFrame then they need to take the restriction off - they can do this fairly easily in the IIS config.
There's nothing you can do to circumvent it and anything that does work should get patched quickly in a security hotfix. You can't tell the browser to just render the frame if the source content header says not allowed in frames. That would make it easier for session hijacking.
If the content is GET only you don't post data back then you could get the page server side and proxy the content without the header, but then any post back should get invalidated.
The negative margin trick:
http://pastehtml.com/view/1dujbt3.html
Not elegant, I suppose, but it works in some cases.
You may also want to read "Why getter and setter methods are evil":
Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.
This article explains why you shouldn't use getters and setters (and when you can use them) and suggests a design methodology that will help you break out of the getter/setter mentality.
In my case I saw the same message due to the different signatures of the installed apk and an uploaded to the market apk.
You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScript
instead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.
part of manifest.json
"browser_action": {
"default_title": "Test",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]
index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="test">TEST!</button>
<script src="test.js"></script>
</body>
</html>
test.js
document.getElementById("test").addEventListener('click', () => {
console.log("Popup DOM fully loaded and parsed");
function modifyDOM() {
//You can play with your DOM here or check URL against your regex
console.log('Tab script:');
console.log(document.body);
return document.body.innerHTML;
}
//We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
}, (results) => {
//Here we have just the innerHTML and not DOM structure
console.log('Popup script:')
console.log(results[0]);
});
});
Doing some testing with a Raspberry Pi 3B+ (I'm using an overlay file system, and need to sync periodically), I ran a comparison of my own for diff -q and cmp -s; note that this is a log from inside /dev/shm, so disk access speeds are a non-issue:
[root@mypi shm]# dd if=/dev/urandom of=test.file bs=1M count=100 ; time diff -q test.file test.copy && echo diff true || echo diff false ; time cmp -s test.file test.copy && echo cmp true || echo cmp false ; cp -a test.file test.copy ; time diff -q test.file test.copy && echo diff true || echo diff false; time cmp -s test.file test.copy && echo cmp true || echo cmp false
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 6.2564 s, 16.8 MB/s
Files test.file and test.copy differ
real 0m0.008s
user 0m0.008s
sys 0m0.000s
diff false
real 0m0.009s
user 0m0.007s
sys 0m0.001s
cmp false
cp: overwrite âtest.copyâ? y
real 0m0.966s
user 0m0.447s
sys 0m0.518s
diff true
real 0m0.785s
user 0m0.211s
sys 0m0.573s
cmp true
[root@mypi shm]# pico /root/rwbscripts/utils/squish.sh
I ran it a couple of times. cmp -s consistently had slightly shorter times on the test box I was using. So if you want to use cmp -s to do things between two files....
identical (){
echo "$1" and "$2" are the same.
echo This is a function, you can put whatever you want in here.
}
different () {
echo "$1" and "$2" are different.
echo This is a function, you can put whatever you want in here, too.
}
cmp -s "$FILEA" "$FILEB" && identical "$FILEA" "$FILEB" || different "$FILEA" "$FILEB"
Floating point numbers lack precision to accurately represent "1.6" out to that many decimal places. The rounding errors are real. Your number is not actually 1.6.
Check out: http://docs.python.org/library/decimal.html
Copied from : https://docs.python.org/2/library/uuid.html (Since the links posted were not active and they keep updating)
>>> import uuid
>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'
>>> # get the raw 16 bytes of the UUID
>>> x.bytes
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
Using preg_replace
$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;
If you are on ubuntu, just install pyqt5 with apt-get
command:
sudo apt-get install python3-pyqt5 # for python3
or
sudo apt-get install python-pyqt5 # for python2
However, on Ubuntu 14.04 the python-pyqt5 package is left out [source] and need to be installed manually [source]
You can also get the number of data by using the count function.
$query = $this->dm->createQueryBuilder('AppBundle:Items')
->field('isDeleted')->equals(false)
->getQuery()->count();
function arr(arr1,arr2){_x000D_
_x000D_
function filt(value){_x000D_
return arr2.indexOf(value) === -1;_x000D_
}_x000D_
_x000D_
return arr1.filter(filt)_x000D_
}_x000D_
_x000D_
document.getElementById("p").innerHTML = arr([1,2,3,4],[2,4])
_x000D_
<p id="p"></p>
_x000D_
For anyone looking for a solution that doesn't require [Serializable]
classes and where the result is an approximation instead of exact science.
The best method I could find is json serialization into a memorystream using UTF32 encoding.
private static long? GetSizeOfObjectInBytes(object item)
{
if (item == null) return 0;
try
{
// hackish solution to get an approximation of the size
var jsonSerializerSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
MaxDepth = 10,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
var formatter = new JsonMediaTypeFormatter { SerializerSettings = jsonSerializerSettings };
using (var stream = new MemoryStream()) {
formatter.WriteToStream(item.GetType(), item, stream, Encoding.UTF32);
return stream.Length / 4; // 32 bits per character = 4 bytes per character
}
}
catch (Exception)
{
return null;
}
}
No, this won't give you the exact size that would be used in memory. As previously mentioned, that is not possible. But it'll give you a rough estimation.
Note that this is also pretty slow.
It's even simpler than that. Just did this (on Windows, but it should work on other OS):
Git just sees you added a directory and renamed a bunch of files. No biggie.
Use the ExecuteStoreQuery method of the entity context. This avoids downloading the entire result set and deserializing into objects to do a simple row count.
int count;
using (var db = new MyDatabase()){
string sql = "SELECT COUNT(*) FROM MyTable where FkId = {0}";
object[] myParams = {1};
var cntQuery = db.ExecuteStoreQuery<int>(sql, myParams);
count = cntQuery.First<int>();
}
If you already have the int typed as an Integer you can do this:
Integer y = 1;
long x = y.longValue();
On input type=file add an event onchange="preview()"
For the function preview()
type:
thumb.src=URL.createObjectURL(event.target.files[0]);
Live example:
function preview() {
thumb.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
<input type="file" onchange="preview()">
<img id="thumb" src="" width="150px"/>
</form>
_x000D_
To see what was changed in a file in the last commit:
git diff HEAD~1 path/to/file
You can change the number (~1) to the n-th commit which you want to diff with.
Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.
You can avoid this problem by
Hibernate.initialize(obj);
Fetch profiles
to select lazy/non-lazy fetching runtimeFurther I would recommend looking at the related
links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.
You can also run your app like any other console applications but only after the publish.
Let's suppose you have the simple console app named MyTestConsoleApp. Open the package manager console and run the following command:
dotnet publish -c Debug -r win10-x64
-c flag mean that you want to use the debug configuration (in other case you should use Release value) - r flag mean that your application will be runned on Windows platform with x64 architecture.
When the publish procedure will be finished your will see the *.exe file located in your bin/Debug/publish directory.
Now you can call it via command line tools. So open the CMD window (or terminal) move to the directory where your *.exe file is located and write the next command:
>> MyTestConsoleApp.exe argument-list
For example:
>> MyTestConsoleApp.exe --input some_text -r true
I didn't understand this pattern until I came across with uncle bob article and read comments. Consider the following code:
public class Employee
{
}
public class SalariedEmployee : Employee
{
}
public class HourlyEmployee : Employee
{
}
public class QtdHoursAndPayReport
{
public void PrintReport()
{
var employees = new List<Employee>
{
new SalariedEmployee(),
new HourlyEmployee()
};
foreach (Employee e in employees)
{
if (e is HourlyEmployee he)
PrintReportLine(he);
if (e is SalariedEmployee se)
PrintReportLine(se);
}
}
public void PrintReportLine(HourlyEmployee he)
{
System.Diagnostics.Debug.WriteLine("hours");
}
public void PrintReportLine(SalariedEmployee se)
{
System.Diagnostics.Debug.WriteLine("fix");
}
}
class Program
{
static void Main(string[] args)
{
new QtdHoursAndPayReport().PrintReport();
}
}
While it may look good since it confirms to Single Responsibility it violates Open/Closed principle. Each time you have new Employee type you will have to add if with type check. And if you won't you'll never know that at compile time.
With visitor pattern you can make your code cleaner since it does not violate open/closed principle and does not violate Single responsibility. And if you forget to implement visit it won't compile:
public abstract class Employee
{
public abstract void Accept(EmployeeVisitor v);
}
public class SalariedEmployee : Employee
{
public override void Accept(EmployeeVisitor v)
{
v.Visit(this);
}
}
public class HourlyEmployee:Employee
{
public override void Accept(EmployeeVisitor v)
{
v.Visit(this);
}
}
public interface EmployeeVisitor
{
void Visit(HourlyEmployee he);
void Visit(SalariedEmployee se);
}
public class QtdHoursAndPayReport : EmployeeVisitor
{
public void Visit(HourlyEmployee he)
{
System.Diagnostics.Debug.WriteLine("hourly");
// generate the line of the report.
}
public void Visit(SalariedEmployee se)
{
System.Diagnostics.Debug.WriteLine("fix");
} // do nothing
public void PrintReport()
{
var employees = new List<Employee>
{
new SalariedEmployee(),
new HourlyEmployee()
};
QtdHoursAndPayReport v = new QtdHoursAndPayReport();
foreach (var emp in employees)
{
emp.Accept(v);
}
}
}
class Program
{
public static void Main(string[] args)
{
new QtdHoursAndPayReport().PrintReport();
}
}
}
The magic is that while v.Visit(this)
looks the same it's in fact different since it call different overloads of visitor.
I was trying to do the same thing. While background-color and background-image exist on separate layers within an object -- meaning they can co-exist -- CSS gradients seem to co-opt the background-image layer.
From what I can tell, border-image seems to have wider support than multiple backgrounds, so maybe that's an alternative approach.
http://articles.sitepoint.com/article/css3-border-images
UPDATE: A bit more research. Seems Petra Gregorova has something working here --> http://petragregorova.com/demos/css-gradient-and-bg-image-final.html
Throwing in an option since I didn't see this exact scenario covered. If you don't want c
updated when a
or b
update, then an ES6 IIFE works well.
var foo = ((a,b) => ({
a,
b,
c: a + b
}))(a,b);
For my needs, I have an object that relates to an array which will end up being used in a loop, so I only want to calculate some common setup once, so this is what I have:
let processingState = ((indexOfSelectedTier) => ({
selectedTier,
indexOfSelectedTier,
hasUpperTierSelection: tiers.slice(0,indexOfSelectedTier)
.some(t => pendingSelectedFiltersState[t.name]),
}))(tiers.indexOf(selectedTier));
Since I need to set a property for indexOfSelectedTier
and I need to use that value when setting the hasUpperTierSelection
property, I calculate that value first and pass it in as a param to the IIFE
Edit If you are asking about security, see my addendum at the bottom Edit
PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.
$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);
This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.
Addendum
I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.
I think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.
As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:
$(window).resize(function() {
//update stuff
});
For .Net <= 4.0 Use the TimeSpan class.
TimeSpan t = TimeSpan.FromSeconds( secs );
string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
t.Hours,
t.Minutes,
t.Seconds,
t.Milliseconds);
(As noted by Inder Kumar Rathore) For .NET > 4.0 you can use
TimeSpan time = TimeSpan.FromSeconds(seconds);
//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");
(From Nick Molyneux) Ensure that seconds is less than TimeSpan.MaxValue.TotalSeconds
to avoid an exception.
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
So, this is all you need:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
$(function(){
$('.easy_editor').css('border','9px solid red');
});
use this
$("a").each(function () {
var href=$(this).prop('href');
if (href.indexOf('?') > -1) {
alert("Contains questionmark");
}
});
After some days searching the Internet I found that this error usually occurs when an html element id has the same id as some variable in the javascript function. After changing the name of one of them my code was working fine.
maxFiles
Count: maxFiles: 1
maxfilesexceeded
event, clear all files and add a new file:event: Called for each file that has been rejected because the number of files exceeds the maxFiles limit.
var myDropzone = new Dropzone("div#yourDropzoneID", { url: "/file/post",
uploadMultiple: false, maxFiles: 1 });
myDropzone.on("maxfilesexceeded", function (file) {
myDropzone.removeAllFiles();
myDropzone.addFile(file);
});
In intellij you can auto generate toString method by pressing alt+inset and then selecting toString() here is an out put for a test class:
public class test {
int a;
char b;
String c;
Test2 test2;
@Override
public String toString() {
return "test{" +
"a=" + a +
", b=" + b +
", c='" + c + '\'' +
", test2=" + test2 +
'}';
}
}
As you can see, it generates a String by concatenating, several attributes of the class, for primitives it will print their values and for reference types it will use their class type (in this case to string method of Test2).
This answer is only applicable for websites which uses Bootstrap. The responsive embed feature of the Bootstrap does the job. It is based on the width (not height) of the content.
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div>
jsfiddle: http://jsfiddle.net/00qggsjj/2/
To dump:
pg_dump -Fc mydb > db.dump
To restore:
pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d my_db db/latest.dump
Another alternative: HigLabo
https://higlabo.codeplex.com/documentation
Good discussion: https://higlabo.codeplex.com/discussions/479250
//====Imap sample================================//
//You can set default value by Default property
ImapClient.Default.UserName = "your server name";
ImapClient cl = new ImapClient("your server name");
cl.UserName = "your name";
cl.Password = "pass";
cl.Ssl = false;
if (cl.Authenticate() == true)
{
Int32 MailIndex = 1;
//Get all folder
List<ImapFolder> l = cl.GetAllFolders();
ImapFolder rFolder = cl.SelectFolder("INBOX");
MailMessage mg = cl.GetMessage(MailIndex);
}
//Delete selected mail from mailbox
ImapClient pop = new ImapClient("server name", 110, "user name", "pass");
pop.AuthenticateMode = Pop3AuthenticateMode.Pop;
Int64[] DeleteIndexList = new.....//It depend on your needs
cl.DeleteEMail(DeleteIndexList);
//Get unread message list from GMail
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
//Select folder
ImapFolder folder = cl.SelectFolder("[Gmail]/All Mail");
//Search Unread
SearchResult list = cl.ExecuteSearch("UNSEEN UNDELETED");
//Get all unread mail
for (int i = 0; i < list.MailIndexList.Count; i++)
{
mg = cl.GetMessage(list.MailIndexList[i]);
}
}
//Change mail read state as read
cl.ExecuteStore(1, StoreItem.FlagsReplace, "UNSEEN")
}
//Create draft mail to mailbox
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
var smg = new SmtpMessage("from mail address", "to mail addres list"
, "cc mail address list", "This is a test mail.", "Hi.It is my draft mail");
cl.ExecuteAppend("GMail/Drafts", smg.GetDataText(), "\\Draft", DateTimeOffset.Now);
}
}
//Idle
using (var cl = new ImapClient("imap.gmail.com", 993, "user name", "pass"))
{
cl.Ssl = true;
cl.ReceiveTimeout = 10 * 60 * 1000;//10 minute
if (cl.Authenticate() == true)
{
var l = cl.GetAllFolders();
ImapFolder r = cl.SelectFolder("INBOX");
//You must dispose ImapIdleCommand object
using (var cm = cl.CreateImapIdleCommand()) Caution! Ensure dispose command object
{
//This handler is invoked when you receive a mesage from server
cm.MessageReceived += (Object o, ImapIdleCommandMessageReceivedEventArgs e) =>
{
foreach (var mg in e.MessageList)
{
String text = String.Format("Type is {0} Number is {1}", mg.MessageType, mg.Number);
Console.WriteLine(text);
}
};
cl.ExecuteIdle(cm);
while (true)
{
var line = Console.ReadLine();
if (line == "done")
{
cl.ExecuteDone(cm);
break;
}
}
}
}
}
Running an SQL query in PHPmyadmin to find and replace text in all wordpress blog posts, such as finding mysite.com/wordpress and replacing that with mysite.com/news Table in this example is tj_posts
UPDATE `tj_posts`
SET `post_content` = replace(post_content, 'mysite.com/wordpress', 'mysite.com/news')
CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.
You need to define the animation keyframes and apply it to the element:
@keyframes changewidth {
from {
width: 100px;
}
to {
width: 300px;
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.
Because you haven't specified what front end (GUI technology) you're using it would be hard to make a specific recommendation. In WPF you could create a listbox and for each new line of chat add a new listboxitem to the end of the collection. This link provides some suggestions as to how you may achieve the same result in a winforms environment.
Do it the vi way.
To delete 5 lines press: 5dd
( 5 delete )
To select ( actually copy them to the clipboard ) you type: 10yy
It is a bit hard to grasp, but very handy to learn when using those remote terminals
Be aware of the learning curves for some editors:
(source: calver at unix.rulez.org)
The simplest solution is probably:
In [10]: ''.join(set('aaabcabccd'))
Out[10]: 'acbd'
Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.
You refer to the output as a "list". If a list is what you really want, replace ''.join
with list
:
In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']
As far as performance goes, worrying about it at this stage sounds like premature optimization.
I know three plugins that permit to open files, support auto-completion, and don't require to enter the full path name of the file(s) to open (as long as the files are under one of the directories from &path
vim option):
:e
/:find
, but on split actions)Lately, I've seen another plugin with a similar feature, but I don't remember the name.
Soon, :find is likely support auto-completion -- patches on this topic are circulating on vim_dev mailing-list these days.
set ConnectionFactory or Connection hostname to localhost
If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv
Here's an answer, based on (and I think an improvement on) Tester101's answer, expressed as a subroutine, with the CopyFile line once instead of three times, and prepared to handle changing the file name as the copy is made (no hard-coded destination directory). I also found I had to delete the target file before copying to get this to work, but that might be a Windows 7 thing. The WScript.Echo statements are because I didn't have a debugger and can of course be removed if desired.
Sub CopyFile(SourceFile, DestinationFile)
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
Dim wasReadOnly
wasReadOnly = False
If fso.FileExists(DestinationFile) Then
'Check to see if the file is read-only
If fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is read-only.
WScript.Echo "Removing the read-only attribute"
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
wasReadOnly = True
End If
WScript.Echo "Deleting the file"
fso.DeleteFile DestinationFile, True
End If
'Copy the file
WScript.Echo "Copying " & SourceFile & " to " & DestinationFile
fso.CopyFile SourceFile, DestinationFile, True
If wasReadOnly Then
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Set fso = Nothing
End Sub
Yes, you can use the *args
(splat) syntax:
function_that_needs_strings(*my_list)
where my_list
can be any iterable; Python will loop over the given object and use each element as a separate argument to the function.
See the call expression documentation.
There is a keyword-parameter equivalent as well, using two stars:
kwargs = {'foo': 'bar', 'spam': 'ham'}
f(**kwargs)
and there is equivalent syntax for specifying catch-all arguments in a function signature:
def func(*args, **kw):
# args now holds positional arguments, kw keyword arguments
If I remember correctly, this is the default property for controls.
Can you try by going into Design-View for the admin_reasons that contains the specified Control, then changing the control's Modifiers property to Public or Internal.
In MySQL, It should be like this
INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';
Use StringBuilder
:
String str;
Char a, b, c;
a = 'i';
b = 'c';
c = 'e';
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
sb.append(c);
str = sb.toString();
One-liner:
new StringBuilder().append(a).append(b).append(c).toString();
Doing ""+a+b+c
gives:
new StringBuilder().append("").append(a).append(b).append(c).toString();
I asked some time ago related question.
FORCE_INDEX
is going to be deprecated after MySQL 8:
Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in
a future release of MySQL, and at some time thereafter to be removed altogether.
https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
You should be using JOIN_INDEX
, GROUP_INDEX
, ORDER_INDEX
, and INDEX
instead, for v8.
if you have number of columns in your database table more than number of columns in your csv you can proceed like this:
LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);
Using $("textarea#ExampleMessage").html('whatever you want to put here');
can be a good way, because .val()
can have problems when you are using data from database.
For example:
A database field named as description
has the following value asjkdfklasdjf sjklñadf
. In this case using .val() to assign value to textarea can be a tedious job.
Big difference between an image and an iframe is the fact that an image keeps its aspect-ratio. You could combine an image and an iframe with will result in a responsive iframe. Hope this answerers your question.
Check this link for example : http://jsfiddle.net/Masau/7WRHM/
HTML:
<div class="wrapper">
<div class="h_iframe">
<!-- a transparent image is preferable -->
<img class="ratio" src="http://placehold.it/16x9"/>
<iframe src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe>
</div>
<p>Please scale the "result" window to notice the effect.</p>
</div>
CSS:
html,body {height:100%;}
.wrapper {width:80%;height:100%;margin:0 auto;background:#CCC}
.h_iframe {position:relative;}
.h_iframe .ratio {display:block;width:100%;height:auto;}
.h_iframe iframe {position:absolute;top:0;left:0;width:100%; height:100%;}
note: This only works with a fixed aspect-ratio.
Either run basicConfig
with stream=sys.stdout
as the argument prior to setting up any other handlers or logging any messages, or manually add a StreamHandler
that pushes messages to stdout to the root logger (or any other logger you want, for that matter).
You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE
if everythings check out to be correct or FALSE
if anything is invalid. It doesn't get easier then this!
function validateDate(date) {
var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
if (matches == null) return false;
var d = matches[3];
var m = matches[2] - 1;
var y = matches[1] ;
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
Be aware that months need to be subtracted like this: var m = matches[2] - 1;
else the new Date()
instance won't be properly made.
As has, to some extent, been mentioned before, an enum is a java class with the special condition that its definition must start with at least one "enum constant".
Apart from that, and that enums cant can't be extended or used to extend other classes, an enum is a class like any class and you use it by adding methods below the constant definitions:
public enum MySingleton {
INSTANCE;
public void doSomething() { ... }
public synchronized String getSomething() { return something; }
private String something;
}
You access the singleton's methods along these lines:
MySingleton.INSTANCE.doSomething();
String something = MySingleton.INSTANCE.getSomething();
The use of an enum, instead of a class, is, as has been mentioned in other answers, mostly about a thread-safe instantiation of the singleton and a guarantee that it will always only be one copy.
And, perhaps, most importantly, that this behavior is guaranteed by the JVM itself and the Java specification.
Here's a section from the Java specification on how multiple instances of an enum instance is prevented:
An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type. The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.
Worth noting is that after the instantiation any thread-safety concerns must be handled like in any other class with the synchronized keyword etc.
<asp:GridView ID="gvEmployee" runat="server"
AutoGenerateColumns="False" ShowHeaderWhenEmpty=”True”>
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Designation" HeaderText="Designation" />
<asp:BoundField DataField="Salary" HeaderText="Salary" />
</Columns>
<EmptyDataTemplate>No Record Available</EmptyDataTemplate>
</asp:GridView>
in CS Page
gvEmployee.DataSource = dt;
gvEmployee.DataBind();
The reason to prefer Promises over callback functions is to have multiple callbacks and to avoid the problems like Callback Hell.
Callback hell (for more details, refer http://callbackhell.com/): Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:
asyncCall(function(err, data1){
if(err) return callback(err);
anotherAsyncCall(function(err2, data2){
if(err2) return calllback(err2);
oneMoreAsyncCall(function(err3, data3){
if(err3) return callback(err3);
// are we done yet?
});
});
});
With Promises above code can be rewritten as below:
asyncCall()
.then(function(data1){
// do something...
return anotherAsyncCall();
})
.then(function(data2){
// do something...
return oneMoreAsyncCall();
})
.then(function(data3){
// the third and final async response
})
.fail(function(err) {
// handle any error resulting from any of the above calls
})
.done();
Shorter version of:
REGEXP_REPLACE( my_value, '[[:space:]]', '' )
Would be:
REGEXP_REPLACE( my_value, '\s')
Neither of the above statements will remove "null" characters.
To remove "nulls" encase the statement with a replace
Like so:
REPLACE(REGEXP_REPLACE( my_value, '\s'), CHR(0))
You can use a BehaviorSubject
within a facade service then subscribe to that subject in any component and when an event happens to trigger a change in data call .next()
on it. Make sure to close out those subscriptions within the on destroy lifecycle hook.
data-api.facade.ts
@Injectable({
providedIn: 'root'
})
export class DataApiFacade {
currentTabIndex: BehaviorSubject<number> = new BehaviorSubject(0);
}
some.component.ts
constructor(private dataApiFacade: DataApiFacade){}
ngOnInit(): void {
this.dataApiFacade.currentTabIndex
.pipe(takeUntil(this.destroy$))
.subscribe(value => {
if (value) {
this.currentTabIndex = value;
}
});
}
setTabView(event: MatTabChangeEvent) {
this.dataApiFacade.currentTabIndex.next(event.index);
}
ngOnDestroy() {
this.destroy$.next(true);
this.destroy$.complete();
}
Simple use this great free online tool:
Angular has several timepoints to start executing functions. If you seek for something like jQuery's
$(document).ready();
You may find this analog in angular to be very useful:
$scope.$watch('$viewContentLoaded', function(){
//do something
});
This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.
UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:
$scope.$watch('$viewContentLoaded',
function() {
$timeout(function() {
//do something
},0);
});
ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );
new File(absolutePath).getName();
As has already been said: figure
will create a new figure for your next plots. While calling figure
you can also configure it. Example:
figHandle = figure('Name', 'Name of Figure', 'OuterPosition',[1, 1, scrsz(3), scrsz(4)]);
The example sets the name for the window and the outer size of it in relation to the used screen.
Here figHandle
is the handle to the resulting figure and can be used later to change appearance and content. Examples:
Dot notation:
figHandle.PaperOrientation = 'portrait';
figHandle.PaperUnits = 'centimeters';
Old Style:
set(figHandle, 'PaperOrientation', 'portrait', 'PaperUnits', 'centimeters');
Using the handle with dot notation or set
, options for printing are configured here.
By keeping the handles for the figures with distinc names you can interact with multiple active figures. To set a existing figure as your active, call figure(figHandle)
. New plots will go there now.
function uploadFile() {
var fileElement = document.getElementById("fileToUpload");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension == "odx-d"||fileExtension == "odx"||fileExtension == "pdx"||fileExtension == "cmo"||fileExtension == "xml") {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/post_uploadReq");
xhr.send(fd);
}
else {
alert("You must select a valid odx,pdx,xml or cmo file for upload");
return false;
}
}
tried this , works very well
Look this example.
CREATE TABLE [dbo].#TestTable(
[id] [int] NOT NULL,
[create_date] [date] NOT NULL,
[info1] [varchar](50) NOT NULL,
[info2] [varchar](50) NOT NULL,
)
Insert some data
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/1/09', 'Blue', 'Green')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/2/09', 'Red', 'Yellow')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/3/09', 'Orange', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/1/09', 'Yellow', 'Blue')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/5/09', 'Blue', 'Orange')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/2/09', 'Green', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/8/09', 'Red', 'Blue')
Repeat same Values for 1
INSERT INTO dbo.#TestTable (id, create_date, info1, info2) VALUES (1, '1/1/09', 'Blue', 'Green')
Look All
SELECT * FROM #TestTable
Look your results
SELECT Id,
create_date,
info1,
info2,
ROW_NUMBER() OVER (PARTITION BY Id ORDER BY create_date DESC) AS RowId,
RANK() OVER(PARTITION BY Id ORDER BY create_date DESC) AS [RANK]
FROM #TestTable
Need to understand the different
A wild card would work nicely for this, although to be safe it would be best to make the use of the wild card as minimal as possible, so something along the lines of this:
rm -rf abc.log.2012-*
Although from the looks of it, are those just single files? The recursive option should not be necessary if none of those items are directories, so best to not use that, just for safety.
I've been struggling with this all afternoon whilst working with an ASP Core project and xUnit 2.2.0. The solution for me was adding a reference to Microsoft.DotNet.InternalAbstractions
I found this out when trying to run the test project manually with dotnet test
which failed but reported that InternalAbstractions
was missing. I did not see this error in the test output window when the auto discovery failed. The only info I saw in the discovery window was a return code, which didn't mean anything to me at the time, but in hindsight was probably indicating an error.
If the caller is another project, you should write the config in caller project not the called one.