I'm not specifically addressing the quoting issue because, well, sometimes, it's just reasonable to consider an alternative approach.
rxvt() { urxvt -fg "#${1:-000000}" -bg "#${2:-FFFFFF}"; }
which you can then call as:
rxvt 123456 654321
the idea being that you can now alias this without concern for quotes:
alias rxvt='rxvt 123456 654321'
or, if you need to include the #
in all calls for some reason:
rxvt() { urxvt -fg "${1:-#000000}" -bg "${2:-#FFFFFF}"; }
which you can then call as:
rxvt '#123456' '#654321'
then, of course, an alias is:
alias rxvt="rxvt '#123456' '#654321'"
(oops, i guess i kind of did address the quoting :)
You could drop the primary key column and re-create it. All the ids should then be reassigned in order.
However this is probably a bad idea in most situations. If you have other tables that have foreign keys to this table then it will definitely not work.
Here is complete console working application code. Please install RestSharp package.
using RestSharp;
using System;
namespace RESTSharpClient
{
class Program
{
static void Main(string[] args)
{
string url = "https://abc.example.com/";
string jsonString = "{" +
"\"auth\": {" +
"\"type\" : \"basic\"," +
"\"password\": \"@P&p@y_10364\"," +
"\"username\": \"prop_apiuser\"" +
"}," +
"\"requestId\" : 15," +
"\"method\": {" +
"\"name\": \"getProperties\"," +
"\"params\": {" +
"\"showAllStatus\" : \"0\"" +
"}" +
"}" +
"}";
IRestClient client = new RestClient(url);
IRestRequest request = new RestRequest("api/properties", Method.POST, DataFormat.Json);
request.AddHeader("Content-Type", "application/json; CHARSET=UTF-8");
request.AddJsonBody(jsonString);
var response = client.Execute(request);
Console.WriteLine(response.Content);
//TODO: do what you want to do with response.
}
}
}
Use the document.createElement function and then add it as a child of your select.
var newOption = document.createElement("option");
newOption.text = 'the options text';
newOption.value = 'some value if you want it';
daySelect.appendChild(newOption);
I want to add an answer here that noone has explicitly stated with implementation.
This is a great resource to refer to for this failure: https://matplotlib.org/faq/usage_faq.html
In my case, using matplotlib.use
did not work because it was somehow already set somewhere else. However, I was able to get beyond the error by defining an environment variable:
export MPLBACKEND=Agg
This takes care of the issue.
My error was in a CircleCI flow specifically, and this resolved the failing tests. One wierd thing was, my tests would pass when run using pytest
, however would fail when using parallelism
along with circleci tests split
feature. However, declaring this env variable resolved the issue.
Cause you need to add jQuery library to your file:
jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.
<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
I would use the SplFileObject class...
$file = new SplFileObject("filename");
if (!$file->eof()) {
$file->seek($lineNumber);
$contents = $file->current(); // $contents would hold the data from line x
}
If you try to open a TCP connection to another host and see the error "Connection refused," it means that
RST is a bit on the TCP packet which indicates that the connection should be reset. Usually it means that the other host has received your connection attempt and is actively refusing your TCP connection, but sometimes an intervening firewall may block your TCP SYN packet and send a TCP RST back to you.
See https://tools.ietf.org/html/rfc793 page 69:
SYN-RECEIVED STATE
If the RST bit is set
If this connection was initiated with a passive OPEN (i.e., came from the LISTEN state), then return this connection to LISTEN state and return. The user need not be informed. If this connection was initiated with an active OPEN (i.e., came from SYN-SENT state) then the connection was refused, signal the user "connection refused". In either case, all segments on the retransmission queue should be removed. And in the active OPEN case, enter the CLOSED state and delete the TCB, and return.
curious - why doesn't the 'nothing easier than this' answer (above) not work? it looks logical? http://206.251.38.181/jquery-learn/ajax/iframe.html
Here is a very good tutorial for MVVM beginners; http://geekswithblogs.net/mbcrump/archive/2010/06/27/getting-started-with-mvvm-general-infolinks.aspx [Getting started with MVVM (General Info+Links)]
The accepted answer is not necessarily correct. queuecomplete
will be called even when the selected file is larger than the max file size.
The proper event to use is successmultiple
or completemultiple
.
Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect
Your file should directly be under the project folder, and not inside any other sub-folder.
If the folder of your project is named for e.g. AProject
, it should be in the same place as your src
folder.
Aproject
src
word.txt
var result;_x000D_
result = "1,2,3".split(","); _x000D_
console.log(result);
_x000D_
More info on W3Schools describing the String Split function.
That is a default behaviour of each browser; your browser seems to be Safari, in Google Chrome it is orange in color!
Use this to remove this effect:
button {
outline: none; // this one
}
You should declare it with declarations array(meta property) of @NgModule
as shown below (RC5 and later
),
import {CoursesComponent} from './courses.component';
@NgModule({
imports: [ BrowserModule],
declarations: [ AppComponent,CoursesComponent], //<----here
providers: [],
bootstrap: [ AppComponent ]
})
Algorithm ArrayList LinkedList
seek front O(1) O(1)
seek back O(1) O(1)
seek to index O(1) O(N)
insert at front O(N) O(1)
insert at back O(1) O(1)
insert after an item O(N) O(1)
ArrayLists are good for write-once-read-many or appenders, but bad at add/remove from the front or middle.
1.<a href="index.jsp?p=products">Products</a>
when user clicks on Products link,you can directly call products.jsp.
I mean u can maintain name of the JSP file same as parameter Value.
<%
if(request.getParameter("p")!=null)
{
String contextPath="includes/";
String p = request.getParameter("p");
p=p+".jsp";
p=contextPath+p;
%>
<%@include file="<%=p%>" %>
<%
}
%>
or
2.you can maintain external resource file with key,value pairs. like below
products : products.jsp
customer : customers.jsp
you can programatically retrieve the name of JSP file from properies file.
this way you can easily change the name of JSP file
This helped me find the "Dynamic web project" in Eclipse 2020-12 version. Restart the eclipse and go to file->new->other->web and you will see project will be available.
You can use -v
option multiple times in docker run
command to mount multiple directory in container:
docker run -t -i \
-v '/on/my/host/test1:/on/the/container/test1' \
-v '/on/my/host/test2:/on/the/container/test2' \
ubuntu /bin/bash
Note that %in%
returns a logical vector of TRUE
and FALSE
. To negate it, you can use !
in front of the logical statement:
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
!where_case_travelled_1 %in%
c('Outside Canada','Outside province/territory of residence but within Canada'))
Regarding your original approach with -c(...)
, -
is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")
). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -
.
Try :
(Get-Location).path
or:
($pwd).path
If you are wondering how to get your domain to appear as
www.mydomain.com
instead of redirecting thewww
request tomydomain.com
, try this:
CNAME file on gh-pages branch will have one line:
www.mydomain.com
(instead of mydomain.com
)
No matter your preference on redirection (in other words, no matter what is in your CNAME file on the gs-pages branch), with your DNS provider, you should set it up like this:
A @ 192.30.252.154
A @ 192.30.252.153
CNAME www username.github.io
Use System.nanoTime to get the current time.
long startTime = System.nanoTime();
.....your program....
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println(totalTime);
The above code prints the running time of the program in nanoseconds.
Another possibility is to use an absolute positioning oriented to the right. You can do it this way:
style="position: absolute; right: 0;"
What finally worked for me (Grails now works smoothly) is doing almost like Steve B. has pointed out:
JAVA_HOME=/usr/lib/jvm/default-java
This way if the user changes the default JDK for the system, JAVA_HOME
still works.
default-java
is a symlink to the current JVM.
On Mac OSX 10.15, Even after installing gpg, i was getting gpg2 command not found
$ brew install gnupg gnupg2
Warning: gnupg 2.2.23 is already installed and up-to-date
To reinstall 2.2.23, run `brew reinstall gnupg`
$ gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
-bash: gpg2: command not found
Instead, this worked for me
$ gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
If you put together the answers so far, clean up and improve, you would arrive at this superior query:
UPDATE sales
SET status = 'ACTIVE'
WHERE (saleprice, saledate) IN (
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING count(*) = 1
);
Which is much faster than either of them. Nukes the performance of the currently accepted answer by factor 10 - 15 (in my tests on PostgreSQL 8.4 and 9.1).
But this is still far from optimal. Use a NOT EXISTS
(anti-)semi-join for even better performance. EXISTS
is standard SQL, has been around forever (at least since PostgreSQL 7.2, long before this question was asked) and fits the presented requirements perfectly:
UPDATE sales s
SET status = 'ACTIVE'
WHERE NOT EXISTS (
SELECT FROM sales s1 -- SELECT list can be empty for EXISTS
WHERE s.saleprice = s1.saleprice
AND s.saledate = s1.saledate
AND s.id <> s1.id -- except for row itself
)
AND s.status IS DISTINCT FROM 'ACTIVE'; -- avoid empty updates. see below
db<>fiddle here
Old SQL Fiddle
If you don't have a primary or unique key for the table (id
in the example), you can substitute with the system column ctid
for the purpose of this query (but not for some other purposes):
AND s1.ctid <> s.ctid
Every table should have a primary key. Add one if you didn't have one, yet. I suggest a serial
or an IDENTITY
column in Postgres 10+.
Related:
The subquery in the EXISTS
anti-semi-join can stop evaluating as soon as the first dupe is found (no point in looking further). For a base table with few duplicates this is only mildly more efficient. With lots of duplicates this becomes way more efficient.
For rows that already have status = 'ACTIVE'
this update would not change anything, but still insert a new row version at full cost (minor exceptions apply). Normally, you do not want this. Add another WHERE
condition like demonstrated above to avoid this and make it even faster:
If status
is defined NOT NULL
, you can simplify to:
AND status <> 'ACTIVE';
The data type of the column must support the <>
operator. Some types like json
don't. See:
This query (unlike the currently accepted answer by Joel) does not treat NULL values as equal. The following two rows for (saleprice, saledate)
would qualify as "distinct" (though looking identical to the human eye):
(123, NULL)
(123, NULL)
Also passes in a unique index and almost anywhere else, since NULL values do not compare equal according to the SQL standard. See:
OTOH, GROUP BY
, DISTINCT
or DISTINCT ON ()
treat NULL values as equal. Use an appropriate query style depending on what you want to achieve. You can still use this faster query with IS NOT DISTINCT FROM
instead of =
for any or all comparisons to make NULL compare equal. More:
If all columns being compared are defined NOT NULL
, there is no room for disagreement.
the accepted answer does not work any longer with laravel 5.3 because mailable tries to access ->email
and results in
ErrorException in Mailable.php line 376: Trying to get property of non-object
a working code for laravel 5.3 is this:
$users_temp = explode(',', '[email protected],[email protected]');
$users = [];
foreach($users_temp as $key => $ut){
$ua = [];
$ua['email'] = $ut;
$ua['name'] = 'test';
$users[$key] = (object)$ua;
}
Mail::to($users)->send(new OrderAdminSendInvoice($o));
Assuming you also want to check if the item is not null
if (array.Length > 25 && array[25] != null)
{
//it exists
}
This error occurs when you copy a project than past it, and then you change the name of that project.
in such a case, follow the following steps.
Step-1: you need to edit your web.xml file. remove servlet and servlet-mapping of the previous projects.
Step-2: got to SERVER--> server.xml--> find context
Example :- Context docBase="JSPandServletDemo" path="/JSPandServletDemo" reloadable="true" source="org.eclipse.jst.jee.server:JSPandServletDemo"/>
now you just need to change the pathname to your current project name.
Good Luck Happy Coding :)
Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use ✓
for ✓ and ✗
for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.
As mentioned in the comments, ✓
and ✗
are not supported in HTML4, so you may be better off using the more cryptic ✓
and ✗
if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.
The accepted answer via git merge will get the job done but leaves a messy commit hisotry, correct way should be 'rebase' via the following steps(assuming you want to keep your feature branch in sycn with develop before you do the final push before PR).
1 git fetch
from your feature branch (make sure the feature branch you are working on is update to date)
2 git rebase origin/develop
3 if any conflict shall arise, resolve them one by one
4 use git rebase --continue
once all conflicts are dealt with
5 git push --force
In my case, i just change some step below with iOS 9.3 To solve this problem:
Settings -> General -> Device Management -> Developer app Choose your current developer account name. Taps Trust "Your developer account name" Taps "Trust" in pop up. Done
Quirksmode had a post on this.
Since the page is now broken, and only accessible via archive.org, I reproduced it here:
IFrames
On this page I give a short overview of accessing iframes from the page they’re on. Not surprisingly, there are some browser considerations.
An iframe is an inline frame, a frame that, while containing a completely separate page with its own URL, is nonetheless placed inside another HTML page. This gives very nice possibilities in web design. The problem is to access the iframe, for instance to load a new page into it. This page explains how to do it.
Frame or object?
The fundamental question is whether the iframe is seen as a frame or as an object.
top.frames[1].frames[2]
and such). Does the iframe fit into this frame hierarchy?document.getElementById('theiframe'))
to access it.
In general browsers allow both views on 'real' (hard-coded) iframes, but generated iframes cannot be accessed as frames.NAME attribute
The most important rule is to give any iframe you create a name
attribute, even if you also use an id
.
<iframe src="iframe_page1.html"
id="testiframe"
name="testiframe"></iframe>
Most browsers need the name
attribute to make the iframe part of the frame hierarchy. Some browsers (notably Mozilla) need the id
to make the iframe accessible as an object. By assigning both attributes to the iframe you keep your options open. But name
is far more important than id
.
Access
Either you access the iframe as an object and change its src
or you access the iframe as a frame and change its location.href
.
document.getElementById('iframe_id').src = 'newpage.html'; frames['iframe_name'].location.href = 'newpage.html'; The frame syntax is slightly preferable because Opera 6 supports it but not the object syntax.
Accessing the iframe
So for a complete cross–browser experience you should give the iframe a name and use the
frames['testiframe'].location.href
syntax. As far as I know this always works.
Accessing the document
Accessing the document inside the iframe is quite simple, provided you use the name
attribute. To count the number of links in the document in the iframe, do
frames['testiframe'].document.links.length
.
Generated iframes
When you generate an iframe through the W3C DOM the iframe is not immediately entered into the frames
array, though, and the frames['testiframe'].location.href
syntax will not work right away. The browser needs a little time before the iframe turns up in the array, time during which no script may run.
The document.getElementById('testiframe').src
syntax works fine in all circumstances.
The target
attribute of a link doesn't work either with generated iframes, except in Opera, even though I gave my generated iframe both a name
and an id
.
The lack of target
support means that you must use JavaScript to change the content of a generated iframe, but since you need JavaScript anyway to generate it in the first place, I don't see this as much of a problem.
Text size in iframes
A curious Explorer 6 only bug:
When you change the text size through the View menu, text sizes in iframes are correctly changed. However, this browser does not change the line breaks in the original text, so that part of the text may become invisible, or line breaks may occur while the line could still hold another word.
I had the same problem and what I did is to replace the single quotes with the double one, but what was worse is the fact I had the same error when I had a comma for the last attribute of the json object. So I used regex in python to replace it before using the json.loads()
function. (Be careful about the s at the end of "loads")
import re
with open("file.json", 'r') as f:
s = f.read()
correct_format = re.sub(", *\n *}", "}", s)
data_json = json.loads(correct_format)
The used regex return each comma followed by a newline and "}", replacing it just with a "}".
1- update your local meta-data using : git fetch --all
2- show your remote and local branches using : git branch -a , see the following Screenshot
3- switch to target branch , that you want to linked with the remote: using
git checkout branchName
example :
4- Link your local branch to a remote branch using:
git branch --set-upstream-to nameOfRemoteBranch
N.B : nameOfRemoteBranch : to copy from the output of step 2 " git branch -r "
Example of use:
General rule is that you want packages from require-dev section only in development (dev) environments, for example local environment.
Packages in require-dev section are packages which help you debug app, run tests etc.
At staging and production environment you probably want only packages from require section.
But anyway you can run composer install --no-dev and composer update --no-dev on any environment, command will install only packages from required section not from require-dev, but probably you want to run this only at staging and production environments not on local.
Theoretically you can put all packages in require section and nothing will happened, but you don't want developing packages at production environment because of the following reasons :
Some good candidates for require-dev are :
"filp/whoops": "^2.0",
"fzaninotto/faker": "^1.4",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^2.0",
"phpunit/phpunit": "^7.0"
you can see what above packages are doing and you will see why you don't need them on production.
See more here : https://getcomposer.org/doc/04-schema.md
if you want to get the index values, you can simply do:
dataframe.index
this will output a pandas.core.index
I solved it by doing the following:
In Visual studio I went in Project -> Project Dependencies
I selected the XXX.Test
solution and told it that it also depends on the XXX
solution to make the post-build
events in the XXX.Test
solution not generate this error (exit with code 4
).
Let's say your table has two other columns: foo and bar
INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, "155"
FROM Table
WHERE Event_ID = "120"
window.onbeforeunload = function () {
return "Do you really want to close?";
};
It would be fine to use query parameters on a POST endpoint, provided they refer to already existing resources.
For example:
POST /user_settings?user_id=4
{
"use_safe_mode": 1
}
The POST above has a query parameter referring to an existing resource. The body parameter defines the new resource to be created.
(Granted, this may be more of a personal preference than a dogmatic principle.)
Based on @jared-burrows' solution. For any package, but passing Context as parameter...
public static String getDataDir(Context context) throws Exception {
return context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0)
.applicationInfo.dataDir;
}
Update 2019
Remember that whatever CSS overrides you define must be the same CSS specificity or greater in order to properly override Bootstrap's CSS.
Bootstrap 4.1+
The Navbar is transparent by default. If you only want to change the background color, it can be done simply by applying the color to the <navbar class="bg-custom">
, but remember that won't change the other colors such as the links, hover and dropdown menu colors.
Here's CSS that will change any relevant Navbar colors in Bootstrap 4...
/* change the background color */
.navbar-custom {
background-color: #ff5500;
}
/* change the brand and text color */
.navbar-custom .navbar-brand,
.navbar-custom .navbar-text {
color: rgba(255,255,255,.8);
}
/* change the link color */
.navbar-custom .navbar-nav .nav-link {
color: rgba(255,255,255,.5);
}
/* change the color of active or hovered links */
.navbar-custom .nav-item.active .nav-link,
.navbar-custom .nav-item:focus .nav-link,
.navbar-custom .nav-item:hover .nav-link {
color: #ffffff;
}
Demo: http://www.codeply.com/go/U9I2byZ3tS
Override Navbar Light or Dark
If you're using the Bootstrap 4 Navbar navbar-light
or navbar-dark
classes, then use this in the overrides. For example, changing the Navbar link colors...
.navbar-light .nav-item.active .nav-link,
.navbar-light .nav-item:focus .nav-link,
.navbar-light .nav-item:hover .nav-link {
color: #ffffff;
}
When making any Bootstrap customizations, you need to understand CSS Specificity. Overrides in your custom CSS need to use selectors that are as specific as the bootstrap.css. Read more
Transparent Navbar
Notice that the Bootstrap 4 Navbar is transparent by default. Use navbar-dark
for dark/bold background colors, and use navbar-light
if the navbar is a lighter color. This will effect the color of the text and color of the toggler icon as explained here.
You could always include it using __DIR__
:
include(dirname(__DIR__).'/config.php');
__DIR__
is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__
. In this case, as we need to ascend a directory we use PHP's dirname
which ascends the file tree, and from here we can access config.php
.
You could set the root path in this method too:
define('ROOT_PATH', dirname(__DIR__) . '/');
in test.php would set your root to be at the /root/
level.
include(ROOT_PATH.'config.php');
Should then work to include the config file from where you want.
Extending the top voted comment.
Note that you should pass request as a parameter to your delete function in your views. An example would be like:
from django.shortcuts import redirect
def delete(request, id):
YourModelName.objects.filter(id=id).delete()
return redirect('url_name')
Have you tried?
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Example Link: Webview File Download - Thanks @c49
You can use PowerShell
$AttachmentPath = "CV File location"
$QueryFmt= "Query"
Invoke-Sqlcmd -ServerInstance Server -Database DBName -Query $QueryFmt | Export-CSV $AttachmentPath
Most answers based on (a1 - a2) or (a1 & a2) would not work if there are duplicate elements in either array. I arrived here looking for a way to see if all letters of a word (split to an array) were part of a set of letters (for scrabble for example). None of these answers worked, but this one does:
def contains_all?(a1, a2)
try = a1.chars.all? do |letter|
a1.count(letter) <= a2.count(letter)
end
return try
end
<input type="file"
id="fileUploadButton"
style={{ display: 'none' }}
onChange={onFileChange}
/>
<label htmlFor={'fileUploadButton'}>
<Button
color="secondary"
className={classes.btnUpload}
variant="contained"
component="span"
startIcon={
<SvgIcon fontSize="small">
<UploadIcon />
</SvgIcon>
}
>
Upload
</Button>
</label>
Make sure Button has component="span", that helped me.
My simple solution:
$("form").children('input[type="submit"]').click();
It is work for me.
HTML:
<select class="shortenedSelect">
<option value="0" disabled>Please select an item</option>
<option value="1">Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</option>
</select>
CSS:
.shortenedSelect {
max-width: 350px;
}
Javascript:
// Shorten select option text if it stretches beyond max-width of select element
$.each($('.shortenedSelect option'), function(key, optionElement) {
var curText = $(optionElement).text();
$(this).attr('title', curText);
// Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system.
var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3);
if (curText.length > lengthToShortenTo) {
$(this).text('... ' + curText.substring((curText.length - lengthToShortenTo), curText.length));
}
});
// Show full name in tooltip after choosing an option
$('.shortenedSelect').change(function() {
$(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title')));
});
Works perfectly. I had the same issue myself. Check out this JSFiddle http://jsfiddle.net/jNWS6/426/
Check my answer to a similar question. You could try the same loop in Python. This page suggests:
import time
while 1:
where = file.tell()
line = file.readline()
if not line:
time.sleep(1)
file.seek(where)
else:
print line, # already has newline
Also see the question tail() a file with Python.
You need to create a new Window class. You can design that then any way you want. You can create and show a window modally like this:
MyWindow popup = new MyWindow();
popup.ShowDialog();
You can add a custom property for your result value, or if you only have two possible results ( + possibly undeterminate, which would be null
), you can set the window's DialogResult
property before closing it and then check for it (it is the value returned by ShowDialog()
).
With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here: http://bl.ocks.org/mbostock/7555321
That automatically does line breaks for long text svg for a given width in pixel.
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
Create a path with moveTo
and lineTo
(live demo):
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100,50);
ctx.lineTo(50, 100);
ctx.lineTo(0, 90);
ctx.closePath();
ctx.fill();
As for your second problem:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\pickle.py", line
1365, in load encoding=encoding,
errors=errors).load() EOFError
After you have read the contents of the file, the file pointer will be at the end of the file - there will be no further data to read. You have to rewind the file so that it will be read from the beginning again:
file.seek(0)
What you usually want to do though, is to use a context manager to open the file and read data from it. This way, the file will be automatically closed after the block finishes executing, which will also help you organize your file operations into meaningful chunks.
Finally, cPickle is a faster implementation of the pickle module in C. So:
In [1]: import _pickle as cPickle
In [2]: d = {"a": 1, "b": 2}
In [4]: with open(r"someobject.pickle", "wb") as output_file:
...: cPickle.dump(d, output_file)
...:
# pickle_file will be closed at this point, preventing your from accessing it any further
In [5]: with open(r"someobject.pickle", "rb") as input_file:
...: e = cPickle.load(input_file)
...:
In [7]: print e
------> print(e)
{'a': 1, 'b': 2}
.hide()
stores the previous display
property just before setting it to none
, so if it wasn't the standard display
property for the element you're a bit safer, .show()
will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.
<object Margin="left,top,right,bottom"/>
- or -
<object Margin="left,top"/>
- or -
<object Margin="thicknessReference"/>
See here: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.margin.aspx
In order to work on all modern browsers, you will need two steps:
Add javascript:void(0);
as src
attribute for the iframe element. Otherwise the content will be overriden by the empty src
on Firefox.
<iframe src="javascript:void(0);"></iframe>
Programatically change the content of the inner html
element.
$(iframeSelector).contents().find('html').html(htmlContent);
Step 1 from comment (link) by @susan
Step 2 from solutions (link1, link2) by @erimerturk and @x10
An alternative to type -a
is command -V
Since most of the times I am interested in the first result only, I also pipe from head. This way the screen will not flood with code in case of a bash function.
command -V lshw | head -n1
CSS
div.horizontalgap {
float: left;
overflow: hidden;
height: 1px;
width: 0px;
}
Usage in HTML (for a 10px horizontal gap)
<div class="horizontalgap" style="width:10px"></div>
The Replace string function will do that.
it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...)
That's not correct, and you will be unable to cite an authoriitative source for that claim. It should be changed whenever you make a change that is incompatible under the rules given in the Versioning of Serializable Objects section of the Object Serialization Specification, which specifically does not include additional fields or change of field order, and when you haven't provided readObject(), writeObject(),
and/or readResolve()
or /writeReplace()
methods and/or a serializableFields
declaration that could cope with the change.
Just to add the information I was looking for: pragma mark
is Xcode specific, so if you deal with a C++ project that you open in different IDEs, it does not have any effect there. In Qt Creator, for example, it does not add categories for methods, nor generate any warnings/errors.
EDIT
#pragma
is a preprocessor directive which comes from C programming language. Its purpose is to specify implementation-dependent information to the compiler - that is, each compiler might choose to interpret this directive as it wants. That said, it is rather considered an extension which does not change/influence the code itself. So compilers might as well ignore it.
Xcode is an IDE which takes advantage of #pragma
and uses it in its own specific way. The point is, #pragma
is not Xcode and even Objective-C specific.
You can also use kafkactl for this:
# get all consumer groups (output as yaml)
kafkactl get consumer-groups -o yaml
# get only consumer groups assigned to a single topic (output as table)
kafkactl get consumer-groups --topic topic-a
Sample output (e.g. as yaml):
name: my-group
protocoltype: consumer
topics:
- topic-a
- topic-b
- topic-c
Disclaimer: I am contributor to this project
You can run npx webpack
. The npx command, which ships with Node 8.2/npm 5.2.0 or higher, runs the webpack binary (./node_modules/.bin/webpack) of the webpack package.
Source of info: https://webpack.js.org/guides/getting-started/
I think that the handling of a dialog should be the responsibility of the view, and the view needs to have code to support that.
If you change the ViewModel - View interaction to handle dialogs then the ViewModel is dependant on that implementation. The simplest way to deal with this problem is to make the View responsible for performing the task. If that means showing a dialog then fine, but could also be a status message in the status bar etc.
My point is that the whole point of the MVVM pattern is to separate business logic from the GUI, so you shouldn't be mixing GUI logic (to display a dialog) in the business layer (the ViewModel).
I just tested and for me, none of the other solutions worked. I simply tried this and it worked perfectly on Firefox and Chrome, just as I had expected:
<div class='wrap'>
<iframe ...></iframe>
</div>
and the css:
.wrap {
width: 640px;
height: 480px;
overflow: hidden;
}
iframe {
width: 76.92% !important;
height: 76.92% !important;
-webkit-transform: scale(1.3);
transform: scale(1.3);
-webkit-transform-origin: 0 0;
transform-origin: 0 0;
}
This scales all the content by 30%. The width/height percentages of course need to be adjusted accordingly (1/scale_factor).
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
I use
function windowHasScroll()
{
return document.body.clientHeight > document.documentElement.clientHeight;
}
Most of the solutions presented here would crash for large values and should not be used in production code.
If you don't care for very large values use this code to clamp the Double
to max/min Int
values.
let bigFloat = Float.greatestFiniteMagnitude
let smallFloat = -bigFloat
extension Float {
func toIntTruncated() -> Int {
let maxTruncated = min(self, Float(Int.max).nextDown)
let bothTruncated = max(maxTruncated, Float(Int.min))
return Int(bothTruncated)
}
}
// This crashes:
// let bigInt = Int(bigFloat)
// this works for values up to 9223371487098961920
let bigInt = bigFloat.toIntTruncated()
let smallInt = smallFloat.toIntTruncated()
To attach JDK source so that you refer to Java Source Code for code look-up which helps in learning the library implementation and sometimes in debugging, all you have to do is:
In your Eclipse Java Project > JRE Reference Library locate rt.jar. Right click and go to Properties:
Select "Java Source Attachment" on the right and to the left select "External Location" and click on "External File" Button and locate "src.zip" file in your $JAVA_HOME path in my case for my windows machine src.zip location is: C:/Program Files/Java/jdk1.7.0_45/src.zip.
You are done now! Just Ctrl + click on any Java library Class in your project code to look-up the source code for the java class.
In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;
In package body:
initialize the table in declarations:
exch_rt exch_tbl := exch_tbl();
in order to add record to the local collection, in begin - end block you can do:
exch_rt.extend;
one_row.exch_rt_usd := 2;
one_row.exch_rt_eur := 1;
one_row.currency_cd := 'dollar';
exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop
in order to get data from this table , inside package body you can use:
select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)
enjoy!
P.S. sorry for a late answer :D
You can run the application file of project in simulator - not .ipa file.
You can get it from:
Libraries-->Applicationsupport-->iphone simulator-->4.3(its ur simulator version)-->applications-->
then u can see many files like 0CD04F....
find out your application file through open it.
You can copy the file to your system(which system simulator u need run ) location Libraries-->Applicationsupport-->iphone simulator-->4.3(its your simulator version)-->applications-->
Then open the simulator 4.3 (its your simulator version where you pasted). You can see the application installed there.
Getting from other people:
Please tell them to find out Libraries-->Applicationsupport-->iphone simulator-->4.3(its ur simulator version)-->applications-->
then you can see many files like 0CD04F....
from their system and receive that file from them.
After they have got the file, please copy and paste the file in to your system `Libraries-->Applicationsupport-->iphone simulator-->4.3(its your simulator version)-->applications-->(paste the file here).
Then you can see the app is installed in your system simulator and you can run it after clicking the file.
/** eworkyou **//
$('#navigation a').bind('click',function(e){
var $this = $(this);
var prev = current;
current = $this.parent().index() + 1; //
if (current == 1){
$("#navigation a:eq(1)").unbind("click"); //
}
if (current >= 2){
$("#navigation a:eq(1)").bind("click"); //
}
I just had this issue and realized that there were empty columns being treated as columns with values, I saw this by opening my CSV in my text editor. To fix this, I opened my spreadsheet and deleted the columns after my last column, they looked completely empty but they were not. After I did this, the import worked perfectly.
I use a tiny perl script, which I call "unsort":
#!/usr/bin/perl
use List::Util 'shuffle';
@list = <STDIN>;
print shuffle(@list);
I've also got a NULL-delimited version, called "unsort0" ... handy for use with find -print0 and so on.
PS: Voted up 'shuf' too, I had no idea that was there in coreutils these days ... the above may still be useful if your systems doesn't have 'shuf'.
Another alternative is to use capturing sub-expressions with the regular expression functions regmatches
and regexec
.
# the original example
x <- 'hello stackoverflow'
# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))
This returns the entire string, the first character, and the "popped" result in a list of length 1.
myStrings
[[1]]
[1] "hello stackoverflow" "h" "ello stackoverflow"
which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x))))
. That is, it contains the super set of the desired elements as well as the full string.
Adding sapply
will allow this method to work for a character vector of length > 1.
# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')
# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))
This returns a list with the matched full string as the first element and the matching subexpressions captured by ()
as the following elements. So in the regular expression '(^.)(.*)'
, (^.)
matches the first character and (.*)
matches the remaining characters.
myStrings
[[1]]
[1] "hello stackoverflow" "h" "ello stackoverflow"
[[2]]
[1] "right back" "r" "ight back"
[[3]]
[1] "at yah" "a" "t yah"
Now, we can use the trusty sapply
+ [
method to pull out the desired substrings.
myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back" "t yah"
It is important to note that each jQuery()
call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.
This applies regardless of syntax. You can use jQuery()
, jQuery(function() {})
, $(document).ready()
, whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.
This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.
using(var client = new System.Net.WebClient()) {
client.UploadData(address,"PUT",data);
}
BETWEEN (Transact-SQL)
Specifies a(n) (inclusive) range to test.
test_expression [ NOT ] BETWEEN begin_expression AND end_expression
Arguments
test_expression
Is the expression to test for in the range defined by begin_expression and end_expression. test_expression must be the same data type as both begin_expression and end_expression.
NOT
Specifies that the result of the predicate be negated.
begin_expression
Is any valid expression. begin_expression must be the same data type as both test_expression and end_expression.
end_expression
Is any valid expression. end_expression must be the same data type as both test_expression and begin_expression.
AND
Acts as a placeholder that indicates test_expression should be within the range indicated by begin_expression and end_expression.
Remarks
To specify an exclusive range, use the greater than (>) and less than operators (<). If any input to the BETWEEN or NOT BETWEEN predicate is NULL, the result is UNKNOWN.
Result Value
BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.
NOT BETWEEN returns TRUE if the value of test_expression is less than the value of begin_expression or greater than the value of end_expression.
To clear a permanent redirect, go to chrome://settings/clearBrowserData and from there only clearing "cached images and files" cleared the redirect.
Go to chrome://net-internals. On the right of the top red status bar, click on the down arrow ? to open the drop-down menu, and under the "Tools" group, choose "Clear cache".
As of version 48, this was the only thing that worked for me to clear a cached 301.
What I do is, I replace
values.
Like this-
df['col'].replace(to_replace=['category_1', 'category_2', 'category_3'], value=[1, 2, 3], inplace=True)
In this way, if the col
column has categorical values, they get replaced by the numerical values.
You can use something like this:
for i in `cat foo.txt`
do
sudo $i
done
Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo
as a command. But it gives you an idea on how to start.
If you want to put some page in the dialog then you can use these
function Popup()
{
$("#pop").load('login.html').dialog({
height: 625,
width: 600,
modal:true,
close: function(event,ui){
$("pop").dialog('destroy');
}
});
}
HTML:
<Div id="pop" style="display:none;">
</Div>
The solution of using a list of axes by abevieiramota works very well until you use only one row of images, as pointed out in the comments. Using a reasonable aspect ratio for figsize
helps, but is still far from perfect. For example:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9.75, 3))
for ax in axes.flat:
im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)
fig.colorbar(im, ax=axes.ravel().tolist())
plt.show()
The colorbar function provides the shrink
parameter which is a scaling factor for the size of the colorbar axes. It does require some manual trial and error. For example:
fig.colorbar(im, ax=axes.ravel().tolist(), shrink=0.75)
int i = 7122960;
decimal d = (decimal)i / 100;
Android Studio can now show this. Go to Build
> Analyze APK...
and select your apk. Then you can see the content of the AndroidManifset file.
Invoking Java with "java -version:1.5", etc. should run with the correct version of Java. (Obviously replace 1.5 with the version you want.)
If Java is properly installed on Windows there are paths to the vm for each version stored in the registry which it uses so you don't need to mess about with environment versions on Windows.
If you find yourself writing the above solution as often as I do then you could implement it as a generic:
public static int GetEnumEntries<T>() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an enumerated type");
return Enum.GetNames(typeof(T)).Length;
}
It seems that you have a bunch of describe
s that never have end
s keywords, starting with describe "when email format is invalid" do
until describe "when email address is already taken" do
Put an end on those guys and you're probably done =)
Yes you can...
WITH SET1 AS (SELECT SYSDATE FROM DUAL), -- SET1 initialised
SET2 AS (SELECT * FROM SET1) -- SET1 accessed
SELECT * FROM SET2; -- SET2 projected
10/29/2013 10:43:26 AM
Follow the order in which it should be initialized in Common Table Expressions
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
You can find out what Git does with a file by seeing what it does when you add it to the index. The index is like a pre-commit. With the index committed, you can use git checkout
to bring everything that was in the index back into the working directory. So, what does Git do when you add a symbolic link to the index?
To find out, first, make a symbolic link:
$ ln -s /path/referenced/by/symlink symlink
Git doesn't know about this file yet. git ls-files
lets you inspect your index (-s
prints stat
-like output):
$ git ls-files -s ./symlink
[nothing]
Now, add the contents of the symbolic link to the Git object store by adding it to the index. When you add a file to the index, Git stores its contents in the Git object store.
$ git add ./symlink
So, what was added?
$ git ls-files -s ./symlink
120000 1596f9db1b9610f238b78dd168ae33faa2dec15c 0 symlink
The hash is a reference to the packed object that was created in the Git object store. You can examine this object if you look in .git/objects/15/96f9db1b9610f238b78dd168ae33faa2dec15c
in the root of your repository. This is the file that Git stores in the repository, that you can later check out. If you examine this file, you'll see it is very small. It does not store the contents of the linked file. To confirm this, print the contents of the packed repository object with git cat-file
:
$ git cat-file -p 1596f9db1b9610f238b78dd168ae33faa2dec15c
/path/referenced/by/symlink
(Note 120000
is the mode listed in ls-files
output. It would be something like 100644
for a regular file.)
But what does Git do with this object when you check it out from the repository and into your filesystem? It depends on the core.symlinks
config. From man git-config
:
core.symlinks
If false, symbolic links are checked out as small plain files that contain the link text.
So, with a symbolic link in the repository, upon checkout you either get a text file with a reference to a full filesystem path, or a proper symbolic link, depending on the value of the core.symlinks
config.
Either way, the data referenced by the symlink is not stored in the repository.
If you see table class it has border-spacing: 2px; You could override table class in your css and set its border-spacing: 0px!important in table; I did it like
table {
border-collapse: separate;
white-space: normal;
line-height: normal;
font-weight: normal;
font-size: medium;
font-style: normal;
color: -internal-quirk-inherit;
text-align: start;
border-spacing: 0px!important;
font-variant: normal; }
It saved my day.Hope it would be of help. Thanks.
Also, for those who happened to realize too late, that they committed with the wrong credentials, the solution (after the fact) is to change the svn author of that revision: see this question
Basically the syntax is:
svn propset --revprop -r (revision_number) svn:author (new username)
In case you're inside a Sub of Function and you want to exit it, you can use :
Exit Sub
or
Exit Function
The standard way to add Multiple functions
<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here</button>
or
<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here</button>
Taken from the Dapper Tests which is currently on Dapper 1.42.
// custom mapping
var map = new CustomPropertyTypeMap(typeof(TypeWithMapping),
(type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), map);
Helper class to get name off the Description attribute (I personally have used Column like @kalebs example)
static string GetDescriptionFromAttribute(MemberInfo member)
{
if (member == null) return null;
var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
return attrib == null ? null : attrib.Description;
}
Class
public class TypeWithMapping
{
[Description("B")]
public string A { get; set; }
[Description("A")]
public string B { get; set; }
}
This supports:
ng new project-name --routing
You can add --style=scss
for SASS .scss support.
You can add --ng4
for using Angular 4 instead of Angular 2.
After creating the project, the CLI will automatically run npm install
for you. If you want to use Yarn instead, or just want to look at the project skeleton without install, check how to do it here.
Inside the project folder:
ng build -prod
At the current version you need to to specify --aot
manually, because it can be used in development mode (although that's not practical due to slowness).
This also performs AoT compilation for even smaller bundles (no Angular compiler, instead, generated compiler output). The bundles are much smaller with AoT if you use Angular 4 as the generated code is smaller.
You can test your app with AoT in development mode (sourcemaps, no minification) and AoT by running ng build --aot
.
The default output dir is ./dist
, although it can be changed in ./angular-cli.json
.
The result of build step is the following:
(Note: <content-hash>
refers to hash / fingerprint of the contents of the file that's meant to be a cache busting way, this is possible since Webpack writes the script
tags by itself)
./dist/assets
./src/assets/**
./dist/index.html
./src/index.html
, after adding webpack scripts to it./angular-cli.json
./dist/inline.js
./dist/main.<content-hash>.bundle.js
./dist/styles.<content-hash>.bundle.js
In older versions it also created gzipped versions for checking their size, and .map
sourcemaps files, but this is no longer happening as people kept asking to remove these.
In certain other occasions, you might find other unwanted files/folders:
./out-tsc/
./src/tsconfig.json
's outDir
./out-tsc-e2e/
./e2e/tsconfig.json
's outDir
./dist/ngfactory/
Pseudo-elements are not part of the DOM, so they can't be manipulated using jQuery or Javascript.
But as pointed out in the accepted answer, you can use the JS to append a style block which ends of styling the pseudo-elements.
Here are few pointers/suggestions for investigation
vote
method which creates a fresh HTTP connection.HttpClient
instance to post to the server. This way it wont create too many connections from the client side. HttpClient
needs to be shut and hence call httpclient.getConnectionManager().shutdown();
to release the resources used by the connections. If you like to remove last 5 characters, you can use:
path.substring(0,path.length() - 5)
( could contain off by one error ;) )
If you like to remove some variable string:
path.substring(0,path.lastIndexOf('yoursubstringtoremove));
(could also contain off by one error ;) )
If $AccountNumber
or $Balance
is a node-set, then this behavior could easily happen. It's not because and
is being treated as or
.
For example, if $AccountNumber
referred to nodes with the values 12345
and 66
and $Balance
referred to nodes with the values 55
and 0
, then
$AccountNumber != '12345'
would be true (because 66
is not equal to 12345
) and $Balance != '0'
would be true (because 55
is not equal to 0
).
I'd suggest trying this instead:
<xsl:when test="not($AccountNumber = '12345' or $Balance = '0')">
$AccountNumber = '12345' or $Balance = '0'
will be true any time there is an $AccountNumber
with the value 12345
or there is a $Balance
with the value 0
, and if you apply not()
to that, you will get a false result.
try:
parts = ip.split('.')
return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)
except ValueError:
return False # one of the 'parts' not convertible to integer
except (AttributeError, TypeError):
return False # `ip` isn't even a string
If you are looking for some thing like this.
Here is the following snippetr
var demoArray = ['A','B','C','D'];_x000D_
var ArrayIndexValue = 2;_x000D_
if(demoArray.includes(ArrayIndexValue)){_x000D_
alert("value exists");_x000D_
//Array index exists_x000D_
}else{_x000D_
alert("does not exist");_x000D_
//Array Index does not Exists_x000D_
}
_x000D_
Middleware is about how our application responds to incoming requests. Middlewares look into the incoming request, and make decisions based on this request. We can build entire applications only using middlewares. For e.g. ASP.NET is a web framework comprising of following chief HTTP middleware components.
As shown in the above diagram, there are various middleware components in ASP.NET which receive the incoming request, and redirect it to a C# class (in this case a controller class).
Mesos and Kubernetes can both be used to manage a cluster of machines and abstract away the hardware.
Mesos, by design, doesn't provide you with a scheduler (to decide where and when to run processes and what to do if the process fails), you can use something like Marathon or Chronos, or write your own.
Kubernetes will do scheduling for you out of the box, and can be used as a scheduler for Mesos (please correct me if I'm wrong here!) which is where you can use them together. Mesos can have multiple schedulers sharing the same cluster, so in theory you could run kubernetes and chronos together on the same hardware.
Super simplistically: if you want control over how your containers are scheduled, go for Mesos, otherwise Kubernetes rocks.
Simple but powerful email validation for check email syntax :
var EmailId = document.getElementById('Email').value;
var emailfilter = /^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/;
if((EmailId != "") && (!(emailfilter.test(EmailId ) ) )) {
msg+= "Enter the valid email address!<br />";
}
TodayDate = new Date();
if (TodayDate > AnotherDate) {} else{}
< = also works, Although with =, it might have to match the milliseconds.
session_start();
if(isset($_SESSION['blah']) && !empty($_SESSION['blah'])) {
echo 'Set and not empty, and no undefined index error!';
}
array_key_exists
is a nice alternative to using isset
to check for keys:
session_start();
if(array_key_exists('blah',$_SESSION) && !empty($_SESSION['blah'])) {
echo 'Set and not empty, and no undefined index error!';
}
Make sure you're calling session_start
before reading from or writing to the session array.
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
There is another simple way, if you don't have an access to the Context.
1). Create a handler from the main looper:
Handler uiHandler = new Handler(Looper.getMainLooper());
2). Implement a Runnable interface:
Runnable runnable = new Runnable() { // your code here }
3). Post your Runnable to the uiHandler:
uiHandler.post(runnable);
That's all ;-) Have fun with threads, but don't forget to synchronize them.
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
In version 5.2.7 I use this to send plain text:
$mail->set('Body', $Body);
You may also use element.insertAdjacentHTML('beforeend', data);
Please read the "Security considerations" on MDN.
As a rule of thumb, value for non-class types and const reference for classes. If a class is really small it's probably better to pass by value, but the difference is minimal. What you really want to avoid is passing some gigantic class by value and having it all duplicated - this will make a huge difference if you're passing, say, a std::vector with quite a few elements in it.
Any of this answers didn't work for me so here is code which trust any certificates.
import java.io.IOException;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class HttpsClientBuilder {
public static DefaultHttpClient getBelieverHttpsClient() {
DefaultHttpClient client = null;
SchemeRegistry Current_Scheme = new SchemeRegistry();
Current_Scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
try {
Current_Scheme.register(new Scheme("https", new Naive_SSLSocketFactory(), 8443));
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpParams Current_Params = new BasicHttpParams();
int timeoutConnection = 8000;
HttpConnectionParams.setConnectionTimeout(Current_Params, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(Current_Params, timeoutSocket);
ThreadSafeClientConnManager Current_Manager = new ThreadSafeClientConnManager(Current_Params, Current_Scheme);
client = new DefaultHttpClient(Current_Manager, Current_Params);
//HttpPost httpPost = new HttpPost(url);
//client.execute(httpPost);
return client;
}
public static class Naive_SSLSocketFactory extends SSLSocketFactory
{
protected SSLContext Cur_SSL_Context = SSLContext.getInstance("TLS");
public Naive_SSLSocketFactory ()
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException
{
super(null, null, null, null, null, (X509HostnameVerifier)null);
Cur_SSL_Context.init(null, new TrustManager[] { new X509_Trust_Manager() }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException
{
return Cur_SSL_Context.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException
{
return Cur_SSL_Context.getSocketFactory().createSocket();
}
}
private static class X509_Trust_Manager implements X509TrustManager
{
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
};
}
if you are using vs code just try using background:url("img/bimg.jpg") instead of background:url('img/bimg.jpg') Mine worked at it Nothing much I replaced ' with "
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
console.log(arrayBuffer);_x000D_
document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength;_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
You forgot to mention the name of your database (is it "my"?).
ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE my SET OFFLINE;
ALTER DATABASE my MODIFY FILE
(
Name = my_Data,
Filename = 'D:\DATA\my.MDF'
);
ALTER DATABASE my MODIFY FILE
(
Name = my_Log,
Filename = 'D:\DATA\my_1.LDF'
);
Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:
ALTER DATABASE my SET ONLINE;
ALTER DATABASE my SET MULTI_USER;
This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.
As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:
JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
tuxfiles.org holds a pretty good cheat sheet. I think there are a couple of points to learning the commands:
d$
), go a quick google search to see if you can find a command for it.Besides these tips, there are some basic concepts you should understand.
d$
. To highlight a line after a particular character use v$
. So notice that $
indicates you will be doing something to the end of the line from where your cursor currently is.u
is undo, and ctrl+r
is redo.3dd
will delete the line your cursor is on and the two lines that follow, similarly 3yy
will copy the line your cursor is on and the two lines that follow.:ls
to list the buffers, and :bn
, :bp
to cycle through them.:help
This is probably the best way to 'learn the ropes', and the rest of the commands you will learn through usage.In my case, I missed to write @JsonProperty annotation in one of the fields which was causing this error.
"check out this i m sure you will like it."
log_in.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
username=user_name.getText().toString();
password=pass_word.getText().toString();
if(username.equals(""))
{
user_name.setError("Enter username");
}
else if(password.equals(""))
{
pass_word.setError("Enter your password");
}
else
{
Intent intent=new Intent(MainActivity.this,Scan_QRActivity.class);
startActivity(intent);
}
}
});
Update for MySQL 8.0
Your sql-mode
will not have NO_AUTO_CREATE_USER
as it has been removed as mentioned here - how-to-set-sql-mode-in-my-cnf-in-mysql-8
[mysqld]
sql-mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
Also if someone doesn't have a my.cnf
file then they create a new one in /etc/my.cnf
and then add the above lines.
//Xcode 8.1 and swift 3.0
We can also handle it by Optional Binding, Simply
let occur = "10"
if let occ = Int(occur) {
print("By optional binding :", occ*2) // 20
}
h1 { font-size: 150%; }
h2 { font-size: 120%; }
Tune as needed.
How about this?
if (window.location.protocol !== 'https:') {
window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}
Ideally you'd do it on the server side, though.
This does not need assertion, Latest update in fragment in android JetPack
requireActivity().finish();
For Kotlin Here is added the lambda expression and Optimized the Code.
radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
run {
when (optionId) {
R.id.radioButton1 -> {
// do something when radio button 1 is selected
}
R.id.radioButton2 -> {
// do something when radio button 2 is selected
}
// add more cases here to handle other buttons in the your RadioGroup
}
}
}
Hope this will help you. Thanks!
You can take a look at InterpolatedUnivariateSpline
Here an example using it:
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline
# given values
xi = np.array([0.2, 0.5, 0.7, 0.9])
yi = np.array([0.3, -0.1, 0.2, 0.1])
# positions to inter/extrapolate
x = np.linspace(0, 1, 50)
# spline order: 1 linear, 2 quadratic, 3 cubic ...
order = 1
# do inter/extrapolation
s = InterpolatedUnivariateSpline(xi, yi, k=order)
y = s(x)
# example showing the interpolation for linear, quadratic and cubic interpolation
plt.figure()
plt.plot(xi, yi)
for order in range(1, 4):
s = InterpolatedUnivariateSpline(xi, yi, k=order)
y = s(x)
plt.plot(x, y)
plt.show()
Because C# doesn't allow that type of inheritance conversion at the moment.
This is working for me.
latestsetuplist = SetupTemplate.objects.order_by('-creationTime')[:10][::1]
You could use a semaphore.
While the condition is not met, another thread acquires the semaphore.
Your thread would try to acquire it with acquireUninterruptibly()
or tryAcquire(int permits, long timeout, TimeUnit unit)
and would be blocked.
When the condition is met, the semaphore is also released and your thread would acquire it.
You could also try using a SynchronousQueue
or a CountDownLatch
.
if you do not want to be bothered by the date format, you could compare the column with the general date format, for example
select *
From table
where cast (RegistrationDate as date) between '20161201' and '20161220'
make sure the date is in DATE format, otherwise cast (col as DATE)
I get it resolved appending datetime as an random number:
$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
console.log('your get response is new!!!');
});
An 8-digit hex color value is a representation of ARGB (Alpha, Red, Green, Blue), whereas a 6-digit value just assumes 100% opacity (fully opaque) and defines just the RGB values. So to make this be fully opaque, you can either use #FF555555, or just #555555. Each 2-digit hex value is one byte, representing values from 0-255.
This can also occur if you change the name of your xib file, and you forget to change all the places it is referenced.
Example: MainWindow.xib is a TabBarController that contains a custom ViewController named FirstViewController with associated xib file FirstView. You change the name to SecondViewController and associated xib file to SecondView.
Solution:
Open MainWindow.xib (that contains the TabBarController):
Open SecondView.xib (this was copied from FirstView.xib):
Optionally you may need to:
Tested Code:
$("input").css("background","red");
Complete:
$('input:text').focus(function () {
$(this).css({ 'background': 'Black' });
});
$('input:text').blur(function () {
$(this).css({ 'background': 'red' });
});
Tested in version:
jquery-1.9.1.js
jquery-ui-1.10.3.js
strtotime
? Lists? Regular expressions?
What's wrong with PHP's native DateTime object?
For whose want create a Custom Cell :
CustomCell.h
#import <UIKit/UIKit.h>
@interface HeaderCollectionViewCell : UICollectionViewCell
@property (strong,nonatomic) UIImageView *image;
@end
CustomCell.m
#import "HeaderCollectionViewCell.h"
@implementation HeaderCollectionViewCell
#define IMAGEVIEW_BORDER_LENGTH 5
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
-(void)setup{
_image = [[UIImageView alloc] initWithFrame:(CGRectInset(self.bounds, IMAGEVIEW_BORDER_LENGTH, IMAGEVIEW_BORDER_LENGTH))];
[self addSubview:_image];
}
@end
UIViewController.h
#import <UIKit/UIKit.h>
@interface HomeViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (strong,nonatomic) UICollectionView *collectionView;
@end
UIViewController.m
#import "HomeViewController.h"
#import "HomeView.h"
#import "HeaderCollectionViewCell.h"
@interface HomeViewController ()
@property (nonatomic) NSString *cellID;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.whiteColor;
_cellID = @"id";
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
_collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_collectionView registerClass:[HeaderCollectionViewCell class] forCellWithReuseIdentifier:_cellID];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
_collectionView.backgroundColor = UIColor.redColor;
[self.view addSubview:_collectionView];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 4;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
HeaderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_cellID forIndexPath:indexPath];
cell.image.image = [UIImage imageNamed:@"premium-icon"];
return cell;
}
-(UITabBarItem*) tabBarItem{
return [[UITabBarItem alloc] initWithTitle:@"Início" image:[UIImage imageNamed:@"home-icon"] tag:0];
}
@end
You get the cursor position by calling GetCursorPos
.
POINT p;
if (GetCursorPos(&p))
{
//cursor position now in p.x and p.y
}
This returns the cursor position relative to screen coordinates. Call ScreenToClient
to map to window coordinates.
if (ScreenToClient(hwnd, &p))
{
//p.x and p.y are now relative to hwnd's client area
}
You hide and show the cursor with ShowCursor
.
ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again
You must ensure that every call to hide the cursor is matched by one that shows it again.
This worked for me in Eclipse Mars with WildFly 11. Double-click on WildFly server under Servers to open the configuration page. In the Overview tab -> Publishing, choose "Automatically publish when resources change" and set the interval to 1. Next, Overview tab -> Application Reload Behavior, uncheck the use default pattern and set the pattern to \.jar$|\.class$
. In the Deployment tab, uncheck Deploy project as compressed archives. Hope this helps.
You may also need to enable the World Wide Web Service inbound firewall rule.
On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules
Find World Wide Web Services (HTTP Traffic-In)
in the list and select to enable the rule. Change is pretty much immediate.
Lets do some experimentation, to see how we could get/interpret the length of different dict/array values in a dict.
create our test dict, see list and dict comprehensions:
>>> my_dict = {x:[i for i in range(x)] for x in range(4)}
>>> my_dict
{0: [], 1: [0], 2: [0, 1], 3: [0, 1, 2]}
Get the length of the value of a specific key:
>>> my_dict[3]
[0, 1, 2]
>>> len(my_dict[3])
3
Get a dict of the lengths of the values of each key:
>>> key_to_value_lengths = {k:len(v) for k, v in my_dict.items()}
{0: 0, 1: 1, 2: 2, 3: 3}
>>> key_to_value_lengths[2]
2
Get the sum of the lengths of all values in the dict:
>>> [len(x) for x in my_dict.values()]
[0, 1, 2, 3]
>>> sum([len(x) for x in my_dict.values()])
6
Suppose consider two string s and t.
Give them some values.
When you compare them using (s==t) it returns a boolean value(true or false , 1 or 0).
But when you compare using s.compare(t) ,the expression returns a value
(i) 0 - if s and t are equal
(ii) <0 - either if the value of the first unmatched character in s is less than that of t or the length of s is less than that of t.
(iii) >0 - either if the value of the first unmatched character in t is less than that of s or the length of t is less than that of s.
it takes this command about 2 mins to return the data as there is a lot of data
Probably, Bad Design. Consider using paging here.
default connection time is 30 secs, how do I increase this
As you are facing a timeout on your command, therefore you need to increase the timeout of your sql command. You can specify it in your command like this
// Setting command timeout to 2 minutes
scGetruntotals.CommandTimeout = 120;
Maybe
SELECT count(*) FROM (
SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total
although that would not be the sum of all the movies, just how many have 4 genre's.
So maybe you want
SELECT sum(
SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total
check this Twig Reference.
You can do it that simple:
{% if (a or b) %}
...
{% endif %}
the 3 additive colors are in fact red, green, and blue. printers use cmyk (cyan, magenta, yellow, and black).
and as http://en.wikipedia.org/wiki/Additive_color explains: if you use RYB as your primary colors, how do you make green? since yellow is made from equal amounts of red and green.
I had this problem on production with Heroku and locally while debugging on my macbook pro this morning.
After an hour of debugging, this resolved on its own both locally and on production. I'm not sure what fixed it, so that's a bit annoying. It happened right when I thought I did something, but reverting my supposed fix didn't bring the problem back :(
Interestingly enough, it appears my database service, MongoDb has been having server problems since this morning, so there's a good chance this was related to it.
In my case, the Google Services gradle plugin wasn't generating the required values.xml
file from the google-services.json
file. The Firebase library uses this generated values file to initialize itself and it appears that it doesn't throw an error if the values file can't be found. Check that the values file exists at the following location and is populated with the appropriate strings from your google-sevices.json
file:
app/build/generated/res/google-services/{build_type}/values/values.xml
and/or
app/build/generated/res/google-services/{flavor}/{build_type}/xml/global_tracker.xml
For more detail see: https://developers.google.com/android/guides/google-services-plugin
My particular case was caused by using a gradle tools version that was too advanced for the version of Android Studio that I was running (ie ensure you run grade tools v3.2.X-YYY with Android Studio v3.2).
I think you just have it backwards.
print ", ".join(set_3)
UPDATED ANSWER for iOS 13 and scene delegate:
make sure in your info.plist file you go into Application Scene Manifest -> Scene Configuration -> Application Session Role -> Item 0 and delete the reference to the main storyboard there as well. Otherwise you'll get the same warning about failing to instantiate from storyboard.
Also, move the code from the app delegate to the scene delegate method scene(_:willConnectTo:options:), since this is where life cycle events are handled now.
In Eclipse, Goto Window-> Show View -> Other -> Android-> Logcat.
Logcat is nothing but a console of your Emulator or Device.
System.out.println
does not work in Android. So you have to handle every thing in Logcat. More Info Look out this Documentation.
Edit 1: System.out.println is working on Logcat. If you use that the Tag will be like System.out and Message will be your message.
Typing /**
+ then pressing Enter above a method signature will create Javadoc stubs for you.
This helps for me to do IN condition Hope this will help you..
CREATE PROCEDURE `test`(IN Array_String VARCHAR(100))
BEGIN
SELECT * FROM Table_Name
WHERE FIND_IN_SET(field_name_to_search, Array_String);
END//;
Calling:
call test('3,2,1');
Another way to use itertools.ifilter
. This checks truthiness and process
(using lambda
)
Sample-
for x in itertools.ifilter(lambda x: x[2] == 0, my_list):
print x
if you are sure that you did the right thing, but docker still complains, take a look at this issue: https://github.com/moby/moby/issues/27134.
I got burnt by this, and it seems like restarting docker engine service docker restart
will just fix this problem.
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
Shorter:
$html = preg_replace("/<script.*?\/script>/s", "", $html);
When doing regex things might go wrong, so it's safer to do like this:
$html = preg_replace("/<script.*?\/script>/s", "", $html) ? : $html;
So that when the "accident" happen, we get the original $html instead of empty string.
I faced this issue because my web page was zoomed out to 90% and as I was viewing my page in responsive mode through the browser developer tools, I did not notice it right away.
Docker container exits if task inside is done, so if you want to keep it alive even if it does not have any job or already finished them, you can do docker run -di image
. After you do docker container ls
you will see it running.
The only solution that worked for me and $.each
was definitely causing the error. so i used for loop
and it's not throwing error anymore.
Example code
$.ajax({
type: 'GET',
url: 'https://example.com/api',
data: { get_param: 'value' },
success: function (data) {
for (var i = 0; i < data.length; ++i) {
console.log(data[i].NameGerman);
}
}
});
There are several ways to do plots in R; lattice
is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:
Reasonstats <- read.table(text="Category Reason Species
Decline Genuine 24
Improved Genuine 16
Improved Misclassified 85
Decline Misclassified 41
Decline Taxonomic 2
Improved Taxonomic 7
Decline Unclear 41
Improved Unclear 117", header=T)
ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3 <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason
windows()
barplot(t(Reasonstats3), beside=TRUE, ylab="number of species",
cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
box(bty="l")
Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline
and for Improved
. Then I made those categories the column names. I also made the Reason
s the row names. The barplot()
function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot()
function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot()
wants for your intended output.
The simpler way is:
DELETE TableA
FROM TableB
WHERE TableA.ID = TableB.ID
Your old version of the app that you are installing has dependent libraries / jars that have been changed. I ran into this issue when updating other jar files that my app was refrencing.
You will need to Uninstall your old version and then you should have no more issues...
Settings-->Applications-->Manage Applications-->[Find and Uninstall your App]
INSTALL_FAILED_DEXOPT errors should not erupt. Like
[2011-06-14 01:23:40 - ProtectYourself] Installing ProtectYourself.apk...
[2011-06-14 01:24:26 - ProtectYourself] Installation error: INSTALL_FAILED_DEXOPT
[2011-06-14 01:24:26 - ProtectYourself] Please check logcat output for more details.
[2011-06-14 01:24:26 - ProtectYourself] Launch canceled!
Whoo hoo.
Hi I'm also relatively new but I can give you basic help.
UPDATE 12.01.2016:
The bold line is the current branch.
You can also just double click a branch to use checkout.
And here some helpful links:
You are making a wrong assumption. Just because the debugger/Playground shows your dictionary in square brackets (which is how Cocoa displays dictionaries) that does not mean that is the way the JSON output is formatted.
Here is example code that will convert a dictionary of strings to JSON:
Swift 3 version:
import Foundation
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
withJSONObject: dictionary,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .ascii)
print("JSON string = \(theJSONText!)")
}
To display the above in "pretty printed" format you'd change the options line to:
options: [.prettyPrinted]
Or in Swift 2 syntax:
import Foundation
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
let theJSONData = NSJSONSerialization.dataWithJSONObject(
dictionary ,
options: NSJSONWritingOptions(0),
error: nil)
let theJSONText = NSString(data: theJSONData!,
encoding: NSASCIIStringEncoding)
println("JSON string = \(theJSONText!)")
The output of that is
"JSON string = {"anotherKey":"anotherValue","aKey":"aValue"}"
Or in pretty format:
{
"anotherKey" : "anotherValue",
"aKey" : "aValue"
}
The dictionary is enclosed in curly braces in the JSON output, just as you'd expect.
In Swift 3/4 syntax, the code above looks like this:
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
withJSONObject: dictionary,
options: .prettyPrinted
),
let theJSONText = String(data: theJSONData,
encoding: String.Encoding.ascii) {
print("JSON string = \n\(theJSONText)")
}
}
Alternatively, if you want to specify expected parameters in action signature, but pass them as arbitrary GET
arguments. Use filters, for example:
Create a route without parameters:
$Route::get('/history', ['uses'=>'ExampleController@history']);
Specify action with two parameters and attach the filter:
class ExampleController extends BaseController
{
public function __construct($browser)
{
$this->beforeFilter('filterDates', array(
'only' => array('history')
));
}
public function history($fromDate, $toDate)
{
/* ... */
}
}
Filter that translates GET
into action's arguments :
Route::filter('filterDates', function($route, Request $request) {
$notSpecified = '_';
$fromDate = $request->get('fromDate', $notSpecified);
$toDate = $request->get('toDate', $notSpecified);
$route->setParameter('fromDate', $fromDate);
$route->setParameter('toDate', $toDate);
});
It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.
Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
Map<String, DataSet> result = new HashMap<>();
multiDataPoints.forEach(pt ->
pt.keyToData.forEach((key, value) ->
result.computeIfAbsent(
key, k -> new DataSet(k, new ArrayList<>()))
.dataPoints.add(new DataPoint(pt.timestamp, value))));
return result.values();
}
Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
new Object() {
String key = e.getKey();
DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
}))
.collect(
collectingAndThen(
groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}
Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.map(mdp -> mdp.keyToData.entrySet().stream()
.collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
.reduce(new HashMap<>(), mapMerger())
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:
<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
return (lhs, rhs) -> {
Map<K, List<V>> result = new HashMap<>();
lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
return result;
};
}
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
Check that you have free space on /var as this is where Docker stores the image files by default (in /var/lib/docker).
First clean stuff up by using docker ps -a
to list all containers (including stopped ones) and docker rm
to remove them; then use docker images
to list all the images you have stored and docker rmi
to remove them.
Next change the storage location with a -g option on the docker daemon or by editing /etc/default/docker
and adding the -g
option to DOCKER_OPTS
. -g
specifies the location of the "Docker runtime" which is basically all the stuff that Docker creates as you build images and run containers. Choose a location with plenty of space as the disk space used will tend to grow over time. If you edit /etc/default/docker
, you will need to restart the docker daemon for the change to take effect.
Now you should be able to create a new image (or pull one from Docker Hub) and you should see a bunch of files getting created in the directory you specified with the -g option.
Your applets will run.
If they are still not running then you have to add that website name in exception site list of Security tab of Java in Control panel.
Lets make it very simple:
Maven Lifecycles: 1. Clean 2. Default (build) 3. Site
Maven Phases of the Default Lifecycle: 1. Validate 2. Compile 3. Test 4. Package 5. Verify 6. Install 7. Deploy
Note: Don't mix or get confused with maven goals with maven lifecycle.
See Maven Build Lifecycle Basics1
Try:
string output = YourString.replaceAll("\\s","")
s - indicates space character (tab characters etc)
Total online memory
Calculate the total online memory using the sys-fs.
totalmem=0;
for mem in /sys/devices/system/memory/memory*; do
[[ "$(cat ${mem}/online)" == "1" ]] \
&& totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes)))));
done
#one-line code
totalmem=0; for mem in /sys/devices/system/memory/memory*; do [[ "$(cat ${mem}/online)" == "1" ]] && totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes))))); done
echo ${totalmem} bytes
echo $((totalmem/1024**3)) GB
Example output for 4 GB system:
4294967296 bytes
4 GB
Explanation
/sys/devices/system/memory/block_size_bytes
Number of bytes in a memory block (hex value). Using 0x in front of the value makes sure it's properly handled during the calculation.
/sys/devices/system/memory/memory*
Iterating over all available memory blocks to verify they are online and add the calculated block size to totalmem if they are.
[[ "$(cat ${mem}/online)" == "1" ]] &&
You can change or remove this if you prefer another memory state.
Change all "es6" and "es7" to "es" in your polyfills.ts and polyfills.ts
the app domain is your domain name.
Before you enter your domain, first click on Add Platform, select website, enter your site URL and mobile site url. Save the settings.
Thereafter, you can enter the domain name in the App domains field.
See more at my blog: http://www.ogbongeblog.com/2014/03/unable-to-add-app-domains-to-new.html
<div class="container">
<div class="box">
<img src="http://lorempixel.com/1600/1200/" alt="">
</div>
</div>
.container {
display: flex;
flex-direction: row;
justify-content: center;
align-items: stretch;
width: 100%;
height: 100%;
border-radius: 4px;
background-color: hsl(0, 0%, 96%);
}
.box {
border-radius: 4px;
display: flex;
}
.box img {
width: 100%;
object-fit: contain;
border-radius: 4px;
}
Common Query To Check Database Size in SQL Server that supports both Azure and On-Premises-
Method 1 – Using ‘sys.database_files’ System View
SELECT
DB_NAME() AS [database_name],
CONCAT(CAST(SUM(
CAST( (size * 8.0/1024) AS DECIMAL(15,2) )
) AS VARCHAR(20)),' MB') AS [database_size]
FROM sys.database_files;
Method 2 – Using ‘sp_spaceused’ System Stored Procedure
EXEC sp_spaceused ;
You can use the stringr
library:
library('stringr')
a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A_C
# 6 0.55313288 f A_C
# 7 0.31264280 g A_C
# 8 0.33759921 h A_C
# 9 0.72322599 i A_C
# 10 0.25223075 j A_C
data$c <- str_replace_all(data$c, '_', '-')
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A-C
# 6 0.55313288 f A-C
# 7 0.31264280 g A-C
# 8 0.33759921 h A-C
# 9 0.72322599 i A-C
# 10 0.25223075 j A-C
Note that this does change factored variables into character.
Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget
when you want to retrieve it again as a list.
dput(mylist, "mylist.txt")
Does GitHub have this social feature?
If the commit email is kept private, GitHub now (July 2020) proposes:
Users and organizations can now add Twitter usernames to their GitHub profiles
You can now add your Twitter username to your GitHub profile directly from your profile page, via profile settings, and also the REST API.
We've also added the latest changes:
- Organization admins can now add Twitter usernames to their profile via organization profile settings and the REST API.
- All users are now able to see Twitter usernames on user and organization profiles, as well as via the REST and GraphQL APIs.
- When sponsorable maintainers and organizations add Twitter usernames to their profiles, we'll encourage new sponsors to include that Twitter username when they share their sponsorships on Twitter.
That could be a workaround to leave a message to a GitHub user.
You should find them by default in a folder like /etc/my.cnf
, maybe also depends on versions. From MySQL Configuration File:
Interestingly, the scope of this file can be set according to its location. The settings will be considered global to all MySQL servers if stored in /etc/my.cnf. It will be global to a specific server if located in the directory where the MySQL databases are stored (/usr/local/mysql/data for a binary installation, or /usr/local/var for a source installation). Finally, its scope could be limited to a specific user if located in the home directory of the MySQL user (~/.my.cnf). Keep in mind that even if MySQL does locate a my.cnf file in /etc/my.cnf (global to all MySQL servers on that machine), it will continue its search for a server-specific file, and then a user-specific file. You can think of the final configuration settings as being the result of the /etc/my.cnf, mysql-data-dir/my.cnf, and ~/.my.cnf files.
There are a few switches to package managers to list specific files.
RPM Sytems:
There are switches to rpm
command, -q
for query, and -c
or --configfiles
to list config files. There is also -l
or --list
The --configfiles
one didn't quiet work for me, but --list
did list a few .cnf
files held by mysql-server
rpm -q --list mysql-server
DEB Systems:
Also with limited success: dpkg --listfiles mysql-server
if ($inputs['type'] == 'attach') {
The code is valid, but it expects the function parameter $inputs
to be an array. The "Illegal string offset" warning when using $inputs['type']
means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type'
is not suitable.)
So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.
However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type'
to 0
, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)
You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs);
in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:
if (is_array($inputs) && $inputs['type'] == 'attach') {
Set the XML as:
<ToggleButton
android:id="@+id/flashlightButton"
style="@style/Button"
android:layout_above="@+id/buttonStrobeLight"
android:layout_marginBottom="20dp"
android:onClick="onToggleClicked"
android:text="ToggleButton"
android:textOn="Light ON"
android:textOff="Light OFF" />
Correct Method is
.PopupPanel
{
border: solid 1px black;
position: fixed;
left: 50%;
top: 50%;
background-color: white;
z-index: 100;
height: 400px;
margin-top: -200px;
width: 600px;
margin-left: -300px;
}
You can use a Deferred objects for ASYNC loading.
function load_img_async(source) {
return $.Deferred (function (task) {
var image = new Image();
image.onload = function () {task.resolve(image);}
image.onerror = function () {task.reject();}
image.src=source;
}).promise();
}
$.when(load_img_async(IMAGE_URL)).done(function (image) {
$(#id).empty().append(image);
});
Please pay attention: image.onload must be before image.src to prevent problems with cache.
Expanding on someone else's answer:
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
Using json_encode() requires:
$myVarValue
encoded as UTF-8 (or US-ASCII, of course)Since UTF-8 supports full Unicode, it should be safe to convert on the fly.
Note that because json_encode
escapes forward slashes, even a string that contains </script>
will be escaped safely for printing with a script block.
Adding JDK path through JAVA_HOME tab in "Open Gradle Run Configuration" will solve the problem.
When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
Apply SerializableAttribute
to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute
even if the class also implements the ISerializable
interface to control the serialization process.
All the public and private fields in a type that are marked by the SerializableAttribute
are serialized by default, unless the type implements the ISerializable
interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute
. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute
to that field.
See MSDN for more details.
Edit 1
Any reason to not mark something as serializable
When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.
For me, I had to change a line of code in my local_env.yml
to get the rspec tests to run.
I had originally had:
REDIS_HOST: 'redis'
and changed it to:
REDIS_HOST: 'localhost'
and the test ran fine.