It is not quite as baked-in in Java, so you don't get this for free. It is done with convention rather than language constructs. In all data transfer classes (and maybe even in all classes you write...), you should implement a sensible toString
method. So here you need to override toString()
in your Person
class and return the desired state.
There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString()
writing shortcut.
For those who have trouble with the accepted solution, there is another way to exclude resource from shaded jar with DontIncludeResourceTransformer:
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
<resource>BC1024KE.DSA</resource>
</transformer>
</transformers>
From Shade 3.0, this transformer accepts a list of resources. Before that you just need to use multiple transformer each with one resource.
In the action method of the request to the url "http://localhost:85458/api/ctrl/"
var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) ;
this will get you http://localhost:85458
update
update
ngComponentOutlet
was added to 4.0.0-beta.3
update
There is a NgComponentOutlet
work in progress that does something similar https://github.com/angular/angular/pull/11235
RC.7
// Helper component to add dynamic components
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
@Input() type: Type<Component>;
cmpRef: ComponentRef<Component>;
private isViewInitialized:boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
// when the `type` input changes we destroy a previously
// created component before creating the new one
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Usage example
// Use dcl-wrapper component
@Component({
selector: 'my-tabs',
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
// The list of components to create tabs from
types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
entryComponents: [C1, C2, C3],
bootstrap: [ App ]
})
export class AppModule {}
See also angular.io DYNAMIC COMPONENT LOADER
older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This changed again in Angular2 RC.5
I will update the example below but it's the last day before vacation.
This Plunker example demonstrates how to dynamically create components in RC.5
Update - use ViewContainerRef.createComponent()
Because DynamicComponentLoader
is deprecated, the approach needs to be update again.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Plunker example RC.4
Plunker example beta.17
Update - use loadNextToLocation
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private dcl:DynamicComponentLoader) {}
updateComponent() {
// should be executed every time `type` changes but not before `ngAfterViewInit()` was called
// to have `target` initialized
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
original
Not entirely sure from your question what your requirements are but I think this should do what you want.
The Tabs
component gets an array of types passed and it creates "tabs" for each item in the array.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
@Input() type;
ngOnChanges() {
if(this.cmpRef) {
this.cmpRef.dispose();
}
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
}
@Component({
selector: 'c1',
template: `<h2>c1</h2>`
})
export class C1 {
}
@Component({
selector: 'c2',
template: `<h2>c2</h2>`
})
export class C2 {
}
@Component({
selector: 'c3',
template: `<h2>c3</h2>`
})
export class C3 {
}
@Component({
selector: 'my-tabs',
directives: [DclWrapper],
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
directives: [Tabs]
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
types = [C3, C1, C2, C3, C3, C1, C1];
}
Plunker example beta.15 (not based on your Plunker)
There is also a way to pass data along that can be passed to the dynamically created component like (someData
would need to be passed like type
)
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
cmpRef.instance.someProperty = someData;
this.cmpRef = cmpRef;
});
There is also some support to use dependency injection with shared services.
For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html
Be aware that the result may be slightly different than you expect.
NOW()
returns a DATETIME
.
And INTERVAL
works as named, e.g. INTERVAL 1 DAY = 24 hours
.
So if your script is cron'd to run at 03:00
, it will miss the first three hours of records from the 'oldest' day
.
To get the whole day use CURDATE() - INTERVAL 1 DAY
. This will get back to the beginning of the previous day regardless of when the script is run.
Recently ran into this when upgrading from 2.3 to 3.1; our jQuery animations (slideDown) broke because we were putting hide on the elements in the page template. We went the route of creating name-spaced versions of Bootstrap classes that now carry the ugly !important rule.
.rb-hide { display: none; }
.rb-pull-left { float: left; }
etc...
I solved this issue by deleting in the repository folders where this error was shown everything except the .jar and .pom files.
You could use the <pre>
tag
<div class="text">_x000D_
<pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</div>
_x000D_
If you have to use the same page as the action, you cannot use onSubmit="window.close();"
as it will close the window before the response is received. You have to dinamycally output a JS snippet that closes the window after the SQL data is processed. It would however be far more elegant to use another page as the form action.
Please try this:
#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;
-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;
-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}
Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.
In Visual Studio 2010
Ctrl +k +d indent the complete page.
Ctrl +k +f indent the selected Code.
For more help visit : http://msdn.microsoft.com/en-us/library/da5kh0wa.aspx
every thing is there.
From the DOCS
Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.
SYNTAX:
number_expression | number[:digitInfo[:locale]]
where expression
is a number:
digitInfo
is a string which has a following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
Try this code, it appears to solve your problem.
Dim MaxID As Integer = Convert.ToInt32(IIf(IsDBNull(cmd.ExecuteScalar()), 1, cmd.ExecuteScalar())
)
Create table target_table
As
Select *
from source_table
where 1=2;
Source_table is the table u wanna copy the structure of.
Your string is invalid, but assuming it was valid, you'd have to do:
var finalData = str.replace(/\\/g, "");
When you want to replace all the occurences with .replace
, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.
Cheers
Try using the [StringLength]
attribute:
[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }
That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
Source: http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
The short answer is using the next regular expression:
(?s)<car .*? model=BMW .*?>.*?</car>
A (little) more complicated answer is:
(?s)<([a-z\-_0-9]+?) .*? model=BMW .*?>.*?</\1>
This will makes possible to match car1 and car2 in the following text
<car1 ... model=BMW ...>
...
...
...
</car1>
<car2 ... model=BMW ...>
...
...
...
</car2>
First, parse the string into a naive datetime object. This is an instance of datetime.datetime
with no attached timezone information. See its documentation.
Use the pytz
module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.
Finally, use datetime.astimezone()
method to convert the datetime to UTC.
Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":
from datetime import datetime
import pytz
local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
From there, you can use the strftime()
method to format the UTC datetime as needed:
utc_dt.strftime("%Y-%m-%d %H:%M:%S")
Here's the simple example.
diff --git a/file b/file
index 10ff2df..84d4fa2 100644
--- a/file
+++ b/file
@@ -1,5 +1,5 @@
line1
line2
-this line will be deleted
line4
line5
+this line is added
Here's an explanation (see details here).
--git
is not a command, this means it's a git version of diff (not unix)a/ b/
are directories, they are not real. it's just a convenience when we deal with the same file (in my case a/ is in index and b/ is in working directory)10ff2df..84d4fa2
are blob IDs of these 2 files100644
is the “mode bits,” indicating that this is a regular file (not executable and not a symbolic link)--- a/file +++ b/file
minus signs shows lines in the a/ version but missing from the b/ version; and plus signs shows lines missing in a/ but present in b/ (in my case --- means deleted lines and +++ means added lines in b/ and this the file in the working directory)@@ -1,5 +1,5 @@
in order to understand this it's better to work with a big file; if you have two changes in different places you'll get two entries like @@ -1,5 +1,5 @@
; suppose you have file line1 ... line100 and deleted line10 and add new line100 - you'll get:@@ -7,7 +7,6 @@ line6 line7 line8 line9 -this line10 to be deleted line11 line12 line13 @@ -98,3 +97,4 @@ line97 line98 line99 line100 +this is new line100
Most of the time when we download tomcat and extract the file a folder will be created:
C:\Program Files\apache-tomcat-9.0.1-windows-x64
Inside that actual tomcat folder will be there:
C:\Program Files\apache-tomcat-9.0.1-windows-x64\apache-tomcat-9.0.1
so while selecting you need to select inner folder:
C:\Program Files\apache-tomcat-9.0.1-windows-x64\apache-tomcat-9.0.1
instead of the outer.
You can handle the ListView's PreviewMouseLeftButtonUp event. The reason not to handle the PreviewMouseLeftButtonDown event is that, by the time when you handle the event, the ListView's SelectedItem may still be null.
XAML:
<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...
Code behind:
private void listView_Click(object sender, RoutedEventArgs e)
{
var item = (sender as ListView).SelectedItem;
if (item != null)
{
...
}
}
I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No
I have implemented a small class with the help of which you can handle long clicks on TextView itself and Taps on the links in the TextView.
TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="all"/>
import android.content.Context;
import android.text.Layout;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Patterns;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;
public class TextViewClickMovement extends LinkMovementMethod {
private final String TAG = TextViewClickMovement.class.getSimpleName();
private final OnTextViewClickMovementListener mListener;
private final GestureDetector mGestureDetector;
private TextView mWidget;
private Spannable mBuffer;
public enum LinkType {
/** Indicates that phone link was clicked */
PHONE,
/** Identifies that URL was clicked */
WEB_URL,
/** Identifies that Email Address was clicked */
EMAIL_ADDRESS,
/** Indicates that none of above mentioned were clicked */
NONE
}
/**
* Interface used to handle Long clicks on the {@link TextView} and taps
* on the phone, web, mail links inside of {@link TextView}.
*/
public interface OnTextViewClickMovementListener {
/**
* This method will be invoked when user press and hold
* finger on the {@link TextView}
*
* @param linkText Text which contains link on which user presses.
* @param linkType Type of the link can be one of {@link LinkType} enumeration
*/
void onLinkClicked(final String linkText, final LinkType linkType);
/**
*
* @param text Whole text of {@link TextView}
*/
void onLongClick(final String text);
}
public TextViewClickMovement(final OnTextViewClickMovementListener listener, final Context context) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener());
}
@Override
public boolean onTouchEvent(final TextView widget, final Spannable buffer, final MotionEvent event) {
mWidget = widget;
mBuffer = buffer;
mGestureDetector.onTouchEvent(event);
return false;
}
/**
* Detects various gestures and events.
* Notify users when a particular motion event has occurred.
*/
class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent event) {
// Notified when a tap occurs.
return true;
}
@Override
public void onLongPress(MotionEvent e) {
// Notified when a long press occurs.
final String text = mBuffer.toString();
if (mListener != null) {
Log.d(TAG, "----> Long Click Occurs on TextView with ID: " + mWidget.getId() + "\n" +
"Text: " + text + "\n<----");
mListener.onLongClick(text);
}
}
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
// Notified when tap occurs.
final String linkText = getLinkText(mWidget, mBuffer, event);
LinkType linkType = LinkType.NONE;
if (Patterns.PHONE.matcher(linkText).matches()) {
linkType = LinkType.PHONE;
}
else if (Patterns.WEB_URL.matcher(linkText).matches()) {
linkType = LinkType.WEB_URL;
}
else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
linkType = LinkType.EMAIL_ADDRESS;
}
if (mListener != null) {
Log.d(TAG, "----> Tap Occurs on TextView with ID: " + mWidget.getId() + "\n" +
"Link Text: " + linkText + "\n" +
"Link Type: " + linkType + "\n<----");
mListener.onLinkClicked(linkText, linkType);
}
return false;
}
private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
return buffer.subSequence(buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0])).toString();
}
return "";
}
}
}
TextView tv = (TextView) v.findViewById(R.id.textview);
tv.setText(Html.fromHtml("<a href='test'>test</a>"));
textView.setMovementMethod(new TextViewClickMovement(this, context));
Hope this helps! You can find code here.
set /p line= < file.csv
echo %line%
it will return first line of your file in cmd Windows in variable %line%.
Just finish it up.
string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";
DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
DataSet ds = new DataSet();
using (SqlCommand cmd = new SqlCommand(
sqlCommand, new SqlConnection(connectionString)))
{
cmd.Connection.Open();
DataTable table = new DataTable();
table.Load(cmd.ExecuteReader());
ds.Tables.Add(table);
}
return ds;
}
Make sure you verify your setting for "Prefer 32-bit". In my case Visual Studio 2012 had this setting checked by default. Trying to use anything from an external DLL failed until I unchecked "Prefer 32-bit".
The method takes a regular expression, not a string, and the dot has a special meaning in regular expressions. Escape it like so split("\\.")
. You need a double backslash, the second one escapes the first.
Using the old mysql_native_password
works:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YourRootPassword';
-- or
CREATE USER 'foo'@'%' IDENTIFIED WITH mysql_native_password BY 'bar';
-- then
FLUSH PRIVILEGES;
This is because caching_sha2_password
is introduced in MySQL 8.0, but the Node.js version is not implemented yet. You can see this pull request and this issue for more information. Probably a fix will come soon!
While this is an old topic, I just wanted to point out that .call is slightly faster than .apply. I can't tell you exactly why.
See jsPerf, http://jsperf.com/test-call-vs-apply/3
[UPDATE!
]
Douglas Crockford mentions briefly the difference between the two, which may help explain the performance difference... http://youtu.be/ya4UHuXNygM?t=15m52s
Apply takes an array of arguments, while Call takes zero or more individual parameters! Ah hah!
.apply(this, [...])
.call(this, param1, param2, param3, param4...)
In my case, I had a Class with a method in it. The method did not have 'self' as the first parameter and the error was being thrown when I made a call to the method. Once I added 'self,' to the method's parameter list, it was fine.
See this post where I have submitted Utils.java example to provide pure-java implementations and works without WifiManager. Some android devices may not have wifi available or are using ethernet wiring.
Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6
Building on Darren's answer, to use Notepad++ you can simply do this (all on one line):
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Obviously, the C:/Program Files/Notepad++/notepad++.exe
part should be the path to the Notepad++ executable on your system. For example, it might be C:/Program Files (x86)/Notepad++/notepad++.exe
.
It works like a charm for me.
Actually, technically when indented properly, it would be:
if (condition) {
...
} else {
if (condition) {
...
} else {
...
}
}
There is no else if
, strictly speaking.
(Update: Of course, as pointed out, the above is not considered good style.)
With these two steps we can check if it LL(1) or not. Both of them have to be satisfied.
1.If we have the production:A->a1|a2|a3|a4|.....|an. Then,First(a(i)) intersection First(a(j)) must be phi(empty set)[a(i)-a subscript i.]
2.For every non terminal 'A',if First(A) contains epsilon Then First(A) intersection Follow(A) must be phi(empty set).
Passing no-sandbox to exec seems important for jenkins on windows in foreground or as service. Here's my solution
chromedriver fails on windows jenkins slave running in foreground
To add to bhadra's list of idiomatic guides:
Checkout Anthony Baxter's presentation on Effective Python Programming (from OSON 2005).
An excerpt:
# dict's setdefault method turns this:
if key in dictobj:
dictobj[key].append(val)
else:
dictobj[key] = [val]
# into this:
dictobj.setdefault(key,[]).append(val)
This command should fix it.
docker run --rm -it -v ${PWD}:c:\data
mirkohaaser/docker-clitools
{PWD} is the host current folder. after the :
is the container folder.
If the mounting is correct then files will be listed in the director c:\data
in the container.
For an excel writer you might need the following:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${apache.poi.version}</version>
</dependency>
i have used following method to use input data from excel sheet: Need to import following as well
import jxl.Workbook;
then
Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0);
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();
it will Work
See Creating and modifying HTML at what used to be called the Web Standards Curriculum.
Use the createElement
, createTextNode
and appendChild
methods.
Other options, instead of using a custom XML file, we can use a more user friendly file format: JSON or YAML file.
You can store your settings file in multiple special folders (for all users and per user) as listed here Environment.SpecialFolder Enumeration and multiple files (default read only, per role, per user, etc.)
If you choose to use multiple settings, you can merge those settings: For example, merging settings for default + BasicUser + AdminUser. You can use your own rules: the last one overrides the value, etc.
I have studied a number of Go projects and there is a fair bit of variation. You can kind of tell who is coming from C and who is coming from Java, as the former dump just about everything in the projects root directory in a main
package, and the latter tend to put everything in a src
directory. Neither is optimal however. Each have consequences because they affect import paths and how others can reuse them.
To get the best results I have worked out the following approach.
myproj/
main/
mypack.go
mypack.go
Where mypack.go
is package mypack
and main/mypack.go
is (obviously) package main
.
If you need additional support files you have two choices. Either keep them all in the root directory, or put private support files in a lib
subdirectory. E.g.
myproj/
main/
mypack.go
myextras/
someextra.go
mypack.go
mysupport.go
Or
myproj.org/
lib/
mysupport.go
myextras/
someextra.go
main/
mypack.go
mypage.go
Only put the files in a lib
directory if they are not intended to be imported by another project. In other words, if they are private support files. That's the idea behind having lib
--to separate public from private interfaces.
Doing things this way will give you a nice import path, myproj.org/mypack
to reuse the code in other projects. If you use lib
then internal support files will have an import path that is indicative of that, myproj.org/lib/mysupport
.
When building the project, use main/mypack
, e.g. go build main/mypack
. If you have more than one executable you can also separate those under main
without having to create separate projects. e.g. main/myfoo/myfoo.go
and main/mybar/mybar.go
.
No import is necessary as long as you declare both a.go
and b.go
to be in the same package. Then, you can use go run
to recognize multiple files with:
$ go run a.go b.go
Here you go, no frameworks, short and simple:
var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;
window.addEventListener('scroll', function(){
if (document.documentElement.scrollTop > elTop){
el.style.position = 'fixed';
el.style.top = '0px';
}
else
{
el.style.position = 'static';
el.style.top = 'auto';
}
});
Handle the dragstart
event and return false
.
in vs 2019 Version 16.8.2 right click on you project name and click on "Edit Project File"
Remove the spaces around your =
:
<div>
<input type="text" [(ngModel)]="str" name="str">
</div>
But you need to have the variable named str
on back-end, than its should work fine.
Just a little tip:
I prefer to use the variant RLIKE (exactly the same command as REGEXP) as it sounds more like natural language, and is shorter; well, just 1 char.
The "R" prefix is for Reg. Exp., of course.
The return statements should place in one line. Or the other option is to remove the curly brackets that bound the HTML statement.
example:
return posts.map((post, index) =>
<div key={index}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
);
I know this is old, but it is actually very possible.
Go to your WinSCP profile (Session > Sites > Site Manager)
Click on Edit > Advanced... > Environment > SFTP
Insert sudo su -c /usr/lib/sftp-server
in "SFTP Server" (note this path might be different in your system)
Save and connect
This script is ok except for this case that of course, I've met :
INSERT INTO "requestcomparison_stopword" VALUES(149,'f'); INSERT INTO "requestcomparison_stopword" VALUES(420,'t');
The script should give this output :
INSERT INTO requestcomparison_stopword VALUES(149,'f'); INSERT INTO requestcomparison_stopword VALUES(420,'t');
But gives instead that output :
INSERT INTO requestcomparison_stopword VALUES(1490; INSERT INTO requestcomparison_stopword VALUES(4201;
with some strange non-ascii characters around the last 0 and 1.
This didn't show up anymore when I commented the following lines of the code (43-46) but others problems appeared:
line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
line = line.replace('THIS_IS_TRUE', '1')
line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
line = line.replace('THIS_IS_FALSE', '0')
This is just a special case, when we want to add a value being 'f' or 't' but I'm not really comfortable with regular expressions, I just wanted to spot this case to be corrected by someone.
Anyway thanks a lot for that handy script !!!
Lots of answers found here for creating multidimensional arrays in bash.
And without exception, all are obtuse and difficult to use.
If MD arrays are a required criteria, it is time to make a decision:
Use a language that supports MD arrays
My preference is Perl. Most would probably choose Python. Either works.
Store the data elsewhere
JSON and jq have already been suggested. XML has also been suggested, though for your use JSON and jq would likely be simpler.
It would seem though that Bash may not be the best choice for what you need to do.
Sometimes the correct question is not "How do I do X in tool Y?", but rather "Which tool would be best to do X?"
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
In my case , i accidentally imported my library's R. class not my app module's R. After editing this, it is resolved.
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
Just changing utf8mb4
to utf8
when creating tables solved my problem. For example: CREATE TABLE ... DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
to CREATE TABLE ... DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
.
This should make it work in both cases
function onDateChange() {
// Do something here
}
$('#dpd1').bind('changeDate', onDateChange);
$('#dpd1').bind('input', onDateChange);
This worked great I just add the -a option to ping to resolve the hostname. Thanks https://stackoverflow.com/users/4447323/wombat
@echo off setlocal enabledelayedexpansion set OUTPUT_FILE=result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -n 1 -a %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
You use this command in phpMyAdmin SQL Part:
GRANT SELECT , INSERT , UPDATE , DELETE ON phpmyadmin.* TO `pma`@`localhost` IDENTIFIED BY ''
The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):
import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')
plt.show()
print(fpath)
will show you where you should put the .ttf.
You can see the output here: https://matplotlib.org/gallery/api/font_file.html
Try using Binding Values. You cannot use variables as you do in T-SQL but you can use "parameters". I hope the following link is usefull.Binding Values
You shouldn't have to worry about the stack leaking memory (it is highly uncommon). The only time you can have the stack get out of control is with infinite (or really deep) recursion.
This is just the heap. Sorry, didn't read your question fully at first.
You need to run the JVM with the following command line argument.
-Xmx<ammount of memory>
Example:
-Xmx1024m
That will allow a max of 1GB of memory for the JVM.
This answer is taken from TuxRadar:
When running PHP through your web server, there are two distinct options: running it using PHP's CGI SAPI, or running it as a module for the web server. Each have their own benefits, but, overall, the module is generally preferred.
Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable, giving it the script you called, each time you visit a page. That means each time you load a page, PHP needs to read php.ini and set its settings, it needs to load all its extensions, and then it needs to start work parsing the script - there is a lot of repeated work.
When you run PHP as a module, PHP literally sits inside your web server - it starts only once, loads its settings and extensions only once, and can also store information across sessions. For example, PHP accelerators rely on PHP being able to save cached data across requests, which is impossible using the CGI version.
The obvious advantage of using PHP as a module is speed - you will see a big speed boost if you convert from CGI to a module. Many people, particularly Windows users, do not realise this, and carry on using the php.exe CGI SAPI, which is a shame - the module is usually three to five times faster.
There is one key advantage to using the CGI version, though, and that is that PHP reads its settings every time you load a page. With PHP running as a module, any changes you make in the php.ini file do not kick in until you restart your web server, which makes the CGI version preferable if you are testing a lot of new settings and want to see instant responses.
also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.
the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.
what you are trying to do is more a segmentedbutton than an imagebutton list.
here http://blog.bookworm.at/2010/10/segmented-controls-in-android.html is an example on how to do so. The basic idea is to customize RadioButton instead of ImageButton, since the RadioButton will have the checked state you need
I know this is late but I ended up here with a search for my error 500 with DEBUG=False
, in my case it did turn out to be the ALLOWED_HOSTS
but I was using os.environ.get('variable')
to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False
:
# settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'mysite.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers':['file'],
'propagate': True,
'level':'DEBUG',
},
'MYAPP': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}
Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx
Let's First look at MVC
The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.
There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.
There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.
The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.
MVP – Model View Presenter
Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:
The input begins with the View, not the Presenter.
There is a one-to-one mapping between the View and the associated Presenter.
The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.
The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.
MVVM – Model View View Model
So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:
The input begins with the View, not the View Model.
While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.
The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.
For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.
static String getBase64EncodedCipherText(String cipherText) {
byte[] cText = cipherText.getBytes();
// return an ISO-8859-1 encoded String
return Base64.getEncoder().encodeToString(cText);
}
static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
return new String((Base64.getDecoder().decode(encodedCipherText)));
}
public static void main(String[] args) {
try {
String cText = getRawCipherText(null, "Hello World of Encryption...");
System.out.println("Text to encrypt/encode: Hello World of Encryption...");
// This output is a simple sanity check to display that the text
// has indeed been converted to a cipher text which
// is unreadable by all but the most intelligent of programmers.
// It is absolutely inhuman of me to do such a thing, but I am a
// rebel and cannot be trusted in any way. Please look away.
System.out.println("RAW CIPHER TEXT: " + cText);
cText = getBase64EncodedCipherText(cText);
System.out.println("BASE64 ENCODED: " + cText);
// There he goes again!!
System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText));
System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
} catch (Exception e) {
e.printStackTrace();
}
}
The output looks like:
Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED: q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...
You could do this:
InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));
Note the UTF-8
encoding. You should specify the character set that you want the bytes encoded into. It's common to choose UTF-8
if you don't specifically need anything else. Otherwise if you select nothing you'll get the default encoding that can vary between systems. From the JavaDoc:
The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.
There are several ways, like:
where some_column is null or some_column = ''
or
where ifnull(some_column, '') = ''
or
where coalesce(some_column, '') = ''
of
where ifnull(length(some_column), 0) = 0
You can load both json strings into Python Dictionaries and then combine. This will only work if there are unique keys in each json string.
import json
a = json.loads(jsonStringA)
b = json.loads(jsonStringB)
c = dict(a.items() + b.items())
# or c = dict(a, **b)
It is not a matter of taste. Here are some definitive rules.
If you want to refer to a statically declared variable within the scope in which it was declared then use a C++ reference, and it will be perfectly safe. The same applies to a statically declared smart pointer. Passing parameters by reference is an example of this usage.
If you want to refer to anything from a scope that is wider than the scope in which it is declared then you should use a reference counted smart pointer for it to be perfectly safe.
You can refer to an element of a collection with a reference for syntactic convenience, but it is not safe; the element can be deleted at anytime.
To safely hold a reference to an element of a collection you must use a reference counted smart pointer.
Like that:
SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299'
The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're just trying to use a conditional (e.g. is the last character 'g'), you could also do the following:
if (str.endsWith("g")) {
or, strings
if (str.endsWith("bar")) {
Import library like:
import CoreLocation
set Delegate:
CLLocationManagerDelegate
Take variable like:
var locationManager:CLLocationManager!
On viewDidLoad() write this pretty code:
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
Write CLLocation delegate methods:
//MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation :CLLocation = locations[0] as CLLocation
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
self.labelLat.text = "\(userLocation.coordinate.latitude)"
self.labelLongi.text = "\(userLocation.coordinate.longitude)"
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
if (error != nil){
print("error in reverseGeocode")
}
let placemark = placemarks! as [CLPlacemark]
if placemark.count>0{
let placemark = placemarks![0]
print(placemark.locality!)
print(placemark.administrativeArea!)
print(placemark.country!)
self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
Now set permission for access the location, so add these key value into your info.plist file
<key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
100% working without any issue. TESTED
Use below code to get the solution:
textView.setText(fromHtml("<Your Html Text>"))
Utitilty Method
public static Spanned fromHtml(String text)
{
Spanned result;
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(text);
}
return result;
}
It is impossible for both (?=foo)
and (?=baz)
to match at the same time. It would require the next character to be both f
and b
simultaneously which is impossible.
Perhaps you want this instead:
(?=.*foo)(?=.*baz)
This says that foo
must appear anywhere and baz
must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).
Instead of using ->bindParam()
you can pass the data only at the time of ->execute()
:
$data = [ ':item_name' => $_POST['item_name'], ':item_type' => $_POST['item_type'], ':item_price' => $_POST['item_price'], ':item_description' => $_POST['item_description'], ':image_location' => 'images/'.$_FILES['file']['name'], ':status' => 0, ':id' => 0, ]; $stmt->execute($data);
In this way you would know exactly what values are going to be sent.
After Migrated to Angular8, core-js/es6
or core-js/es7
Will not work.
You have to simply replace import core-js/es/
For ex.
import 'core-js/es6/symbol'
to
import 'core-js/es/symbol'
This will work properly.
If this is your first push
just change the
git push <repo name> master
change it like this!
git push -f <repo name> master
It is because generics were added on to java after they made it, so its kinda clunky because the original makers of java thought that when making an array the type would be specified in the making of it. So that does not work with generics so you have to do E[] array=(E[]) new Object[15]; This compiles but it gives a warning.
VS 2010 Express is no longer linked to any VS Express pages (that I found). I did find this link to the ISO which I used and it fixed the errors mentioned here.
http://download.microsoft.com/download/1/E/5/1E5F1C0A-0D5B-426A-A603-1798B951DDAE/VS2010Express1.iso
Note: Also make sure you have x86 everything (Python + Postgresql) or you'll get other errors. I did not try x64 everything.
It's because there is no long
in javascript.
The key to splitting your string into an array is the multi character delimiter of ", "
. Any solution using IFS
for multi character delimiters is inherently wrong since IFS is a set of those characters, not a string.
If you assign IFS=", "
then the string will break on EITHER ","
OR " "
or any combination of them which is not an accurate representation of the two character delimiter of ", "
.
You can use awk
or sed
to split the string, with process substitution:
#!/bin/bash
str="Paris, France, Europe"
array=()
while read -r -d $'\0' each; do # use a NUL terminated field separator
array+=("$each")
done < <(printf "%s" "$str" | awk '{ gsub(/,[ ]+|$/,"\0"); print }')
declare -p array
# declare -a array=([0]="Paris" [1]="France" [2]="Europe") output
It is more efficient to use a regex you directly in Bash:
#!/bin/bash
str="Paris, France, Europe"
array=()
while [[ $str =~ ([^,]+)(,[ ]+|$) ]]; do
array+=("${BASH_REMATCH[1]}") # capture the field
i=${#BASH_REMATCH} # length of field + delimiter
str=${str:i} # advance the string by that length
done # the loop deletes $str, so make a copy if needed
declare -p array
# declare -a array=([0]="Paris" [1]="France" [2]="Europe") output...
With the second form, there is no sub shell and it will be inherently faster.
Edit by bgoldst: Here are some benchmarks comparing my readarray
solution to dawg's regex solution, and I also included the read
solution for the heck of it (note: I slightly modified the regex solution for greater harmony with my solution) (also see my comments below the post):
## competitors
function c_readarray { readarray -td '' a < <(awk '{ gsub(/, /,"\0"); print; };' <<<"$1, "); unset 'a[-1]'; };
function c_read { a=(); local REPLY=''; while read -r -d ''; do a+=("$REPLY"); done < <(awk '{ gsub(/, /,"\0"); print; };' <<<"$1, "); };
function c_regex { a=(); local s="$1, "; while [[ $s =~ ([^,]+),\ ]]; do a+=("${BASH_REMATCH[1]}"); s=${s:${#BASH_REMATCH}}; done; };
## helper functions
function rep {
local -i i=-1;
for ((i = 0; i<$1; ++i)); do
printf %s "$2";
done;
}; ## end rep()
function testAll {
local funcs=();
local args=();
local func='';
local -i rc=-1;
while [[ "$1" != ':' ]]; do
func="$1";
if [[ ! "$func" =~ ^[_a-zA-Z][_a-zA-Z0-9]*$ ]]; then
echo "bad function name: $func" >&2;
return 2;
fi;
funcs+=("$func");
shift;
done;
shift;
args=("$@");
for func in "${funcs[@]}"; do
echo -n "$func ";
{ time $func "${args[@]}" >/dev/null 2>&1; } 2>&1| tr '\n' '/';
rc=${PIPESTATUS[0]}; if [[ $rc -ne 0 ]]; then echo "[$rc]"; else echo; fi;
done| column -ts/;
}; ## end testAll()
function makeStringToSplit {
local -i n=$1; ## number of fields
if [[ $n -lt 0 ]]; then echo "bad field count: $n" >&2; return 2; fi;
if [[ $n -eq 0 ]]; then
echo;
elif [[ $n -eq 1 ]]; then
echo 'first field';
elif [[ "$n" -eq 2 ]]; then
echo 'first field, last field';
else
echo "first field, $(rep $[$1-2] 'mid field, ')last field";
fi;
}; ## end makeStringToSplit()
function testAll_splitIntoArray {
local -i n=$1; ## number of fields in input string
local s='';
echo "===== $n field$(if [[ $n -ne 1 ]]; then echo 's'; fi;) =====";
s="$(makeStringToSplit "$n")";
testAll c_readarray c_read c_regex : "$s";
}; ## end testAll_splitIntoArray()
## results
testAll_splitIntoArray 1;
## ===== 1 field =====
## c_readarray real 0m0.067s user 0m0.000s sys 0m0.000s
## c_read real 0m0.064s user 0m0.000s sys 0m0.000s
## c_regex real 0m0.000s user 0m0.000s sys 0m0.000s
##
testAll_splitIntoArray 10;
## ===== 10 fields =====
## c_readarray real 0m0.067s user 0m0.000s sys 0m0.000s
## c_read real 0m0.064s user 0m0.000s sys 0m0.000s
## c_regex real 0m0.001s user 0m0.000s sys 0m0.000s
##
testAll_splitIntoArray 100;
## ===== 100 fields =====
## c_readarray real 0m0.069s user 0m0.000s sys 0m0.062s
## c_read real 0m0.065s user 0m0.000s sys 0m0.046s
## c_regex real 0m0.005s user 0m0.000s sys 0m0.000s
##
testAll_splitIntoArray 1000;
## ===== 1000 fields =====
## c_readarray real 0m0.084s user 0m0.031s sys 0m0.077s
## c_read real 0m0.092s user 0m0.031s sys 0m0.046s
## c_regex real 0m0.125s user 0m0.125s sys 0m0.000s
##
testAll_splitIntoArray 10000;
## ===== 10000 fields =====
## c_readarray real 0m0.209s user 0m0.093s sys 0m0.108s
## c_read real 0m0.333s user 0m0.234s sys 0m0.109s
## c_regex real 0m9.095s user 0m9.078s sys 0m0.000s
##
testAll_splitIntoArray 100000;
## ===== 100000 fields =====
## c_readarray real 0m1.460s user 0m0.326s sys 0m1.124s
## c_read real 0m2.780s user 0m1.686s sys 0m1.092s
## c_regex real 17m38.208s user 15m16.359s sys 2m19.375s
##
to make this work in both FF and IE you must write both ways:
button_element.setAttribute('onclick','doSomething();'); // for FF
button_element.onclick = function() {doSomething();}; // for IE
thanks to this post.
UPDATE: This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:
// get old onclick attribute
var onclick = button_element.getAttribute("onclick");
// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") {
button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome
// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
button_element.onclick = function() {
doSomething();
onclick();
}; // for IE7
}
Try ssh -t -t
(or ssh -tt
for short) to force pseudo-tty allocation even if stdin isn't a terminal.
See also: Terminating SSH session executed by bash script
From ssh manpage:
-T Disable pseudo-tty allocation.
-t Force pseudo-tty allocation. This can be used to execute arbitrary
screen-based programs on a remote machine, which can be very useful,
e.g. when implementing menu services. Multiple -t options force tty
allocation, even if ssh has no local tty.
Make sure the PNGs are fully opaque before creating the video
e.g. with imagemagick, give them a black background:
convert 0.png -background black -flatten +matte 0_opaque.png
From my tests, no bitrate or codec is sufficient to make the video look good if you feed ffmpeg PNGs with transparency
An alternative that always exists for learning purpose is to build your custom collector through Collector.of() though toMap() JDK collector here is succinct (+1 here) .
Map<String,Integer> newMap = givenMap.
entrySet().
stream().collect(Collector.of
( ()-> new HashMap<String,Integer>(),
(mutableMap,entryItem)-> mutableMap.put(entryItem.getKey(),Integer.parseInt(entryItem.getValue())),
(map1,map2)->{ map1.putAll(map2); return map1;}
));
Easily you can do it.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
Credits: https://freakycoder.com/android-notes-24-how-to-add-back-button-at-toolbar-941e6577418e
To avoid any ambiguity, use the utilities methods from SwingUtilities :
SwingUtilities.isLeftMouseButton(MouseEvent anEvent)
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
You should not expose this info. in public, specially api keys. It may lead to a privacy leak.
Before making the website public you should hide it. You can do it in 2 or more ways
this is how I implement it .
let dictionary = self.convertStringToDictionary(responceString)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SOCKET_UPDATE"), object: dictionary)
you can just do
select rownum, l.* from student l where name like %ram%
this assigns the row number as the rows are fetched (so no guaranteed ordering of course).
if you wanted to order first do:
select rownum, l.*
from (select * from student l where name like %ram% order by...) l;
We're using Jira 6.2 and I use this query:
updatedDate > startOfDay(-1d) AND updatedDate < endOfDay(-1)
to return all of the issues that were updated from the previous day. You can combine with whichever queries you want to return the appropriate issues for the previous day.
If you can already see the SQL being printed, that means you have the code below in your hibernate.cfg.xml:
<property name="show_sql">true</property>
To print the bind parameters as well, add the following to your log4j.properties file:
log4j.logger.net.sf.hibernate.type=debug
You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.
char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));
Output:
Character: 1
Character: 49
Here is how it works for me with no Servlet use.
Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml
In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )
Now let's use class loader:
InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
I assume by "didn't work" you mean that it's giving you a timestamp instead of the formatted date, because you were doing it correctly:
$effectiveDate = strtotime("+3 months", strtotime($effectiveDate)); // returns timestamp
echo date('Y-m-d',$effectiveDate); // formatted version
This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.
Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.
function f(input, callback) {
var value;
// Assume the async call always succeed
async_call(input, function(result) { callback(result) };
}
The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.
I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:
$("#addComment").click(function() {
if(typeof TinyMCE === "undefined") {
$.ajax({
url: "tinymce.js",
dataType: "script",
cache: true,
success: function() {
TinyMCE.init();
}
});
}
});
The getScript()
function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:
http://www.yoursite.com/js/tinymce.js?_=1399055841840
If a user clicks the #addComment
link multiple times, tinymce.js
will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.
===
Alternatively, in the getScript()
documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript()
function as follows:
jQuery.cachedScript = function( url, options ) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
===
Or, if you want to disable caching globally, you can do so using ajaxSetup()
as follows:
$.ajaxSetup({
cache: true
});
Python does everything that other programming languages do in half the dev time... and so does Google!!! Check out Unladen Swallow if you disagree.
Wait, this is a fact. Does it still qualify as an answer to this question?
version note: this is no longer value in iOS 9 & 10, as they support custom keyboard sizes.
This depends on the model and the QuickType bar:
Try again with chmod -R 755 /var/www/html/test/app/storage
. Use with sudo for Operation not permitted
in chmod. Use Check owner permission if still having the error.
In case of hooks, you should use useEffect
hook.
const [fruit, setFruit] = useState('');
setFruit('Apple');
useEffect(() => {
console.log('Fruit', fruit);
}, [fruit])
Try setting both min-height
and min-width
, with display:block
:
img {
display:block;
min-height:100%;
min-width:100%;
}
(fiddle)
Provided your image's containing element is position:relative
or position:absolute
, the image will cover the container. However, it will not be centred.
You can easily centre the image if you know whether it will overflow horizontally (set margin-left:-50%
) or vertically (set margin-top:-50%
). It may be possible to use CSS media queries (and some mathematics) to figure that out.
Bootstrap 4 Solution
<div class="btn-group w-100">
<button type="button" class="btn">One</button>
<button type="button" class="btn">Two</button>
<button type="button" class="btn">Three</button>
</div>
You basically tell the btn-group
container to have width 100% by adding w-100
class to it. The buttons inside will fill in the whole space automatically.
To complement Jakub's answer, if you have access to the remote git server in ssh, you can go into the git remote directory and set:
user@remote$ git config receive.denyNonFastforwards false
Then go back to your local repo, try again to do your commit with --force
:
user@local$ git push origin +master:master --force
And finally revert the server's setting in the original protected state:
user@remote$ git config receive.denyNonFastforwards true
It should just be get{varname} like every other getter. Changing it to "is" doesn't stop bad variable names, it just makes another unnecessary rule.
Consider program generated code, or reflection derivations.
It's a non-useful convention that should be dropped at the first available opportunity.
I deal with the same problem (Jenkins multibranch pipeline) - having only commit information and trying to find a branch name where this commit originally came from. It must work for remote branches, local copies are not available.
This is what I work with:
git rev-parse HEAD | xargs git name-rev
Optionally you can strip the output:
git rev-parse HEAD | xargs git name-rev | cut -d' ' -f2 | sed 's/remotes\/origin\///g'
It looks like you are trying to do this?
Iterate and mutate an array using Array.prototype.splice
var pre = document.getElementById('out');
function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}
var review = ['a', 'b', 'c', 'b', 'a'];
review.forEach(function(item, index, object) {
if (item === 'a') {
object.splice(index, 1);
}
});
log(review);
_x000D_
<pre id="out"></pre>
_x000D_
Which works fine for simple case where you do not have 2 of the same values as adjacent array items, other wise you have this problem.
var pre = document.getElementById('out');
function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}
var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];
review.forEach(function(item, index, object) {
if (item === 'a') {
object.splice(index, 1);
}
});
log(review);
_x000D_
<pre id="out"></pre>
_x000D_
So what can we do about this problem when iterating and mutating an array? Well the usual solution is to work in reverse. Using ES3 while but you could use for sugar if preferred
var pre = document.getElementById('out');
function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}
var review = ['a' ,'a', 'b', 'c', 'b', 'a', 'a'],
index = review.length - 1;
while (index >= 0) {
if (review[index] === 'a') {
review.splice(index, 1);
}
index -= 1;
}
log(review);
_x000D_
<pre id="out"></pre>
_x000D_
Ok, but you wanted to use ES5 iteration methods. Well and option would be to use Array.prototype.filter but this does not mutate the original array but creates a new one, so while you can get the correct answer it is not what you appear to have specified.
We could also use ES5 Array.prototype.reduceRight, not for its reducing property by rather its iteration property, i.e. iterate in reverse.
var pre = document.getElementById('out');
function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}
var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];
review.reduceRight(function(acc, item, index, object) {
if (item === 'a') {
object.splice(index, 1);
}
}, []);
log(review);
_x000D_
<pre id="out"></pre>
_x000D_
Or we could use ES5 Array.protoype.indexOf like so.
var pre = document.getElementById('out');
function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}
var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'],
index = review.indexOf('a');
while (index !== -1) {
review.splice(index, 1);
index = review.indexOf('a');
}
log(review);
_x000D_
<pre id="out"></pre>
_x000D_
But you specifically want to use ES5 Array.prototype.forEach, so what can we do? Well we need to use Array.prototype.slice to make a shallow copy of the array and Array.prototype.reverse so we can work in reverse to mutate the original array.
var pre = document.getElementById('out');
function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}
var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];
review.slice().reverse().forEach(function(item, index, object) {
if (item === 'a') {
review.splice(object.length - 1 - index, 1);
}
});
log(review);
_x000D_
<pre id="out"></pre>
_x000D_
Finally ES6 offers us some further alternatives, where we do not need to make shallow copies and reverse them. Notably we can use Generators and Iterators. However support is fairly low at present.
var pre = document.getElementById('out');
function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}
function* reverseKeys(arr) {
var key = arr.length - 1;
while (key >= 0) {
yield key;
key -= 1;
}
}
var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];
for (var index of reverseKeys(review)) {
if (review[index] === 'a') {
review.splice(index, 1);
}
}
log(review);
_x000D_
<pre id="out"></pre>
_x000D_
Something to note in all of the above is that, if you were stripping NaN from the array then comparing with equals is not going to work because in Javascript NaN === NaN
is false. But we are going to ignore that in the solutions as it it yet another unspecified edge case.
So there we have it, a more complete answer with solutions that still have edge cases. The very first code example is still correct but as stated, it is not without issues.
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
Also don't forget:
$ s = " I have white space ".split
=> ["I", "have", "white", "space"]
I was also facing the same issue with the latest version of @angular/material i.e. "^9.2.3" So I found out a solution of this. If you go to the folder of @angular/material inside node_modules, you can find a file naming index.d.ts, in that file paste the below code. With this change in the index file you will be able to import the modules using import statements from @angular/material directly. (P.S. If you face error in any of the below statements please comment that.)
export * from '@angular/material/core';
export * from '@angular/material/icon';
export * from '@angular/material/autocomplete';
export * from '@angular/material/badge';
export * from '@angular/material/bottom-sheet';
export * from '@angular/material/button';
export * from '@angular/material/button-toggle';
export * from '@angular/material/card';
export * from '@angular/material/checkbox';
export * from '@angular/material/chips';
export * from '@angular/material/stepper';
export * from '@angular/material/datepicker'
export * from '@angular/material/dialog';
export * from '@angular/material/divider';
export * from '@angular/material/esm2015';
export * from '@angular/material/form-field';
export * from '@angular/material/esm5';
export * from '@angular/material/expansion';
export * from '@angular/material/grid-list';
export * from '@angular/material/icon';
export * from '@angular/material/input';
export * from '@angular/material/list';
export * from '@angular/material/menu';
export * from '@angular/material/paginator';
export * from '@angular/material/progress-bar';
export * from '@angular/material/progress-spinner';
export * from '@angular/material/radio';
export * from '@angular/material/stepper';
export * from '@angular/material/select';
export * from '@angular/material/sidenav';
export * from '@angular/material/slider';
export * from '@angular/material/slide-toggle';
export * from '@angular/material/snack-bar';
export * from '@angular/material/sort';
export * from '@angular/material/table';
export * from '@angular/material/tabs';
export * from '@angular/material/toolbar';
export * from '@angular/material/tooltip';
export * from '@angular/material/tree';
You can try to do json.loads()
, which will throw a ValueError
if the string you pass can't be decoded as JSON.
In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.
When is lexing enough, when do you need EBNF?
EBNF really doesn't add much to the power of grammars. It's just a convenience / shortcut notation / "syntactic sugar" over the standard Chomsky's Normal Form (CNF) grammar rules. For example, the EBNF alternative:
S --> A | B
you can achieve in CNF by just listing each alternative production separately:
S --> A // `S` can be `A`,
S --> B // or it can be `B`.
The optional element from EBNF:
S --> X?
you can achieve in CNF by using a nullable production, that is, the one which can be replaced by an empty string (denoted by just empty production here; others use epsilon or lambda or crossed circle):
S --> B // `S` can be `B`,
B --> X // and `B` can be just `X`,
B --> // or it can be empty.
A production in a form like the last one B
above is called "erasure", because it can erase whatever it stands for in other productions (product an empty string instead of something else).
Zero-or-more repetiton from EBNF:
S --> A*
you can obtan by using recursive production, that is, one which embeds itself somewhere in it. It can be done in two ways. First one is left recursion (which usually should be avoided, because Top-Down Recursive Descent parsers cannot parse it):
S --> S A // `S` is just itself ended with `A` (which can be done many times),
S --> // or it can begin with empty-string, which stops the recursion.
Knowing that it generates just an empty string (ultimately) followed by zero or more A
s, the same string (but not the same language!) can be expressed using right-recursion:
S --> A S // `S` can be `A` followed by itself (which can be done many times),
S --> // or it can be just empty-string end, which stops the recursion.
And when it comes to +
for one-or-more repetition from EBNF:
S --> A+
it can be done by factoring out one A
and using *
as before:
S --> A A*
which you can express in CNF as such (I use right recursion here; try to figure out the other one yourself as an exercise):
S --> A S // `S` can be one `A` followed by `S` (which stands for more `A`s),
S --> A // or it could be just one single `A`.
Knowing that, you can now probably recognize a grammar for a regular expression (that is, regular grammar) as one which can be expressed in a single EBNF production consisting only from terminal symbols. More generally, you can recognize regular grammars when you see productions similar to these:
A --> // Empty (nullable) production (AKA erasure).
B --> x // Single terminal symbol.
C --> y D // Simple state change from `C` to `D` when seeing input `y`.
E --> F z // Simple state change from `E` to `F` when seeing input `z`.
G --> G u // Left recursion.
H --> v H // Right recursion.
That is, using only empty strings, terminal symbols, simple non-terminals for substitutions and state changes, and using recursion only to achieve repetition (iteration, which is just linear recursion - the one which doesn't branch tree-like). Nothing more advanced above these, then you're sure it's a regular syntax and you can go with just lexer for that.
But when your syntax uses recursion in a non-trivial way, to produce tree-like, self-similar, nested structures, like the following one:
S --> a S b // `S` can be itself "parenthesized" by `a` and `b` on both sides.
S --> // or it could be (ultimately) empty, which ends recursion.
then you can easily see that this cannot be done with regular expression, because you cannot resolve it into one single EBNF production in any way; you'll end up with substituting for S
indefinitely, which will always add another a
s and b
s on both sides. Lexers (more specifically: Finite State Automata used by lexers) cannot count to arbitrary number (they are finite, remember?), so they don't know how many a
s were there to match them evenly with so many b
s. Grammars like this are called context-free grammars (at the very least), and they require a parser.
Context-free grammars are well-known to parse, so they are widely used for describing programming languages' syntax. But there's more. Sometimes a more general grammar is needed -- when you have more things to count at the same time, independently. For example, when you want to describe a language where one can use round parentheses and square braces interleaved, but they have to be paired up correctly with each other (braces with braces, round with round). This kind of grammar is called context-sensitive. You can recognize it by that it has more than one symbol on the left (before the arrow). For example:
A R B --> A S B
You can think of these additional symbols on the left as a "context" for applying the rule. There could be some preconditions, postconditions etc. For example, the above rule will substitute R
into S
, but only when it's in between A
and B
, leaving those A
and B
themselves unchanged. This kind of syntax is really hard to parse, because it needs a full-blown Turing machine. It's a whole another story, so I'll end here.
Width and/or height in tables are not standard anymore; as Ianzz says, they are deprecated. Instead the best way to do this is to have a block element inside your table cell that will hold the cell open to your desired size:
<table>
<tr>
<td valign="top">
<div class="left_menu">
<div class="menu_item">
<a href="#">Home</a>
</div>
</div>
</td>
<td valign="top" class="content">Content</td>
</tr>
</table>
CSS
.content {
width: 1000px;
}
.left_menu {
background: none repeat scroll 0 0 #333333;
border-radius: 5px 5px 5px 5px;
font-family: Arial,Helvetica,sans-serif;
font-size: 12px;
font-weight: bold;
padding: 5px;
width: 200px;
}
.menu_item {
background: none repeat scroll 0 0 #CCCCCC;
border-bottom: 1px solid #999999;
border-radius: 5px 5px 5px 5px;
border-top: 1px solid #FFFFCC;
cursor: pointer;
padding: 5px;
}
You could add the time component
WHERE mydate<='2008-11-25 23:59:59'
but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:
WHERE mydate < '2008-11-26 00:00:00'
I've found a solution. If you want to update razor version or mvc 4 to 5, change some lines.
Old code in Views/web.config
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
Replaced with
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
sectionGroup
must be change, too.
I encountered this error message while trying to install varnish cache on ubuntu. The google search landed me here for the error
(23) Failed writing body
, hence posting a solution that worked for me.
The bug is encountered while running the command as root curl -L https://packagecloud.io/varnishcache/varnish5/gpgkey | apt-key add -
the solution is to run apt-key add
as non root
curl -L https://packagecloud.io/varnishcache/varnish5/gpgkey | apt-key add -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="1">first</option>
<option name="2"value="2">second</option>
</select>
</body>
</html>
I had the same problem for a long time now, I often needed to mix Matchers and values and I never managed to do that with Mockito.... until recently ! I put the solution here hoping it will help someone even if this post is quite old.
It is clearly not possible to use Matchers AND values together in Mockito, but what if there was a Matcher accepting to compare a variable ? That would solve the problem... and in fact there is : eq
when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class)))
.thenReturn(recommendedResults);
In this example 'metas' is an existing list of values
This is my solution using css+.
First of all, if the first child (flex-1) should be 100px, it shouldn't be flex.
In css+ in fact you can set flexible and/or static elements (columns or rows) and your example become as easy as this:
<div class="container">
<div class="EXTENDER">
<div class="COLS">
<div class="CELL _100px" style="background-color:blue">100px</div>
<div class="CELL _FLEX" style="background-color:red">flex</div>
</div>
</div>
</div>
Container CSS:
.container {
height: 200px;
width: 500px;
position: relative;
}
And obviously include css+ 0.2 core.
Here is the fiddle.
I followed Telvin's suggestion and it worked on Windows 7:
For me rebuilding the unity game without Unity C# Proects Checkmark worked.
git config --global --unset http.proxy
You should take a look to the format method of python. You could then define your formatting string like this :
>>> s = '{0} BLAH BLAH {1} BLAH {2} BLAH BLIH BLEH'
>>> x = ['1', '2', '3']
>>> print s.format(*x)
'1 BLAH BLAH 2 BLAH 3 BLAH BLIH BLEH'
check your path ,this error will come if file was not exist into given path.
In bootstrap 4, they have designed a bigger input file.
A simple solution to increase the size input file is to use font-size
:
Add you style, for example:
input[type="file"] {
font-size:35px
}
Otherwise, you can make one custom class and add to input control.
vars()['meta_anio_2012'] = 'translate'
just go to google docs and paste this as a formula, where URL is a link to your img
=image("URL", 1)
afterwards, from google docs options, download for excel and you'll have your image on the cell EDIT Per comments, you dont need to keep the image URL alive that long, just long enough for the excel to download it. Then it will stay embedded on the file.
Use the %
operator with a string:
irb(main):001:0> "%03d" % 5
=> "005"
The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:
irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"
Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C
function printf
, but similar formating functions are available in perl, ruby, python, java, php, etc.
Try mono:
http://www.go-mono.com/mono-downloads/download.html
This download works on all versions of Windows XP, 2003, Vista and Windows 7.
Copy the following line to your application manifest file and paste before the <application>
tag.
<uses-permission android:name="android.permission.INTERNET"/>
Placing the permission below the <application/>
tag will work, but will give you warning. So take care to place it before the <application/>
tag declaration.
if you use spring data jpa , spring boot you can add this line in application.properties
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
The problem is that @var
can just denote a single type - Not contain a complex formula. If you had a syntax for "array of Foo", why stop there and not add a syntax for "array of array, that contains 2 Foo's and three Bar's"? I understand that a list of elements is perhaps more generic than that, but it's a slippery slope.
Personally, I have some times used @var Foo[]
to signify "an array of Foo's", but it's not supported by IDE's.
why You don't use Ajax
to
its simple and does not require page refresh
and has success and error
callbacks
take look at my samlpe
<a id="ResendVerificationCode" >@Resource_en.ResendVerificationCode</a>
and in JQuery
$("#ResendVerificationCode").on("click", function() {
getUserbyPhoneIfNotRegisterd($("#phone").val());
});
and this is my ajax which call my controller and my controller and return object from database
function getUserbyPhoneIfNotRegisterd(userphone) {
$.ajax({
type: "GET",
dataType: "Json",
url: '@Url.Action("GetUserByPhone", "User")' + '?phone=' + userphone,
async: false,
success: function(data) {
if (data == null || data.data == null) {
ErrorMessage("", "@Resource_en.YourPhoneDoesNotExistInOurDatabase");
} else {
user = data[Object.keys(data)[0]];
AddVereCode(user.ID);// anather Ajax call
SuccessMessage("Done", "@Resource_en.VerificationCodeSentSuccessfully", "Done");
}
},
error: function() {
ErrorMessage("", '@Resource_en.ErrorOccourd');
}
});
}
My solution to this was use html to hardcode my default option. Like so:
In HAML:
%select{'ng-model' => 'province', 'ng-options' => "province as province for province in summary.provinces", 'chosen' => "chosen-select", 'data-placeholder' => "BC & ON"}
%option{:value => "", :selected => "selected"}
BC & ON
In HTML:
<select ng-model="province" ng-options="province as province for province in summary.provinces" chosen="chosen-select" data-placeholder="BC & ON">
<option value="" selected="selected">BC & ON</option>
</select>
I want my default option to return all values from my api, that's why I have a blank value. Also excuse my haml. I know this isn't directly an answer to the OP's question, but people find this on Google. Hope this helps someone else.
Great answer from Anonymous. \ solved my problem when I tried to escape quotes in HTML strings.
So if you use sed to return some HTML templates (on a server), use double backslash instead of single:
var htmlTemplate = "<div style=\\"color:green;\\"></div>";
I've cribbed together and tested with github the following approach, based on reading other answers, which combines a few techniques:
The advantage of this approach is, once set up, it doesn't require any additional work to get it right - for example, you don't need to change remote URLs or remember to clone things differently - the URL rewriting makes it all work.
~/.ssh/config
# Personal GitHub
Host github.com
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/github_id_rsa
# Work GitHub
Host github-work
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/work_github_id_rsa
Host *
IdentitiesOnly yes
~/.gitconfig
[user]
name = My Name
email = [email protected]
[includeIf "gitdir:~/dev/work/"]
path = ~/dev/work/.gitconfig
[url "github-work:work-github-org/"]
insteadOf = [email protected]:work-github-org/
~/dev/work/.gitconfig
[user]
email = [email protected]
As long as you keep all your work repos under ~/dev/work and personal stuff elsewhere, git will use the correct SSH key when doing pulls/clones/pushes to the server, and it will also attach the correct email address to all of your commits.
References:
To find where Anaconda was installed I used the "where" command on the command line in Windows.
C:\>where anaconda
which for me returned:
C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe
Which allowed me to find the Anaconda Python interpreter at
C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\python.exe
to update PyDev
In my case I have imported the RouterModule in App module but not imported in my feature module. After import the router module in my EventModule the error goes away.
import {NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {EventListComponent} from './EventList.Component';
import {EventThumbnailComponent} from './EventThumbnail.Component';
import { EventService } from './shared/Event.Service'
import {ToastrService} from '../shared/toastr.service';
import {EventDetailsComponent} from './event-details/event.details.component';
import { RouterModule } from "@angular/router";
@NgModule({
imports:[BrowserModule,RouterModule],
declarations:[EventThumbnailComponent,EventListComponent,EventDetailsComponent],
exports: [EventThumbnailComponent,EventListComponent,EventDetailsComponent],
providers: [EventService,ToastrService]
})
export class EventModule {
}
In App.js
import {useHistory } from "react-router-dom";
const TheContext = React.createContext(null);
const App = () => {
const history = useHistory();
<TheContext.Provider value={{ history, user }}>
<Switch>
<Route exact path="/" render={(props) => <Home {...props} />} />
<Route
exact
path="/sign-up"
render={(props) => <SignUp {...props} setUser={setUser} />}
/> ...
Then in a child component :
const Welcome = () => {
const {user, history} = React.useContext(TheContext);
....
+-------+--------+
| name | salary |
+-------+--------+
| A | 100 |
| B | 200 |
| C | 300 |
| D | 400 |
| E | 500 |
| F | 500 |
| G | 600 |
+-------+--------+
IF YOU WANT TO SELECT ONLY Nth HIGHEST SALARY THEN:
SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET N-1;
IF YOU WANT TO SELECT ALL EMPLOYEE WHO GETTING Nth HIGHEST SALARY THEN:
SELECT * FROM emp WHERE salary = (
SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET N-1
);
For Kotlin, You can use something like this :
object FileUtils {
fun Context.getFileName(uri: Uri): String?
= when (uri.scheme) {
ContentResolver.SCHEME_FILE -> File(uri.path).name
ContentResolver.SCHEME_CONTENT -> getCursorContent(uri)
else -> null
}
private fun Context.getCursorContent(uri: Uri): String?
= try {
contentResolver.query(uri, null, null, null, null)?.let { cursor ->
cursor.run {
if (moveToFirst()) getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
else null
}.also { cursor.close() }
}
} catch (e : Exception) { null }
conda should have given us a simple tool like cond env rename <old> <new>
but it hasn't. Simply renaming the directory, as in this previous answer, of course, breaks the hardcoded hashbangs(#!).
Hence, we need to go one more level deeper to achieve what we want.
conda env list
# conda environments:
#
base * /home/tgowda/miniconda3
junkdetect /home/tgowda/miniconda3/envs/junkdetect
rtg /home/tgowda/miniconda3/envs/rtg
Here I am trying to rename rtg
--> unsup
(please bear with those names, this is my real use case)
$ cd /home/tgowda/miniconda3/envs
$ OLD=rtg
$ NEW=unsup
$ mv $OLD $NEW # rename dir
$ conda env list
# conda environments:
#
base * /home/tgowda/miniconda3
junkdetect /home/tgowda/miniconda3/envs/junkdetect
unsup /home/tgowda/miniconda3/envs/unsup
$ conda activate $NEW
$ which python
/home/tgowda/miniconda3/envs/unsup/bin/python
the previous answer reported upto this, but wait, we are not done yet!
the pending task is, $NEW/bin
dir has a bunch of executable scripts with hashbangs (#!
) pointing to the $OLD env paths.
See jupyter
, for example:
$ which jupyter
/home/tgowda/miniconda3/envs/unsup/bin/jupyter
$ head -1 $(which jupyter) # its hashbang is still looking at old
#!/home/tgowda/miniconda3/envs/rtg/bin/python
So, we can easily fix it with a sed
$ sed -i.bak "s:envs/$OLD/bin:envs/$NEW/bin:" $NEW/bin/*
# `-i.bak` created backups, to be safe
$ head -1 $(which jupyter) # check if updated
#!/home/tgowda/miniconda3/envs/unsup/bin/python
$ jupyter --version # check if it works
jupyter core : 4.6.3
jupyter-notebook : 6.0.3
$ rm $NEW/bin/*.bak # remove backups
Now we are done
I think it should be trivial to write a portable script to do all those and bind it to conda env rename old new
.
I tested this on ubuntu. For whatever unforseen reasons, if things break and you wish to revert the above changes:
$ mv $NEW $OLD
$ sed -i.bak "s:envs/$NEW/bin:envs/$OLD/bin:" $OLD/bin/*
this
refers to a reference of the current class.
super
refers to the parent of the current class (which called the super
keyword).
By doing this
, it allows you to access methods/attributes of the current class (including its own private methods/attributes).
super
allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.
Building on some of the responds here, i'd like to add an alternative way. Creating a generic method using reflection, that can map any Stored Procedure response to a List. That is, a List of any type you wish, as long as the given type contains similarly named members to the Stored Procedure columns in the response. Ideally, i'd probably use Dapper for this - but here goes:
private static SqlConnection getConnectionString() // Should be gotten from config in secure storage.
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "it.hurts.when.IP";
builder.UserID = "someDBUser";
builder.Password = "someDBPassword";
builder.InitialCatalog = "someDB";
return new SqlConnection(builder.ConnectionString);
}
public static List<T> ExecuteSP<T>(string SPName, List<SqlParameter> Params)
{
try
{
DataTable dataTable = new DataTable();
using (SqlConnection Connection = getConnectionString())
{
// Open connection
Connection.Open();
// Create command from params / SP
SqlCommand cmd = new SqlCommand(SPName, Connection);
// Add parameters
cmd.Parameters.AddRange(Params.ToArray());
cmd.CommandType = CommandType.StoredProcedure;
// Make datatable for conversion
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
da.Dispose();
// Close connection
Connection.Close();
}
// Convert to list of T
var retVal = ConvertToList<T>(dataTable);
return retVal;
}
catch (SqlException e)
{
Console.WriteLine("ConvertToList Exception: " + e.ToString());
return new List<T>();
}
}
/// <summary>
/// Converts datatable to List<someType> if possible.
/// </summary>
public static List<T> ConvertToList<T>(DataTable dt)
{
try // Necesarry unfotunately.
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name))
{
if (row[pro.Name].GetType() == typeof(System.DBNull)) pro.SetValue(objT, null, null);
else pro.SetValue(objT, row[pro.Name], null);
}
}
return objT;
}).ToList();
}
catch (Exception e)
{
Console.WriteLine("Failed to write data to list. Often this occurs due to type errors (DBNull, nullables), changes in SP's used or wrongly formatted SP output.");
Console.WriteLine("ConvertToList Exception: " + e.ToString());
return new List<T>();
}
}
Gist: https://gist.github.com/Big-al/4c1ff3ed87b88570f8f6b62ee2216f9f
You can put dimens.xml
in
1) values
2) values-hdpi
3) values-xhdpi
4) values-xxhdpi
And give different sizes in dimens.xml
within corresponding folders according to densities.
Two options:
char c1 = '\u0001';
char c1 = (char) 1;
You can just use the method uniq
. Assuming your array is ary
, call:
ary.uniq{|x| x.user_id}
and this will return a set with unique user_id
s.
Works Like a Charm
final DatabaseReference senderDb = FirebaseDatabase.getInstance().getReference(Constant.NODE_MESSAGE).child(myId + "_" + otherId);
senderDb.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
DatabaseReference objRef = senderDb.child( childDataSnapshot.getKey());
Map<String,Object> taskMap = new HashMap<String,Object>();
taskMap.put("is_read", "1");
objRef.updateChildren(taskMap); //should I use setValue()...?
Log.v("Testing",""+ childDataSnapshot.getKey()); //displays the key for the node
}
//notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
You can write your own rule!
// add the rule here
$.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg !== value;
}, "Value must not equal arg.");
// configure your validation
$("form").validate({
rules: {
SelectName: { valueNotEquals: "default" }
},
messages: {
SelectName: { valueNotEquals: "Please select an item!" }
}
});
You should have one listview in your mainlist.xml
file with id as @android:id/list
<ListView
android:id="@android:id/list"
android:layout_height="wrap_content"
android:layout_height="fill_parent"/>
import nltk
nltk.download()
Use this
<script>
$(document).ready(function(){
$( '.expand' ).click(function() {
$( '.img_display_content' ).show();
});
});
</script>
Event assigning always after Document Object Model loaded
Since diawi.com have added some limitations for free accounds.
Next best available and easy to use alternative is
Microsoft
https://firebase.google.com/docs/app-distribution/ios/distribute-console
Others
Happy build sharing!
(It would really have been nice if you'd mentioned which Color
type you were interested in to start with...)
One simple way of doing this is to just build up a dictionary via reflection:
public static class Colors
{
private static readonly Dictionary<string, Color> dictionary =
typeof(Color).GetProperties(BindingFlags.Public |
BindingFlags.Static)
.Where(prop => prop.PropertyType == typeof(Color))
.ToDictionary(prop => prop.Name,
prop => (Color) prop.GetValue(null, null)));
public static Color FromName(string name)
{
// Adjust behaviour for lookup failure etc
return dictionary[name];
}
}
That will be relatively slow for the first lookup (while it uses reflection to find all the properties) but should be very quick after that.
If you want it to be case-insensitive, you can pass in something like StringComparer.OrdinalIgnoreCase
as an extra argument in the ToDictionary
call. You can easily add TryParse
etc methods should you wish.
Of course, if you only need this in one place, don't bother with a separate class etc :)
When cin
gets input it can't use, it sets failbit
:
int n;
cin >> n;
if(!cin) // or if(cin.fail())
{
// user didn't input a number
cin.clear(); // reset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
// next, request user reinput
}
When cin
's failbit
is set, use cin.clear()
to reset the state of the stream, then cin.ignore()
to expunge the remaining input, and then request that the user re-input. The stream will misbehave so long as the failure state is set and the stream contains bad input.
For people do not like to modify chrome's security options, we can simply start a python
http server from directory which contains your local file:
python -m SimpleHTTPServer
and for python 3:
python3 -m http.server
Now you can reach any local file directly from your js code or externally with http://127.0.0.1:8000/some_file.txt
@klode's answer is right.
However, you are supposed to set another response header to make your header accessible to others.
Example:
First, you add 'page-size' in response header
response.set('page-size', 20);
Then, all you need to do is expose your header
response.set('Access-Control-Expose-Headers', 'page-size')
Don't know why, but only thing that worked for me was using asset_path instead of image_path, even though my images are under the assets/images/ directory:
Example:
app/assets/images/mypic.png
In Ruby:
asset_path('mypic.png')
In .scss:
url(asset-path('mypic.png'))
UPDATE:
Figured it out- turns out these asset helpers come from the sass-rails gem (which I had installed in my project).
Remove ~
character in location
so
path="~/Admin/SomePage.aspx"
becomes
path="Admin/SomePage.aspx"
public class Form1 : Form
{
public Form1()
{
InitializeComponents(); // or whatever that method is called :)
this.button.Click += new RoutedEventHandler(buttonClick);
}
private void buttonClick(object sender, EventArgs e)
{
this.Close();
}
}
The cvWaitKey
simply provides something of a delay. For example:
char c = cvWaitKey(33);
if( c == 27 ) break;
Tis was apart of my code in which a video was loaded into openCV and the frames outputted. The 33
number in the code means that after 33ms
, a new frame would be shown. Hence, the was a dely or time interval of 33ms
between each frame being shown on the screen.
Hope this helps.
/dt is the commad which lists you all the tables present in a database. using
/d command and /d+ we can get the details of a table. The sysntax will be like
* /d table_name (or) \d+ table_name
What do you exactly call "special character" ? If you mean something like "anything that is not alphanumeric" you can use org.apache.commons.lang.StringUtils class (methods IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable).
If it is not so trivial, you can use a regex that defines the exact character list you accept and match the string against it.
ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]
As @Jared Ng and @Issun pointed out, the key to solve this kind of RegEx like "matching everything up to a certain word or substring" or "matching everything after a certain word or substring" is called "lookaround" zero-length assertions. Read more about them here.
In your particular case, it can be solved by a positive look ahead: .+?(?=abc)
A picture is worth a thousand words. See the detail explanation in the screenshot.
I tried everything, but this is the only thing that worked.
useLayoutEffect(() => {
document.getElementById("someID").scrollTo(0, 0);
});
After trying a few of the above suggestions without success (Swift versions...) I ended up using the official documentation: https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_from_websites
let downloadTask = URLSession.shared.downloadTask(with: url) {
urlOrNil, responseOrNil, errorOrNil in
// check for and handle errors:
// * errorOrNil should be nil
// * responseOrNil should be an HTTPURLResponse with statusCode in 200..<299
guard let fileURL = urlOrNil else { return }
do {
let documentsURL = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let savedURL = documentsURL.appendingPathComponent(fileURL.lastPathComponent)
try FileManager.default.moveItem(at: fileURL, to: savedURL)
} catch {
print ("file error: \(error)")
}
}
downloadTask.resume()
If you have following two labels:
<asp:Label ID="MonthLabel" runat="server" />
<asp:Label ID="YearLabel" runat="server" />
Than you can use following code just need to set the Text Property for these labels like:
MonthLabel.Text = DateTime.Now.Month.ToString();
YearLabel.Text = DateTime.Now.Year.ToString();
Because none of the above answers did the trick for me, here is my solution:
I combined the POSITION_NONE
with loading on setUserVisibleHint(boolean isVisibleToUser)
instead of onStart()
As seen here: https://stackoverflow.com/a/25676323/497366
In the Fragment
:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
}else{
// fragment is no longer visible
}
}
and in the FragmentStatePagerAdapter
as seen in the top answer here from Simon Dorociak https://stackoverflow.com/a/18088509/497366:
@Override
public int getItemPosition(@NonNull Object object) {
return POSITION_NONE;
}
Now the fragments reload the data into their views everytime they are shown to the user.
In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.
This is an array of the command line switches pass to the program. E.g. if you start the program with the command "myapp.exe -c -d
" then string[] args[]
will contain the strings "-c" and "-d".
Or, if you are doing a split - join:
GROUP_CONCAT(split(thing, " "), '----') AS thing_name,
You may want to inclue WITHIN RECORD
, like this:
GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,
from BigQuery API page
Just to add a bit to what has already been said: if you use sympy, you can use symbols rather than strings which makes them mathematically useful.
import itertools
import sympy
x, y = sympy.symbols('x y')
somelist = [[x,y], [1,2,3], [4,5]]
somelist2 = [[1,2], [1,2,3], [4,5]]
for element in itertools.product(*somelist):
print element
About sympy.
You have to use the index and the Adapter to find out the text you have
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
You're using span6
and span2
. Both of these classes are "float:left
" meaning, if possible they will always try to sit next to each other.
Twitter bootstrap is based on a 12 grid system. So you should generally always get the span**#**
to add up to 12.
E.g.: span4
+ span4
+ span4
OR span6
+ span6
OR span4
+ span3
+ span5
.
To force a span down though, without listening to the previous float you can use twitter bootstraps clearfix
class. To do this, your code should look like this:
<ul class="nav nav-tabs span2">
<li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
<li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
<li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
<li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>
<!-- Notice this following line -->
<div class="clearfix"></div>
<div class="well span6">
<h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>
How about
DROP USER <username>
This is actually an alias for DROP ROLE
.
You have to explicity drop any privileges associated with that user, also to move its ownership to other roles (or drop the object).
This is best achieved by
REASSIGN OWNED BY <olduser> TO <newuser>
and
DROP OWNED BY <olduser>
The latter will remove any privileges granted to the user.
See the postgres docs for DROP ROLE and the more detailed description of this.
Addition:
Apparently, trying to drop a user by using the commands mentioned here will only work if you are executing them while being connected to the same database that the original GRANTS were made from, as discussed here:
The following works in MVC5:
document.getElementById('theID').value = 'new value';
As an add-on to others' excellent posts, here's an article summarizing these techniques:
Use UITextView it supports clickable Links. Create attributed string using the following code
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];
Then set UITextView text as follows
NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],
NSUnderlineColorAttributeName: [UIColor blueColor],
NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;
Make sure that you enable "Selectable" behavior of the UITextView in XIB.
New MySQL 8.0.11 is using caching_sha2_password
as default authentication method. I think that phpMyAdmin cannot understand this authentication method.
You need to create user with one of the older authentication method, e.g. CREATE USER xyz@localhost IDENTIFIED WITH mysql_native_password BY 'passw0rd'
.
More here https://dev.mysql.com/doc/refman/8.0/en/create-user.html and here https://dev.mysql.com/doc/refman/8.0/en/authentication-plugins.html
If you want a simple visual comparison on Windows such as you can get in Visual SourceSafe or Team Foundation Server (TFS), try this:
Note: After upgrading to Windows 10 I have lost the Git context menu options. However, you can achieve the same thing using 'gitk' or 'gitk filename' in a command window.
Once you call 'Git History', the Git GUI tool will start, with a history of the file in the top left pane. Select one of the versions you would like to compare. Then right-click on the second version and choose either
Diff this -> selected
or
Diff selected -> this
Colour-coded differences will appear in the lower left-hand pane.
while installing python packages in a global environment is doable, it is a best practice to isolate the environment between projects (creating virtual environments). Otherwise, confusion between Python versions will arise, just like your problem.
The simplest method is to use venv
library in the project directory:
python3 -m venv venv
Where the first venv
is to call the venv
package, and the second venv
defines the virtual environment directory name.
Then activate the virtual environment:
source venv/bin/activate
Once the virtual environment has been activated, your pip install ...
commands would not be interfered with any other Python version or pip version anymore.
For installing requests
:
pip install requests
Another benefit of the virtual environment is to have a concise list of libraries needed for that specific project.
*note: commands only work on Linux and Mac OS
Sure, a Linked List is a bit confusing for programming n00bs, pretty much the temptation is to look at it as Russian Dolls, because that's what it seems like, a LinkedList Object in a LinkedList Object. But that's a touch difficult to visualize, instead look at it like a computer.
LinkedList = Data + Next Member
Where it's the last member of the list if next is NULL
So a 5 member LinkedList would be:
LinkedList(Data1, LinkedList(Data2, LinkedList(Data3, LinkedList(Data4, LinkedList(Data5, NULL)))))
But you can think of it as simply:
Data1 -> Data2 -> Data3 -> Data4 -> Data5 -> NULL
So, how do we find the end of this? Well, we know that the NULL is the end so:
public void append(LinkedList myNextNode) {
LinkedList current = this; //Make a variable to store a pointer to this LinkedList
while (current.next != NULL) { //While we're not at the last node of the LinkedList
current = current.next; //Go further down the rabbit hole.
}
current.next = myNextNode; //Now we're at the end, so simply replace the NULL with another Linked List!
return; //and we're done!
}
This is very simple code of course, and it will infinitely loop if you feed it a circularly linked list! But that's the basics.
Note in 2018: readAsBinaryString
is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer
(or in some cases, readAsDataURL
) instead.
readAsBinaryString
says that the data must be represented as a binary string, where:
...every byte is represented by an integer in the range [0..255].
JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)
If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText
and readAsBinaryString
, but with readAsBinaryString
you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText
, because readAsText
will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
showResult(fr, "Text");
fr = new FileReader();
fr.onload = receivedBinary;
fr.readAsBinaryString(file);
}
function receivedBinary() {
showResult(fr, "Binary");
}
}
function showResult(fr, label) {
var markup, result, n, aByte, byteStr;
markup = [];
result = fr.result;
for (n = 0; n < result.length; ++n) {
aByte = result.charCodeAt(n);
byteStr = aByte.toString(16);
if (byteStr.length < 2) {
byteStr = "0" + byteStr;
}
markup.push(byteStr);
}
bodyAppend("p", label + " (" + result.length + "):");
bodyAppend("pre", markup.join(" "));
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>
If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13): 54 65 73 74 69 6e 67 20 31 20 32 20 33 Binary (28): ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see, readAsText
interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString
didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).
* XMLHttpRequest.response with responseType = "arraybuffer"
is supported in HTML 5.
** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.
If it's just a matter of easy reading, you could always define your own function :
is.not.null <- function(x) !is.null(x)
So you can use it all along your program.
is.not.null(3)
is.not.null(NULL)
To complete the picture, since -Werror
might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:
-Werror=implicit-function-declaration
See Make one gcc warning an error?
Regarding general use of -Werror
: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.
Ok, try this:
Get the image with the transparent circle - http://i39.tinypic.com/15s97vd.png Put that image in a html element and change that element's background color via css. This way you get the logo with the circle in the color defined in the stylesheet.
The html
<div class="badassColorChangingLogo">
<img src="http://i39.tinypic.com/15s97vd.png" />
Or download the image and change the path to the downloaded image in your machine
</div>
The css
div.badassColorChangingLogo{
background-color:white;
}
div.badassColorChangingLogo:hover{
background-color:blue;
}
Keep in mind that this wont work on non-alpha capable browsers like ie6, and ie7. for ie you can use a js fix. Google ddbelated png fix and you can get the script.
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
It's little late to answer ... but just in case may be someone return to this question looking for an answer
'delay' is property(function) of an Observable
fakeObservable = Observable.create(obs => {
obs.next([1, 2, 3]);
obs.complete();
}).delay(3000);
This worked for me ...
app.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeSuccess', function(){
ga('send', 'pageview', $location.path());
});
});
try this it is quite simple and give you cant make changes to your .css file this should work
<p align="center">
<button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%"> mybuttonname</button>
</p>
There is a a new option as well: get it via pip! There is a package pypiwin32 with wheels available, so you can just install with: pip install pypiwin32
!
Edit: Per comment from @movermeyer, the main project now publishes wheels at pywin32, and so can be installed with pip install pywin32
If you are talking about a text file, then there is really no way to do this without reading all the lines that precede it - After all, lines are determined by the presence of a newline, so it has to be read.
Use a stream that supports readline, and just read the first X-1 lines and dump the results, then process the next one.