Other solutions didn't work form me, here's mine. It applies only to Xcode 8 when running in Swift 2.3 legacy mode:
Looks like Interface Builder is trying to rename the method that should be hooked up to the button.
Here's a radar with more details.
The solution (workaround) is to manually replace the method parameter name to _
:
@IBAction func editPictureTapped(sender: UIButton) { // not working
print("Tapped")
}
Change to this:
@IBAction func editPictureTapped(_: UIButton) { // working OK
print("Tapped")
}
(This is already answered in comments, but since it lacks an actual answer, I'm writing this.)
This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are using different versions of the CRT (the C RunTime library.)
To correct this error, you need to go into your Project Properties
(and/or those of the libraries you are using,) then into C/C++
, then Code Generation
, and check the value of Runtime Library
; this should be exactly the same for all the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)
There are currently four options for this setting:
Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug DLL" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.
Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.
For (some) more information, you can see these (linked from a comment above):
UPDATE: (This is in response to a comment that asks for the reason that this much care must be taken.)
If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless great care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)
The most important part of the problem is this: having the same idea about the size of objects on either side of a function call.
Consider for example that the above two pieces of code are called A
and B
. A is compiled against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a FILE
object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)
Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)
The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.
All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)
This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.
What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it!
Just add the classes to your html
<div class="someDiv radius opacity"></div>
You will have to test your data VERY well. This can get messy. Here is an example of results simply by multiplying the value by 10. Run this to see what happens. On my SQL Server 2017 box, at the 3rd query I get a bunch of *********. If you CAST as BIGINT it should work every time. But if you don't and don't test enough data you could run into problems later on, so don't get sucked into thinking it will work on all of your data unless you test the maximum expected value.
Declare @Floater AS FLOAT =100000003.141592653
SELECT CAST(ROUND(@Floater,0) AS VARCHAR(30) ),
CONVERT(VARCHAR(100),ROUND(@Floater,0)),
STR(@Floater)
SET @Floater =@Floater *10
SELECT CAST(ROUND(@Floater,0) AS VARCHAR(30) ),
CONVERT(VARCHAR(100),ROUND(@Floater,0)),
STR(@Floater)
SET @Floater =@Floater *100
SELECT CAST(ROUND(@Floater,0) AS VARCHAR(30) ),
CONVERT(VARCHAR(100),ROUND(@Floater,0)),
STR(@Floater)
The same as @neobot's answer but a little more modern and succinct.
>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'
Two things to do:
Project Settings > Project compiler output > Set it as "Project path(You actual project's path)”+”\out”.
Project Settings > Module > Path > Choose "Inherit project compile path"
One problem with StringWriter
is that by default it doesn't let you set the encoding which it advertises - so you can end up with an XML document advertising its encoding as UTF-16, which means you need to encode it as UTF-16 if you write it to a file. I have a small class to help with that though:
public sealed class StringWriterWithEncoding : StringWriter
{
public override Encoding Encoding { get; }
public StringWriterWithEncoding (Encoding encoding)
{
Encoding = encoding;
}
}
Or if you only need UTF-8 (which is all I often need):
public sealed class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
As for why you couldn't save your XML to the database - you'll have to give us more details about what happened when you tried, if you want us to be able to diagnose/fix it.
this works for me
Open the file bootstrap-datepicker.js
Go to line 1399 and find format: 'mm/dd/yyyy'
.
Now you can change the date format here.
Is your goal...
Results
in one row and
all the instances of "Bob Jones" in
Archive_Results
in a separate row?Assuming it's #1 you'd want something like...
SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name
This error raised up because you trying to update dict
object by using a wrong sequence (list
or tuple
) structure.
cash_id.create(cr, uid, lines,context=None)
trying to convert lines
into dict object:
(0, 0, {
'name': l.name,
'date': l.date,
'amount': l.amount,
'type': l.type,
'statement_id': exp.statement_id.id,
'account_id': l.account_id.id,
'account_analytic_id': l.analytic_account_id.id,
'ref': l.ref,
'note': l.note,
'company_id': l.company_id.id
})
Remove the second zero from this tuple to properly convert it into a dict object.
To test it your self, try this into python shell:
>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
>>> l=[(0,{'h':88})]
>>> a.update(l)
2 possible reasons:
If using MS Access (especially older versions like 2003) you are forced to use TEXT
datatype on SQL Server as MS Access does not recognize nvarchar(MAX)
as a Memo field in Access, whereas TEXT
is recognized as a Memo-field.
You could use Vi/Vim's Visual Block mode which is designed for stuff like this:
Ctrl-V
Highlight first element in rows you want commented
Shift-i
#
esc
Uncomment would be:
Ctrl-V
Highlight #'s
d
l
This is vi's interactive way of doing this sort of thing rather than counting or reading line numbers.
Lastly, in Gvim you use ctrl-q to get into Visual Block mode rather than ctrl-v (because that's the shortcut for paste).
You can use git log to display the diffs while searching:
git log -p -- path/to/file
Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:
The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
POP and IMAP bandwidth limits
Limit Per day
Download via IMAP 2500 MB
Download via POP 1250 MB
Upload via IMAP 500 MB
How about:
conditions = [a, b, c]
if any(conditions) and not all(conditions):
...
Other variant:
if 1 <= sum(map(bool, conditions)) <= 2:
...
Yeah, I know this is an 8 year-old question, but I was told that it was possible to statically link against a shared-object library and this was literally the top hit when I searched for more information about it.
To actually demonstrate that statically linking a shared-object library is not possible with ld
(gcc
's linker) -- as opposed to just a bunch of people insisting that it's not possible -- use the following gcc
command:
gcc -o executablename objectname.o -Wl,-Bstatic -l:libnamespec.so
(Of course you'll have to compile objectname.o
from sourcename.c
, and you should probably make up your own shared-object library as well. If you do, use -Wl,--library-path,.
so that ld can find your library in the local directory.)
The actual error you receive is:
/usr/bin/ld: attempted static link of dynamic object `libnamespec.so'
collect2: error: ld returned 1 exit status
Hope that helps.
To put it a different way "id()" is not what you care about. You want to know if the variable name can be modified without harming the source variable name.
>>> a = 'hello'
>>> b = a[:]
>>> c = a
>>> b += ' world'
>>> c += ', bye'
>>> a
'hello'
>>> b
'hello world'
>>> c
'hello, bye'
If you're used to C, then these are like pointer variables except you can't de-reference them to modify what they point at, but id() will tell you where they currently point.
The problem for python programmers comes when you consider deeper structures like lists or dicts:
>>> o={'a': 10}
>>> x=o
>>> y=o.copy()
>>> x['a'] = 20
>>> y['a'] = 30
>>> o
{'a': 20}
>>> x
{'a': 20}
>>> y
{'a': 30}
Here o and x refer to the same dict o['a'] and x['a'], and that dict is "mutable" in the sense that you can change the value for key 'a'. That's why "y" needs to be a copy and y['a'] can refer to something else.
I solved this converting the JSP from XHTML to HTML, doing this in the begining:
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
...
I don't try changing sequence via setval
. But using ALTER
I was issued how to write sequence name properly. And this only work for me:
Check required sequence name using SELECT * FROM information_schema.sequences;
ALTER SEQUENCE public."table_name_Id_seq" restart {number};
In my case it was ALTER SEQUENCE public."Services_Id_seq" restart 8;
Also there is a page on wiki.postgresql.org where describes a way to generate sql script to fix sequences in all database tables at once. Below the text from link:
Save this to a file, say 'reset.sql'
SELECT 'SELECT SETVAL(' || quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) || ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' || quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';' FROM pg_class AS S, pg_depend AS D, pg_class AS T, pg_attribute AS C, pg_tables AS PGT WHERE S.relkind = 'S' AND S.oid = D.objid AND D.refobjid = T.oid AND D.refobjid = C.attrelid AND D.refobjsubid = C.attnum AND T.relname = PGT.tablename ORDER BY S.relname;
Run the file and save its output in a way that doesn't include the usual headers, then run that output. Example:
psql -Atq -f reset.sql -o temp psql -f temp rm temp
And the output will be a set of sql commands which look exactly like this:
SELECT SETVAL('public."SocialMentionEvents_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."SocialMentionEvents";
SELECT SETVAL('public."Users_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."Users";
You can use the get() on each dict. Make sure that you have added the None check for each access.
This is a complementary answer for the specific case of you using AWS cloud computing (either EC2 or RDS machines).
Besides doing everything proposed above, when using AWS cloud computing you will need to set you inbound rules in a way that let you access to the ports. Please check this post, which is valid for EC2 and RDS.
This error happened to me, generally it'll be a problem due to not including the mysql-connector.jar in your eclipse project (or your IDE).
In my case, it was because of a problem on the OS.
I was editing a table in phpmyadmin, and mysql hung, I restarted Ubuntu. I cleaned the project without being successful. This morning, when I've tried the web server, it work perfectly the first time.
At the first reboot, the OS recognized that there was a problem, and after the second one, it was fixed. I hope this will save some time to somebody that "could" have this problem!
I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.
To select top n rows updated recently
SELECT *
FROM (
SELECT *
FROM table
ORDER BY UpdateDateTime DESC
)
WHERE ROWNUM < 101;
You can use the -B
option.
-B, --block-size=SIZE use SIZE-byte blocks
All together,
df -BG
Try:
InputStream inputStream= // Your InputStream from your database.
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
saxParser.parse(is, handler);
If it's anything else than UTF-8, just change the encoding part for the good one.
You cannot clear the browser history. It belongs to the user, not the developer. Also have a look at the MDN documentation.
Update: The link you were posting all over does not actually clear your browser history. It just prevents using the back button.
In case you are running it on Fedora or CentOS, this is what worked for me (PostgreSQL 9.6):
In terminal:
$ sudo visudo -f /etc/sudoers
modify the following text from:
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
to
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/pgsql-9.6/bin
exit, then:
$ printenv PATH
$ sudo su postgres
$ psql
To exit postgreSQL terminal, you need to digit:
$ \q
Source: https://serverfault.com/questions/541847/why-doesnt-sudo-know-where-psql-is#comment623883_541880
You can either:
Examples are on the msdn pages provided
Try the following-sibling
axis (following-sibling::td
).
// just use (useEffect). every change will be logged with current value
import React, { useEffect } from "react";
export function () {
useEffect(() => {
window.addEventListener('resize', () => {
const myWidth = window.innerWidth;
console.log('my width :::', myWidth)
})
},[window])
return (
<>
enter code here
</>
)
}
Here is how it worked beautifully for me. In the window resources add the image.
<Image x:Key="delImg" >
<Image.Source>
<BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
</Image.Source>
</Image>
Then the code goes like this.
Image img = new Image()
img.Source = ((Image)this.Resources["delImg"]).Source;
"this" is referring to the Window object
For Redmi users,
Settings -> Password & security -> Privacy -> Special app access -> Device admin apps
Click the deactivate the apps
(First, I'd like to recommend this useful reference site for batch: http://ss64.com/nt/)
Then just another useful explanation: http://htipe.wordpress.com/2008/10/09/the-dp0-variable/
The %~dp0 Variable
The
%~dp0
(that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.The variables
%0-%9
refer to the command line parameters of the batch file.%1-%9
refer to command line arguments after the batch file name.%0
refers to the batch file itself.If you follow the percent character (
%
) with a tilde character (~
), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. Thed
modifier expands to the drive letter and thep
modifier expands to the path of the parameter.Example: Let’s say you have a directory on
C:
calledbat_files
, and in that directory is a file calledexample.bat
. In this case,%~dp0
(combining thed
andp
modifiers) will expand toC:\bat_files\
.Check out this Microsoft article for a full explanation.
Also, check out this forum thread.
And a more clear reference from here:
%CmdCmdLine%
will return the entire command line as passed to CMD.EXE
%*
will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces)
%~dn
will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC)
%~pn
will return the directory of %n if %n is a valid path or file name (no UNC)
%~nn
will return the file name only of %n if %n is a valid file name
%~xn
will return the file extension only of %n if %n is a valid file name
%~fn
will return the fully qualified path of %n if %n is a valid file name or directory
Just found some good reference for the mysterious ~
tilde operator.
The %~
string is called percent tilde operator. You can find it in situations like: %~0
.
The :~
string is called colon tilde operator. You can find it like %SOME_VAR:~0,-1%
.
%1-%9
refer to the command line args. If they are not valid path values, %~dp1
- %~dp9
will all expand to the same value as %~dp0
. But if they are valid path values, they will expand to their own driver/path value.
For example: (batch.bat)
@echo off
@echo ~dp0= %~dp0
@echo ~dp1= %~dp1
@echo ~dp2= %~dp2
@echo on
Run 1:
D:\Workbench>batch arg1 arg2
~dp0= D:\Workbench\
~dp1= D:\Workbench\
~dp2= D:\Workbench\
Run 2:
D:\Workbench>batch c:\123\a.exe e:\abc\b.exe
~dp0= D:\Workbench\
~dp1= c:\123\
~dp2= e:\abc\
In minimalistic programs where a size_t
definition was not loaded "by chance" in some include but I still need it in some context (for example to access std::vector<double>
), then I use that context to extract the correct type. For example typedef std::vector<double>::size_type size_t
.
(Surround with namespace {...}
if necessary to make the scope limited.)
I can't comment yet but following on Fellow Stranger solution you can also keep nesting in case you have keys which values are an array. Like this:
filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]
This works:
params.require(:model).permit(filters: [[:name, values: []]])
I like Ctrl+K, Ctrl+D, which indents the whole document.
Based on this post: https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range
You can do the following:
def normalize(df):
result = df.copy()
for feature_name in df.columns:
max_value = df[feature_name].max()
min_value = df[feature_name].min()
result[feature_name] = (df[feature_name] - min_value) / (max_value - min_value)
return result
You don't need to stay worrying about whether your values are negative or positive. And the values should be nicely spread out between 0 and 1.
Drag the constraint into your VC as an IBOutlet. Then you can change its associated value (and other properties; check the documentation):
@IBOutlet myConstraint : NSLayoutConstraint!
@IBOutlet myView : UIView!
func updateConstraints() {
// You should handle UI updates on the main queue, whenever possible
DispatchQueue.main.async {
self.myConstraint.constant = 10
self.myView.layoutIfNeeded()
}
}
http://jsfiddle.net/isherwood/gfgux
html, body {
height: 100%;
}
#table-row, #table-col, #table-wrapper {
height: 80%;
}
<div id="content" class="container">
<div id="table-row" class="row">
<div id="table-col" class="col-md-7 col-xs-10 pull-left">
<p>Hello</p>
<div id="table-wrapper" class="table-responsive">
<table class="table table-bordered ">
Seeing as Guava gets a mention, I thought I would also suggest Eclipse Collections (formerly known as GS Collections).
The following examples all return a List
with a single item.
Lists.mutable.of("Just one item");
Lists.mutable.with("Or use with");
Lists.immutable.of("Maybe it must be immutable?");
Lists.immutable.with("And use with if you want");
There are similar methods for other collections.
I had this problem on Mac OS X. We don't have a /proc
virtual file system, so the accepted solution cannot work.
We do, instead, have a F_GETPATH
command for fcntl
:
F_GETPATH Get the path of the file descriptor Fildes. The argu-
ment must be a buffer of size MAXPATHLEN or greater.
So to get the file associated to a file descriptor, you can use this snippet:
#include <sys/syslimits.h>
#include <fcntl.h>
char filePath[PATH_MAX];
if (fcntl(fd, F_GETPATH, filePath) != -1)
{
// do something with the file path
}
Since I never remember where MAXPATHLEN
is defined, I thought PATH_MAX
from syslimits would be fine.
If you do not need the recording and playback functionality in your app, using off-the-shelf streaming app and player is a reasonable choice.
If you do need them to be in your app, however, you will have to look into MediaRecorder API (for the server/camera app) and MediaPlayer (for client/player app).
Quick sample code for the server:
// this is your network socket
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// this is the unofficially supported MPEG2TS format, suitable for streaming (Android 3.0+)
mMediaRecorder.setOutputFormat(8);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mediaRecorder.setOutputFile(pfd.getFileDescriptor());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();
On the player side it is a bit tricky, you could try this:
// this is your network socket, connected to the server
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pfd.getFileDescriptor());
mMediaPlayer.prepare();
mMediaPlayer.start();
Unfortunately mediaplayer tends to not like this, so you have a couple of options: either (a) save data from socket to file and (after you have a bit of data) play with mediaplayer from file, or (b) make a tiny http proxy that runs locally and can accept mediaplayer's GET request, reply with HTTP headers, and then copy data from the remote server to it. For (a) you would create the mediaplayer with a file path or file url, for (b) give it a http url pointing to your proxy.
See also:
When starting the JVM, two parameters can be adjusted to suit your memory needs :
-Xms<size>
specifies the initial Java heap size and
-Xmx<size>
the maximum Java heap size.
It's just to clear the adapter, add all itens and notify change like below:
public void show(List<Object> objLIst) {
adapter.clear();
adapter.addAll(objLIst);
adapter.notifyDataSetChanged(); }
Google Translate Kit, an open source library http://ggltranslate.codeplex.com/
Translator gt = new Translator();
/*using cache*/
DemoWriter dw = new DemoWriter();
gt.KeyGen = new SimpleKeyGen();
gt.CacheManager = new SimleCacheManager();
gt.Writer = dw;
Translator.TranslatedPost post = gt.GetTranslatedPost("Hello world", LanguageConst.ENGLISH, LanguageConst.CHINESE);
Translator.TranslatedPost post2 = gt.GetTranslatedPost("I'm Jeff", LanguageConst.ENGLISH, LanguageConst.CHINESE);
this.result.InnerHtml = "<p>" + post.text +post2.text+ "</p>";
dw.WriteToFile();
If you are looking to checkout master
branch for each submodule -- you can use the following command for that purpose:
git submodule foreach git checkout master
Improving on Silas Paul's answer
exporting the variables on a subshell makes them local to the command.
(export $(cat .env | xargs) && rails c)
I was getting this same warning everytime I was doing 'maven clean'. I found the solution :
Step - 1 Right click on your project in Eclipse
Step - 2 Click Properties
Step - 3 Select Maven in the left hand side list.
Step - 4 You will notice "pom.xml" in the Active Maven Profiles text box on the right hand side. Clear it and click Apply.
Below is the screen shot :
Hope this helps. :)
I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay-
AppWaterMarkBuilder.doConfigure()
.setAppCompatActivity(MainActivity.this)
.setWatermarkProperty(R.layout.layout_water_mark)
.showWatermarkAfterConfig();
Then you can hide and show it from anywhere in your app -
/* For hiding the watermark*/
AppWaterMarkBuilder.hideWatermark()
/* For showing the watermark*/
AppWaterMarkBuilder.showWatermark()
Gif preview -
I was missing the MSVCR110.dll. Which I corrected. I could run php from the command line but not the web server. Then I clicked on php-cgi.exe and it gave me the answer. The php5.dll was missing (I downloaded the wrong copy). So for my 2012 IIS box I re-installed using php's x86 non thread safe zip.
A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.
You can implement your OTF
font using @font-face like:
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWeb.otf") format("opentype");
}
@font-face {
font-family: GraublauWeb;
font-weight: bold;
src: url("path/GraublauWebBold.otf") format("opentype");
}
// Edit: OTF now works in most browsers, see comments
However if you want to support a wide variety of browsers i would recommend you to switch to WOFF
and TTF
font types. WOFF
type is implemented by every major desktop browser, while the TTF
type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf") format("truetype");
}
If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:
@font-face {
font-family: GraublauWeb;
src: url("webfont.eot"); /* IE9 Compat Modes */
src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
url("webfont.woff") format("woff"), /* Modern Browsers */
url("webfont.ttf") format("truetype"), /* Safari, Android, iOS */
url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}
You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:
hope this helps
Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup)
.
So, for example, I have:
private string DoSomethingToMyString(string input)
{
// blah
}
Instead of explicitly stating the variable to be used like this:
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
}
I can just omit the name of the var:
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
}
Yea, as everyone else wrote, you cannot do multiple inheritance in Java.
If you have two classes from which you'd like to use code, you'd typically just subclass one (say class A
). For class B
, you abstract the important methods of it to an interface BInterface
(ugly name, but you get the idea), then say Main extends A implements BInterface
. Inside, you can instantiate an object of class B
and implement all methods of BInterface
by calling the corresponding functions of B
.
This changes the "is-a" relationship to a "has-a" relationship as your Main
now is an A
, but has a B
. Depending on your use case, you might even make that change explicit by removing the BInterface
from your A
class and instead provide a method to access your B object directly.
find ./ -name "FOLDERNAME" | xargs rm -Rf
Should do the trick. WARNING, if you accidentally pump a .
or /
into xargs rm -Rf
your entire computer will be deleted without an option to get it back, requiring an OS reinstall.
In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me
If you want to have a new data frame then:
import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new= old[['A', 'C', 'D']]
Go to the path in where the gem is and call gem install -l gemname.gem
This is nice but doesn't answer the question:
"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.
Another option which hasn't been mentioned is to use which
:
length(which(z))
Just to actually provide some context on the "which is faster question", it's always easiest just to test yourself. I made the vector much larger for comparison:
z <- sample(c(TRUE,FALSE),1000000,rep=TRUE)
system.time(sum(z))
user system elapsed
0.03 0.00 0.03
system.time(length(z[z==TRUE]))
user system elapsed
0.75 0.07 0.83
system.time(length(which(z)))
user system elapsed
1.34 0.28 1.64
system.time(table(z)["TRUE"])
user system elapsed
10.62 0.52 11.19
So clearly using sum
is the best approach in this case. You may also want to check for NA
values as Marek suggested.
Just to add a note regarding NA values and the which
function:
> which(c(T, F, NA, NULL, T, F))
[1] 1 4
> which(!c(T, F, NA, NULL, T, F))
[1] 2 5
Note that which only checks for logical TRUE
, so it essentially ignores non-logical values.
On Linux Fedora30 several versions of the full java JDK are available, specifically package names:
java-1.8.0-openjdk-devel.x86_64
java-11-openjdk-devel.x86_64
Once installed, they are found in: /usr/lib/jvm
To select the location/directory of a full development JDK (which is different from the simpler runtime only JRE) look for entries:
ls -ld java*openjdk*
Here are two good choices, which are links to specific versions, where you will have to select the version:
/usr/lib/jvm/java-1.8.0-openjdk
/usr/lib/jvm/java-11-openjdk
$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter
If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
<?php
if ($_GET) {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
} else {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
?>
To call from command line chmod 755 /var/www/webroot/index.php
and use
/usr/bin/php /var/www/webroot/index.php arg1 arg2
To call from the browser, use
http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2
See this list of php image libraries. Basically it's GD or Imagemagick.
API Sanity Checker — test framework for C/C++ libraries:
An automatic generator of basic unit tests for a shared C/C++ library. It is able to generate reasonable (in most, but unfortunately not all, cases) input data for parameters and compose simple ("sanity" or "shallow"-quality) test cases for every function in the API through the analysis of declarations in header files.
The quality of generated tests allows to check absence of critical errors in simple use cases. The tool is able to build and execute generated tests and detect crashes (segfaults), aborts, all kinds of emitted signals, non-zero program return code and program hanging.
Unique features in comparison with CppUnit, Boost and Google Test:
Update: 15th May, 2018:
The latest Windows 10 update (re-)activated the World Wide Web Publishing Service (in German: WWW-Publishingdienst). This might depend on the options you select during the configuration of the update you can make afterwards.
Update: 4th August, 2015:
If you have done clean installation of Windows 10, you may not have the Word Wide Web Publishing Service. In that case, simple WAMP/XAMPP installation should work fine.
If it doesn't, try installing Visual C++ Redistributable and then re-install WAMP/XAMPP.
I was facing a similar problem with WAMP. In Windows 10 TP, the Word Wide Web Publishing Service comes pre-installed. This is related to IIS and you can remove it if you don't need it.
This blocks the port 80
, making Apache act weirdly. You can do the following and try again.
This should make port 80 free and restarting WAMP/XAMPP should get you up and running!
There are other ways to do fix this. See Make WAMP Work On Windows 10.
Your two statements are equivalent.
Most people only use LEFT JOIN
since it seems more intuitive, and it's universal syntax - I don't think all RDBMS support RIGHT JOIN
.
This could also be the case if you have created a systemd
service that has:
[Service]
Restart=always
ExecStart=/usr/bin/docker container start -a my_container
ExecStop=/usr/bin/docker container stop -t 2 my_container
You can use display:inline-block
instead of float
and vertical-align:middle
with this CSS:
.col-lg-4, .col-lg-8 {
float:none;
display:inline-block;
vertical-align:middle;
margin-right:-4px;
}
The demo http://bootply.com/94402
Use this to display the Unix numerical permission values (octal values) and file name.
stat -c '%a %n' *
Use this to display the Unix numerical permission values (octal values) and the folder's sgid and sticky bit, user name of the owner, group name, total size in bytes and file name.
stat -c '%a %A %U %G %s %n' *
Add %y
if you need time of last modification in human-readable format. For more options see stat.
Better version using an Alias
Using an alias is a more efficient way to accomplish what you need and it also includes color. The following displays your results organized by group directories first, display in color, print sizes in human readable format (e.g., 1K 234M 2G) edit your ~/.bashrc
and add an alias for your account or globally by editing /etc/profile.d/custom.sh
Typing cls
displays your new LS command results.
alias cls="ls -lha --color=always -F --group-directories-first |awk '{k=0;s=0;for(i=0;i<=8;i++){;k+=((substr(\$1,i+2,1)~/[rwxst]/)*2^(8-i));};j=4;for(i=4;i<=10;i+=3){;s+=((substr(\$1,i,1)~/[stST]/)*j);j/=2;};if(k){;printf(\"%0o%0o \",s,k);};print;}'"
Folder Tree
While you are editing your bashrc or custom.sh include the following alias to see a graphical representation where typing lstree
will display your current folder tree structure
alias lstree="ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'"
It would display:
|-scripts
|--mod_cache_disk
|--mod_cache_d
|---logs
|-run_win
|-scripts.tar.gz
Add double quotes to use caret operator in version number.
composer require middlewares/whoops "^0.4"
The MySQL documentation you cite actually says a little bit more than you mention. It also says,
A “
'
” inside a string quoted with “'
” may be written as “''
”.
(Also, you linked to the MySQL 5.0 version of Table 8.1. Special Character Escape Sequences, and the current version is 5.6 — but the current Table 8.1. Special Character Escape Sequences looks pretty similar.)
I think the Postgres note on the backslash_quote (string)
parameter is informative:
This controls whether a quote mark can be represented by
\'
in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it (''
) but PostgreSQL has historically also accepted\'
. However, use of\'
creates security risks...
That says to me that using a doubled single-quote character is a better overall and long-term choice than using a backslash to escape the single-quote.
Now if you also want to add choice of language, choice of SQL database and its non-standard quirks, and choice of query framework to the equation, then you might end up with a different choice. You don't give much information about your constraints.
Try "difftool" (assuming you have diff tools setup) - see https://www.kernel.org/pub/software/scm/git/docs/git-difftool.html
I find name status good for the summary but difftool will iterate the changes (and the -d
option gives you the directory view), e.g.
$ git difftool their-branch my-branch
Viewing: 'file1.txt'
Launch 'bc3' [Y/n]:
...
Or as @rsilva4 mentioned with -d
and default to your current branch it is just - e.g. compare to master:
$ git difftool -d master..
...and yes - there are many variations - https://www.kernel.org/pub/software/scm/git/docs/git-reset.html
This may work as well.
SELECT *
FROM myTable
WHERE CHARINDEX('mall', name) > 0
OR CHARINDEX('mall', description) > 0
I had the same problem, here's how I solved it. Following the first section of this very excellent Django tutorial, I did the following:
python manage.py startapp new_app
settings.py
file, adding the following to the list of INSTALLED_APPS
: 'new_app',
new_app
package named new_app_tags
.{% extends 'base_template_name.html' %}
: {% load new_app_tags %}
new_app_tags
module file, create a custom template tag (see below).{% multiply_by_two | "5.0" %}
Example from step 5 above:
from django import template
register = template.Library()
@register.simple_tag
def multiply_by_two(value):
return float(value) * 2.0
It works fine for me using a CSS grid. Initially fix the container and then give overflow-y: auto;
for the centre content which has to get scrolled i.e other than header and footer.
.container{
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
display: grid;
grid-template-rows: 5em auto 3em;
}
header{
grid-row: 1;
background-color: rgb(148, 142, 142);
justify-self: center;
align-self: center;
width: 100%;
}
.body{
grid-row: 2;
overflow-y: auto;
}
footer{
grid-row: 3;
background: rgb(110, 112, 112);
}
_x000D_
<div class="container">
<header><h1>Header</h1></header>
<div class="body">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<footer><h3>Footer</h3></footer>
</div>
_x000D_
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
This code below works for me. I always use only single quotes, and it works fine. I suggest you should use only single quotes or only double quotes, but not mixed up.
$.ajax({
url: 'YourRestEndPoint',
headers: {
'Authorization':'Basic xxxxxxxxxxxxx',
'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
'Content-Type':'application/json'
},
method: 'POST',
dataType: 'json',
data: YourData,
success: function(data){
console.log('succes: '+data);
}
});
Yeah, use .match
, rather than .search
. The result from the .match
call will return the actual string that was matched itself, but it can still be used as a boolean value.
var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';
if (result){
alert('Matched');
}
Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it is a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using indexOf
like this:
matchString = 'best';
// If the match string is coming from user input you could do
// matchString = userInput.toLowerCase() here.
if (string.toLowerCase().indexOf(matchString) != -1){
alert('Matched');
}
Table Creating
create table emp(eno int identity(100001,1),ename varchar(50))
Values inserting
insert into emp(ename)values('narendra'),('ajay'),('anil'),('raju')
Select Table
select * from emp
Output
eno ename
100001 narendra
100002 rama
100003 ajay
100004 anil
100005 raju
// Old version (for history)
let keys = dictionary.keys.map { $0 }
let keys = dictionary?.keys.map { $0 } ?? [T]()
// New more explained version for our ducks
extension Dictionary {
var allKeys: [Dictionary.Key] {
return self.keys.map { $0 }
}
}
If that <p>
tag is created from JavaScript, then you do have another option: use JSS to programmatically insert stylesheets into the document head. It does support '&:hover'
. https://cssinjs.org/
assert_has_calls
is another approach to this problem.
From the docs:
assert_has_calls (calls, any_order=False)
assert the mock has been called with the specified calls. The mock_calls list is checked for the calls.
If any_order is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls.
If any_order is True then the calls can be in any order, but they must all appear in mock_calls.
Example:
>>> from unittest.mock import call, Mock
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)
Source: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_has_calls
Based on DaveK's answer, I created a control extension:
public static void SetToolTip(this Control control, string txt)
{
new ToolTip().SetToolTip(control, txt);
}
Then you can set the tooltip for any control with a single line:
this.MyButton.SetToolTip("Hello world");
On Fedora 32, I managed to solve this same issue by installing lipq5-devel
specifically.
If you install postgresql from the official repository, you will have several versions that won't fix the problem, so it's really a matter of trying out which one it needs.
It will shift the bits by padding that many 0's
.
For ex,
10
which is digit 2
left shift by 2 is 1000
which is digit 8
10
which is digit 2
left shift by 3 is 10000
which is digit 16
I found this answer to the question:
http://padcom13.blogspot.co.uk/2011/10/creating-standalone-applications-with.html
Not only do you get the dependent lib files in a lib folder, you also get a bin director with both a unix and a dos executable.
The executable ultimately calls java with a -cp argument that lists all of your dependent libs too.
The whole lot sits in an appasembly folder inside the target folder. Epic.
============= Yes I know this is an old thread, but it's still coming high on search results so I thought it might help someone like me.
Free read-only viewers:
tail
." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.Free editors:
Builtin programs (no installation required):
MORE
, not the Unix more
. A console program that allows you to view a file, one screen at a time.Web viewers:
Paid editors:
NSURL *url = [NSURL URLWithString:[exreciesDescription objectForKey:@"exercise_url"]];
moviePlayer =[[MPMoviePlayerController alloc] initWithContentURL: url];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doneButtonClicked) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
[[moviePlayer view] setFrame: [self.view bounds]]; // frame must match parent view
[self.view addSubview: [moviePlayer view]];
[moviePlayer play];
-(void)playMediaFinished:(NSNotification*)theNotification
{
moviePlayer=[theNotification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayer];
[moviePlayer.view removeFromSuperview];
}
-(void)doneButtonClicked
{
[moviePlayer stop];
[moviePlayer.view removeFromSuperview];
[self.navigationController popViewControllerAnimated:YES];//no need this if you are opening the player in same screen;
}
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
Android Studio automatically creates a Gradle wrapper in the root of your project, which is how it invokes Gradle. The wrapper is basically a script that calls through to the actual Gradle binary and allows you to keep Gradle up to date, which makes using version control easier. To run a Gradle command, you can simply use the gradlew
script found in the root of your project (or gradlew.bat
on Windows) followed by the name of the task you want to run. For instance, to build a debug version of your Android application, you can run ./gradlew assembleDebug
from the root of your repository. In a default project setup, the resulting apk can then be found in app/build/outputs/apk/app-debug.apk
. On a *nix machine, you can also just run find . -name '*.apk'
to find it, if it's not there.
you can right click on the project select "set configuration" then "Customize", from there you can choose your main class.
For reading/writing excel files, you can use :
readxl
package for reading and writexl
package for writingopenxlsx
package for reading and writingWith xlsx
and XLConnect
(which use rjava) you will face memory errors if you have large files
Windows 10 (and Powershell 5.0 in general) allows you to create symbolic links via the New-Item cmdlet.
Usage:
New-Item -Path C:\LinkDir -ItemType SymbolicLink -Value F:\RealDir
Or in your profile:
function make-link ($target, $link) {
New-Item -Path $link -ItemType SymbolicLink -Value $target
}
Turn on Developer Mode to not require admin privileges when making links with New-Item
:
canvas.toDataURL
is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
Besides the settings for bash/ zsh terminal which are well covered by the other answers, if you want a permanent system environment variable for terminal + GUI applications (works for macOS Sierra; should work for El Capitan too):
launchctl setenv JAVA_HOME $(/usr/libexec/java_home -v 1.8)
(this will set JAVA_HOME to the latest 1.8 JDK, chances are you have gone through serveral updates e.g. javac 1.8.0_101, javac 1.8.0_131)
Of course, change 1.8 to 1.7 or 1.6 (really?) to suit your need and your system
max(ozone$Ozone, na.rm = TRUE)
should do the trick. Remember to include the na.rm = TRUE
or else R will return NA.
Just use "Wait-process" :
"notepad","calc","wmplayer" | ForEach-Object {Start-Process $_} | Wait-Process ;dir
job is done
If you are looking inside dockerfile while creating image, add this line:
RUN apk add --update yourPackageName
Python is strongly, dynamically typed.
As for your example
bob = 1
bob = "bob"
This works because the variable does not have a type; it can name any object. After bob=1
, you'll find that type(bob)
returns int
, but after bob="bob"
, it returns str
. (Note that type
is a regular function, so it evaluates its argument, then returns the type of the value.)
Contrast this with older dialects of C, which were weakly, statically typed, so that pointers and integers were pretty much interchangeable. (Modern ISO C requires conversions in many cases, but my compiler is still lenient about this by default.)
I must add that the strong vs. weak typing is more of a continuum than a boolean choice. C++ has stronger typing than C (more conversions required), but the type system can be subverted by using pointer casts.
The strength of the type system in a dynamic language such as Python is really determined by how its primitives and library functions respond to different types. E.g., +
is overloaded so that it works on two numbers or two strings, but not a string and an number. This is a design choice made when +
was implemented, but not really a necessity following from the language's semantics. In fact, when you overload +
on a custom type, you can make it implicitly convert anything to a number:
def to_number(x):
"""Try to convert function argument to float-type object."""
try:
return float(x)
except (TypeError, ValueError):
return 0
class Foo:
def __init__(self, number):
self.number = number
def __add__(self, other):
return self.number + to_number(other)
Instance of class Foo
can be added to other objects:
>>> a = Foo(42)
>>> a + "1"
43.0
>>> a + Foo
42
>>> a + 1
43.0
>>> a + None
42
Observe that even though strongly typed Python is completely fine with adding objects of type int
and float
and returns an object of type float
(e.g., int(42) + float(1)
returns 43.0
). On the other hand, due to the mismatch between types Haskell would complain if one tries the following (42 :: Integer) + (1 :: Float)
. This makes Haskell a strictly typed language, where types are entirely disjoint and only a controlled form of overloading is possible via type classes.
first up on create your jsp file :
and write the text field which you want
for ex:
after that create your servlet class:
public class test{
protected void doGet(paramter , paramter){
String name = request.getparameter("name");
}
}
try it it is working fine
<%:Html.ActionLink("Details","Details","Product", new {id=item.dateID },null)%>
Just set this extra line in catalina.bat
file
LINE NO AROUND: 143
set "CATALINA_OPTS=-Xms512m -Xmx512m"
And restart Tomcat service
You can disable them in your browser.
Type about:config
in the Firefox address bar and find security.csp.enable
and set it to false
.
You can install the extension called Disable Content-Security-Policy
to disable CSP.
You need to upload the image aswell, then link to the image on the server.
I like Fixedsys in Visual Studio. It's a classic. No anti-aliasing blur.
Apache Commons IO Charsets class can come in handy:
String utf8String = new String(org.apache.commons.io.Charsets.ISO_8859_1.encode(latinString).array())
Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""
You can do one of two things:
^\s*$
; a match means the string is "empty"
^
, $
are the beginning and end of string anchors respectively\s
is a whitespace character*
is zero-or-more repetition of\S
; an occurrence means the string is NOT "empty"
\S
is the negated version of \s
(note the case difference)\S
therefore matches any non-whitespace characterRegexOptions.ECMAScript
, \s
matches things like ellipsis …
So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.
/^[a-z0-9]+$/i
Here's a chart that may be helpful deciding which to use: http://blog.sematext.com/2011/09/19/top-javascript-dynamic-table-libraries/
Not only does it not get executed, it doesn't even get compiled.
#if
is a preprocessor command, which gets evaluated before the actual compilation step. The code inside that block doesn't appear in the compiled binary.
It's often used for temporarily removing segments of code with the intention of turning them back on later.
I have already replied to this question in an answer to Stack Overflow question Trouble using Google sign-in button in emulator. It only works for Android 4.2.2, but lets you use the "Intel Atom (x86)" in AVD.
I think that it is easy to make it work for other versions of Android. Just find the correct files.
try this
$('html').click(function() {
//your stuf
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
you can also use the outside events
after release of android studio v 3.0(stable), It will show popup, If gradle update is available
OR
Manually, just change version of gradle in top-level(project-level) build.gradle
file to latest,
buildscript {
...
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
}
}
check below chart
The Android Gradle Plugin and Gradle Android Gradle Plugin Requires Gradle 1.0.0 - 1.1.3 2.2.1 - 2.3 1.2.0 - 1.3.1 2.2.1 - 2.9 1.5.0 2.2.1+ 2.2.1 - 2.13 2.0.0 - 2.1.2 2.10 - 2.13 2.1.3 - 2.2.3 2.14.1+ 2.3.0+ 3.3+ 3.0.0+ 4.1+ 3.1.0+ 4.4+ 3.2.0 - 3.2.1 4.6+ 3.3.0 - 3.3.1 4.10.1+ 3.4.0 - 3.4.1 5.1.1+ 3.5.0 5.4.1+
check gradle revisions
as mentioned above: its not possible to call a css pseudo-class / -element inline.
what i now did, is:
give your element a unique identifier, f.ex. an id or a unique class.
and write a fitting <style>
element
<style>#id29:before { content: "*";}</style>
<article id="id29">
<!-- something -->
</article>
fugly, but what inline css isnt..?
I got the "No signing certificate" error when running Xcode 11.3 on macOS 10.14.x Mojave. (but after Xcode 12 was released.)
I was also using Fastlane. My fix was to set generate_apple_certs
to false
when running Match. This seemed to generate signing certificates that were backwards-compatible with Xcode 11.3
Match documentation - https://docs.fastlane.tools/actions/match/
This is the relevant section of my Fastfile:
platform :ios do
lane :certs do
force = false
match(type: "development", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.dev")
match(type: "adhoc", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.beta")
match(type: "appstore", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier")
end
...
The Request Payload - or to be more precise: payload body of a HTTP Request
- is the data normally send by a POST or PUT Request.
It's the part after the headers and the CRLF
of a HTTP Request.
A request with Content-Type: application/json
may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.
If you submit a HTML-Form with method="POST"
and Content-Type: application/x-www-form-urlencoded
or Content-Type: multipart/form-data
your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.
So, they differ in the Content-Type
but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.
I was recently tasked to "prototype up some loggin'" for an upcoming project. I didn't have any logging framework experience. I researched, ran through tutorials, made toy apps, etc. on Log4Net, NLog, and Enterprise Library for a few days. Came back 3-4 weeks later and put them together into a cohesive demo. Hopefully some of this is useful to you.
My recommendation for our project is this:
That's based on these findings (opinions!):
So obviously I like NLog so far. Not enough to use it in spite of having another solution available, though.
I see in your Update 2 that you have use sAutoWidth
, but I think you mistyped bAutoWidth
. Try to change this.
You can also add a CSS rule to .table
if the problem persists.
You should also be careful when the width of the content is greater than the header of the column.
So something like the combination of the 1 & 2:
$('.table').dataTable({
bAutoWidth: false,
aoColumns : [
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '10%' }
]
});
I notice that you mention a function %like%
in your current approach. I don't know if that's a reference to the %like%
from "data.table", but if it is, you can definitely use it as follows.
Note that the object does not have to be a data.table
(but also remember that subsetting approaches for data.frame
s and data.table
s are not identical):
library(data.table)
mtcars[rownames(mtcars) %like% "Merc", ]
iris[iris$Species %like% "osa", ]
If that is what you had, then perhaps you had just mixed up row and column positions for subsetting data.
If you don't want to load a package, you can try using grep()
to search for the string you're matching. Here's an example with the mtcars
dataset, where we are matching all rows where the row names includes "Merc":
mtcars[grep("Merc", rownames(mtcars)), ]
mpg cyl disp hp drat wt qsec vs am gear carb
# Merc 240D 24.4 4 146.7 62 3.69 3.19 20.0 1 0 4 2
# Merc 230 22.8 4 140.8 95 3.92 3.15 22.9 1 0 4 2
# Merc 280 19.2 6 167.6 123 3.92 3.44 18.3 1 0 4 4
# Merc 280C 17.8 6 167.6 123 3.92 3.44 18.9 1 0 4 4
# Merc 450SE 16.4 8 275.8 180 3.07 4.07 17.4 0 0 3 3
# Merc 450SL 17.3 8 275.8 180 3.07 3.73 17.6 0 0 3 3
# Merc 450SLC 15.2 8 275.8 180 3.07 3.78 18.0 0 0 3 3
And, another example, using the iris
dataset searching for the string osa
:
irisSubset <- iris[grep("osa", iris$Species), ]
head(irisSubset)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
For your problem try:
selectedRows <- conservedData[grep("hsa-", conservedData$miRNA), ]
According to the documentation. You can use:
$locationProvider.html5Mode(true).hashPrefix('!');
NB: If your browser does not support to HTML 5. Dont worry :D it have fallback to hashbang mode. So, you don't need to check with
if(window.history && window.history.pushState){ ... }
manually
For example: If you click: <a href="/other">Some URL</a>
In HTML5 Browser:
angular will automatically redirect to example.com/other
In Not HTML5 Browser:
angular will automatically redirect to example.com/#!/other
It seems there must be at least one local commit on the master branch to do:
git push -u origin master
So if you did git init .
and then git remote add origin ...
, you still need to do:
git add ...
git commit -m "..."
Git is very flexible. You shouldn't need hundreds of branches to do what you are asking. If you want to revert the state all the way back to the 2nd change (and it is indeed a change that was already committed and pushed), use git revert
. Something like:
git revert a4r9593432
where a4r9593432 is the starting characters of the hash of the commit you want to back out.
If the commit contains changes to many files, but you just want to revert just one of the files, you can use git reset
(the 2nd or 3rd form):
git reset a4r9593432 -- path/to/file.txt
# the reverted state is added to the staging area, ready for commit
git diff --cached path/to/file.txt # view the changes
git commit
git checkout HEAD path/to/file.txt # make the working tree match HEAD
But this is pretty complex, and git reset is dangerous. Use git checkout <hash> <file path>
instead, as Jefromi suggests.
If you just want to view what the file looked like in commit x, you can use git show
:
git show a4r9593432:path/to/file.txt
For all of the commands, there are many ways to refer to a commit other than via the commit hash (see Naming Commits in the Git User Manual).
lsof and fuser didn't give me anything either.
After a process of renaming all possible directories to .old and rebooting the system every time after I made changes I found one particular directory (relating to postfix) that was responsible.
It turned out that I had once made a symlink from /var/spool/postfix to /disk2/pers/mail/postfix/varspool in order to minimise disk writes on an SDCARD-based root filesystem (Sheeva Plug).
With this symlink, even after stopping the postfix and dovecot services (both ps aux as well as netstat -tuanp didn't show anything related) I was not able to unmount /disk2/pers.
When I removed the symlink and updated the postfix and dovecot config files to point directly to the new dirs on /disk2/pers/ I was able to successfully stop the services and unmount the directory.
Next time I will look more closely at the output of:
ls -lR /var | grep ^l | grep disk2
The above command will recursively list all symbolic links in a directory tree (here starting at /var) and filter out those names that point to a specific target mount point (here disk2).
I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).
Also in Logic Friday the expression A | B
just returns 3 entries in truth table; I expected 4.
As most of us use Eclipse already for writing code, Why not use the Memory Analyser Tool(MAT) in Eclipse. It works great.
The Eclipse MAT is a set of plug-ins for the Eclipse IDE which provides tools to analyze heap dumps
from Java application and to identify memory problems
in the application.
This helps the developer to find memory leaks with the following features
Have a look at the following apache commons function:
org.apache.commons.io.FileUtils.readFileToByteArray(File)
Nowadays, Alpine images will boot directly into /bin/sh
by default, without having to specify a shell to execute:
$ sudo docker run -it --rm alpine
/ # echo $0
/bin/sh
This is since the alpine
image Dockerfiles now contain a CMD
command, that specifies the shell to execute when the container starts: CMD ["/bin/sh"]
.
In older Alpine image versions (pre-2017), the CMD command was not used, since Docker used to create an additional layer for CMD which caused the image size to increase. This is something that the Alpine image developers wanted to avoid. In recent Docker versions (1.10+), CMD no longer occupies a layer, and so it was added to alpine
images. Therefore, as long as CMD is not overridden, recent Alpine images will boot into /bin/sh
.
For reference, see the following commit to the official Alpine Dockerfiles by Glider Labs:
https://github.com/gliderlabs/docker-alpine/commit/ddc19dd95ceb3584ced58be0b8d7e9169d04c7a3#diff-db3dfdee92c17cf53a96578d4900cb5b
The Instant
class doesn't contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC.
So, formatter can't print a date because date always printed for concrete time zone.
You should set time zone to formatter and all will be fine, like this :
Instant instant = Instant.ofEpochMilli(92554380000L);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);
assert formatter.format(instant).equals("07/12/72 05:33");
assert instant.toString().equals("1972-12-07T05:33:00Z");
Here is another one liner:
[[ -d /tmp/test ]] && rm -r /tmp/test
Here's how to do it with list comprehension:
a = (1, 2, 3)
b = (4, 5, 6)
[print('f:', i, '; b', j) for i, j in zip(a, b)]
prints:
f: 1 ; b 4
f: 2 ; b 5
f: 3 ; b 6
...and for your right click notification menu add a context menu to the form and edit it and set mouseclick events for each of contextmenuitems by double clicking them and then attach it to the notifyicon1 by selecting the ContextMenuStrip in notifyicon property.
If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:
# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master
I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.
If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours
merge strategy:
# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master
In my case, it started hapenning after I updated to Android Studio 1.2. To fix it I just had to remove "\bin" from my JAVA_HOME variable.
I think inline scripts are hard to stop instead you can try with this:
<div id="test">
<div>Click Me</div>
</div>
and script:
$(function () {
$('#test').children().click(function(){
alert('hello');
});
$('#test').children().off('click');
});
You need to destroy old data-table instance and then re-initialize data-table
First Check if data-table instance exist by using $.fn.dataTable.isDataTable
if exist then destroy it and then create new instance like this
if ($.fn.dataTable.isDataTable('#dataTableExample')) {
$('#dataTableExample').DataTable().destroy();
}
$('#dataTableExample').DataTable({
responsive: true,
destroy: true
});
ps -ef | grep 'myProcessName' | grep -v grep | awk '{print $2}' | xargs -r kill -9
What's this code doing?
The ps -ef
produces a list of process id's on the computer visible to this user. The pipe grep filters that down for rows containing that string. The grep -v grep
says don't match on the process itself doing the grepping. The pipe awk print says split the rows on default delimiter whitespace and filter to the second column which is our process id. The pipe xargs spins up a new process to send all those pid's to kill -9
, ending them all.
The above code is bad, dangerous, ugly and hackish for several reasons.
If the code being force-ended is doing any database ops or secure transactions with low probability race conditions, some fraction of a percent of the time, atomicity of that transaction will be wrecked, producing undefined behavior. kill -9 takes no prisoners. If your code is sensitive to this, try replacing the xargs kill
part with a transmitted flag that requests a graceful shutdown, and only if that request is denied, last-resort to kill -9
There's a non zero possibility that you will accidentally end the operating system or caused undefined behavior in an unrelated process, leading to whole system instability because ps -ef
lists every possible process that could exist, and you can't be sure some weird 3rd party library shares your process name, or that in the time between read and execute kill -9, the processid had changed to something else, and now you've accidentally ended some random process you didn't intend to.
But, if you understand the risks and control for them with very unique names, and you're ok with a few dropped transactions or occasional corruption in data, then 99.9% of the time yer gonna be fine. If there's a problem, reboot the computer, make sure there aren't any process collisions. It's because of code like this that makes the tech support script: "Have you tried restarting your computer" a level 5 meme.
It really all depends on exactly WHAT you need the random generation for, but here's my take.
First, create a standalone method for generating the random number. Be sure to allow for limits.
public static int newRandom(int limit){
return generatedRandom.nextInt(limit); }
Next, you will want to create a very simple decision structure that compares values. This can be done in one of two ways. If you have a very limited amount of numbers to verify, a simple IF statement will suffice:
public static int testDuplicates(int int1, int int2, int int3, int int4, int int5){
boolean loopFlag = true;
while(loopFlag == true){
if(int1 == int2 || int1 == int3 || int1 == int4 || int1 == int5 || int1 == 0){
int1 = newRandom(75);
loopFlag = true; }
else{
loopFlag = false; }}
return int1; }
The above compares int1 to int2 through int5, as well as making sure that there are no zeroes in the randoms.
With these two methods in place, we can do the following:
num1 = newRandom(limit1);
num2 = newRandom(limit1);
num3 = newRandom(limit1);
num4 = newRandom(limit1);
num5 = newRandom(limit1);
Followed By:
num1 = testDuplicates(num1, num2, num3, num4, num5);
num2 = testDuplicates(num2, num1, num3, num4, num5);
num3 = testDuplicates(num3, num1, num2, num4, num5);
num4 = testDuplicates(num4, num1, num2, num3, num5);
num5 = testDuplicates(num5, num1, num2, num3, num5);
If you have a longer list to verify, then a more complex method will yield better results both in clarity of code and in processing resources.
Hope this helps. This site has helped me so much, I felt obliged to at least TRY to help as well.
Assets provide a way to include arbitrary files like text, xml, fonts, music, and video in your application. If you try to include these files as "resources", Android will process them into its resource system and you will not be able to get the raw data. If you want to access data untouched, Assets are one way to do it.
Remove the content of the folder \.m2\repository\org\apache\maven\plugins\maven-resource-plugin\2.7
. The cached info turned out to be the issue.
Using a $where
query will be slow, in part because it can't use indexes. For this sort of problem, I think it would be better to store a high value for the "expires" field that will naturally always be greater than Now(). You can either store a very high date millions of years in the future, or use a separate type to indicate never. The cross-type sort order is defined at here.
An empty Regex or MaxKey (if you language supports it) are both good choices.
File -> Export -> Web -> WAR file
OR in Kepler follow as shown below :
The functions need to be defined before being used. There is no mechanism is sh to pre-declare functions, but a common technique is to do something like:
main() { case "$choice" in true) process_install;; false) process_exit;; esac } process_install() { commands... commands... } process_exit() { commands... commands... } main()
Use the imp module, or the more direct __import__()
function.
There are 3 parts to using Font-Awesome in Angular Projects
Installation
Install from NPM and save to your package.json
npm install --save font-awesome
Styling If using CSS
Insert into your style.css
@import '~font-awesome/css/font-awesome.css';
Styling If using SCSS
Insert into your style.scss
$fa-font-path: "../node_modules/font-awesome/fonts";
@import '~font-awesome/scss/font-awesome.scss';
Usage with plain Angular 2.4+ 4+
<i class="fa fa-area-chart"></i>
Usage with Angular Material
In your app.module.ts modify the constructor to use the MdIconRegistry
export class AppModule {
constructor(matIconRegistry: MatIconRegistry) {
matIconRegistry.registerFontClassAlias('fontawesome', 'fa');
}
}
and add MatIconModule
to your @NgModule
imports
@NgModule({
imports: [
MatIconModule,
....
],
declarations: ....
}
Now in any template file you can now do
<mat-icon fontSet="fontawesome" fontIcon="fa-area-chart"></mat-icon>
Similar to Stone's answer, but for Windows/.NET developers:
If you have Visual Studio and ReSharper - An easy alternative for formatting Javascript is:
My suggestion for dynamic JQuery Grid are below.
http://reconstrukt.com/ingrid/
https://github.com/mleibman/SlickGrid
http://www.datatables.net/index
Best one is :
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.
Variable length pagination
On-the-fly filtering
Multi-column sorting with data type detection
Smart handling of column widths
Display data from almost any data source
DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)
Scrolling options for table viewport
Fully internationalisable
jQuery UI ThemeRoller support
Rock solid - backed by a suite of 2600+ unit tests
Wide variety of plug-ins inc. TableTools, FixedColumns, KeyTable and more
Dynamic creation of tables
Ajax auto loading of data
Custom DOM positioning
Single column filtering
Alternative pagination types
Non-destructive DOM interaction
Sorting column(s) highlighting
Advanced data source options
Extensive plug-in support
Sorting, type detection, API functions, pagination and filtering
Fully themeable by CSS
Solid documentation
110+ pre-built examples
Full support for Adobe AIR
Depends on your needs there is an addition to accepted answer. You may also implement it like this:
var parseCompletion: (() ->Void)!
and later in some func assign to it
func someHavyFunc(completion: @escaping () -> Void){
self.parseCompletion = completion
}
and in some second function use it
func someSecondFunc(){
if let completion = self.parseCompletion {
completion()
}
}
note that @escaping
parameter is a mandatory here
this is to make display:inline-block work in all browsers:
Quirkly enough, in IE (6/7) , if you trigger hasLayout with "zoom:1" and then set the display to inline, it behaves as an inline block.
.inline-block {
display: inline-block;
zoom: 1;
*display: inline;
}
How element visibility and jQuery works;
An element could be hidden with display:none
, visibility:hidden
or opacity:0
. The difference between those methods:
display:none
hides the element, and it does not take up any space;visibility:hidden
hides the element, but it still takes up space in the layout;opacity:0
hides the element as "visibility:hidden", and it still takes up space in the layout; the only difference is that opacity lets one to make an element partly transparent;
if ($('.target').is(':hidden')) {
$('.target').show();
} else {
$('.target').hide();
}
if ($('.target').is(':visible')) {
$('.target').hide();
} else {
$('.target').show();
}
if ($('.target-visibility').css('visibility') == 'hidden') {
$('.target-visibility').css({
visibility: "visible",
display: ""
});
} else {
$('.target-visibility').css({
visibility: "hidden",
display: ""
});
}
if ($('.target-visibility').css('opacity') == "0") {
$('.target-visibility').css({
opacity: "1",
display: ""
});
} else {
$('.target-visibility').css({
opacity: "0",
display: ""
});
}
Useful jQuery toggle methods:
$('.click').click(function() {
$('.target').toggle();
});
$('.click').click(function() {
$('.target').slideToggle();
});
$('.click').click(function() {
$('.target').fadeToggle();
});
Perfect! Thank you Jay, below is my HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="../css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="../css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="../css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<link href="../css/highlight.css" rel="stylesheet" type="text/css" media="screen" />
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
$.getJSON("readJSON.php",function(data){
$.each(data.post, function(i,post){
content += '<p>' + post.post_author + '</p>';
content += '<p>' + post.post_content + '</p>';
content += '<p' + post.date + '</p>';
content += '<br/>';
$(content).appendTo("#posts");
});
});
});
/* ]]> */
</script>
</head>
<body>
<div class="container">
<div class="span-24">
<h2>Check out the following posts:</h2>
<div id="posts">
</di>
</div>
</div>
</body>
</html>
And my JSON outputs:
{ posts: [{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"This is a post","author":"Ryan Coughlin"}]}
I get this error, when I run my code:
object is undefined
http://localhost:8888/rks/post/js/jquery.js
Line 19
You can useflatten()
from the numpy package.
import numpy as np
a = np.array([[1, 2],
[3, 4],
[5, 6]])
a_flat = a.flatten()
print(f"original array: {a} \nflattened array = {a_flat}")
Output:
original array: [[1 2]
[3 4]
[5 6]]
flattened array = [1 2 3 4 5 6]
Might just be for Visual Studio '15, if you right-click on source code, there's an option for insert comment
This puts summary
tags around your comment section, but it does give the indentation that you want.
You need to intent
your current context
to another activity first with startActivity
. After that you can finish
your current activity
from where you redirect.
Intent intent = new Intent(this, FirstActivity.class);// New activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); // Call once you redirect to another activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
- Clears the activity stack. If you don't want to clear the activity stack. PLease don't use that flag then.
default-username = root
password = you-know-it-better
url for localhost = jdbc:mysql://localhost
default-port = 3306
lodash will work, tested even for angular 5, http://jsfiddle.net/L5qrfx3x/
var remoteJSON = {"allowExternalMembers": "false", "whoCanJoin":
"CAN_REQUEST_TO_JOIN"};
var localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN",
"allowExternalMembers": "false"};
if(_.isEqual(remoteJSON, localJSON)){
//TODO
}
it works, for installation in angular, follow this
Comment out a range of lines:
First set a bookmark at the beginning of range:
ma
Go the the last line in range
The command is:
:'a,.s/^/# /
Assuming #
is your comment character.
<h1 style="text-align: left; float: left;">Text 1</h1>
<h2 style="text-align: right; float: right; display: inline;">Text 2</h2>
<hr style="clear: both;" />
Hope this helps!
In my case working with python 2.7 with numpy version 1.15.0, it worked with
pip install statsmodels=="0.10.0"
fill in the "X display location" did not work for me. but install MobaXterm did the job.
WARNING: This deletes all commits on the email branch. It's like deleting the email branch and creating it anew at the head of the staging branch.
The easiest way to do it:
//the branch you want to overwrite
git checkout email
//reset to the new branch
git reset --hard origin/staging
// push to remote
git push -f
Now the email branch and the staging are the same.
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
So you can use:
myvar = getURLParameter('myvar');
You might also consider adding the exception type you want to retry for. For instance is this a timeout exception you want to retry? A database exception?
RetryForExcpetionType(DoSomething, typeof(TimeoutException), 5, 1000);
public static void RetryForExcpetionType(Action action, Type retryOnExceptionType, int numRetries, int retryTimeout)
{
if (action == null)
throw new ArgumentNullException("action");
if (retryOnExceptionType == null)
throw new ArgumentNullException("retryOnExceptionType");
while (true)
{
try
{
action();
return;
}
catch(Exception e)
{
if (--numRetries <= 0 || !retryOnExceptionType.IsAssignableFrom(e.GetType()))
throw;
if (retryTimeout > 0)
System.Threading.Thread.Sleep(retryTimeout);
}
}
}
You might also note that all of the other examples have a similar issue with testing for retries == 0 and either retry infinity or fail to raise exceptions when given a negative value. Also Sleep(-1000) will fail in the catch blocks above. Depends on how 'silly' you expect people to be but defensive programming never hurts.
I believe that what you want is
int[] k = new int[3];
if (k != null) { // Note, != and not == as above
System.out.println(k.length);
}
You newed it up so it was never going to be null.
@GET
does support List of Strings
Setup:
Java : 1.7
Jersey version : 1.9
Resource
@Path("/v1/test")
Subresource:
// receive List of Strings
@GET
@Path("/receiveListOfStrings")
public Response receiveListOfStrings(@QueryParam("list") final List<String> list){
log.info("receieved list of size="+list.size());
return Response.ok().build();
}
Jersey testcase
@Test
public void testReceiveListOfStrings() throws Exception {
WebResource webResource = resource();
ClientResponse responseMsg = webResource.path("/v1/test/receiveListOfStrings")
.queryParam("list", "one")
.queryParam("list", "two")
.queryParam("list", "three")
.get(ClientResponse.class);
Assert.assertEquals(200, responseMsg.getStatus());
}
h = ['a','b','c','d','e','f']
g = ''
for f in h:
g = g + f
>>> g
'abcdef'
I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.
Same solutions as Python urllib2 Basic Auth Problem apply.
see https://stackoverflow.com/a/24048852/1733117; you can subclass urllib2.HTTPBasicAuthHandler
to add the Authorization
header to each request that matches the known url.
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
'''Preemptive basic auth.
Instead of waiting for a 403 to then retry with the credentials,
send the credentials if the url is handled by the password manager.
Note: please use realm=None when calling add_password.'''
def http_request(self, req):
url = req.get_full_url()
realm = None
# this is very similar to the code from retry_http_basic_auth()
# but returns a request object.
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
If you find boost::assign::map_list_of
useful, but can't use it for some reason, you could write your own:
template<class K, class V>
struct map_list_of_type {
typedef std::map<K, V> Map;
Map data;
map_list_of_type(K k, V v) { data[k] = v; }
map_list_of_type& operator()(K k, V v) { data[k] = v; return *this; }
operator Map const&() const { return data; }
};
template<class K, class V>
map_list_of_type<K, V> my_map_list_of(K k, V v) {
return map_list_of_type<K, V>(k, v);
}
int main() {
std::map<int, char> example =
my_map_list_of(1, 'a') (2, 'b') (3, 'c');
cout << example << '\n';
}
It's useful to know how such things work, especially when they're so short, but in this case I'd use a function:
struct A {
static map<int, int> const m;
};
namespace {
map<int,int> create_map() {
map<int, int> m;
m[1] = 2; // etc.
return m;
}
}
map<int, int> const A::m = create_map();
Consider adding this to your CSS to resolve the problem:
.btn {
width: 20%;
margin-left: 40%;
margin-right: 30%;
}
you need to cast int to str before concatenating. for that use str(temperature)
. Or you can print the same output using ,
if you don't want to convert like this.
print("the furnace is now",temperature , "degrees!")
Use your code
public class FragmentOne extends Fragment implements OnClickListener{
View view;
Fragment fragmentTwo;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi);
buttonSayHi.setOnClickListener(this);
return view;
}
But I think is better handle the buttons in this way:
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonSayHi:
/** Do things you need to..
fragmentTwo = new FragmentTwo();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
*/
break;
}
}
Here is PySpark version to create Hive table from parquet file. You may have generated Parquet files using inferred schema and now want to push definition to Hive metastore. You can also push definition to the system like AWS Glue or AWS Athena and not just to Hive metastore. Here I am using spark.sql to push/create permanent table.
# Location where my parquet files are present.
df = spark.read.parquet("s3://my-location/data/")
cols = df.dtypes
buf = []
buf.append('CREATE EXTERNAL TABLE test123 (')
keyanddatatypes = df.dtypes
sizeof = len(df.dtypes)
print ("size----------",sizeof)
count=1;
for eachvalue in keyanddatatypes:
print count,sizeof,eachvalue
if count == sizeof:
total = str(eachvalue[0])+str(' ')+str(eachvalue[1])
else:
total = str(eachvalue[0]) + str(' ') + str(eachvalue[1]) + str(',')
buf.append(total)
count = count + 1
buf.append(' )')
buf.append(' STORED as parquet ')
buf.append("LOCATION")
buf.append("'")
buf.append('s3://my-location/data/')
buf.append("'")
buf.append("'")
##partition by pt
tabledef = ''.join(buf)
print "---------print definition ---------"
print tabledef
## create a table using spark.sql. Assuming you are using spark 2.1+
spark.sql(tabledef);
You have to use either DQL or the QueryBuilder. E.g. in your Purchase-EntityRepository you could do something like this:
$q = $this->createQueryBuilder('p')
->where('p.prize > :purchasePrize')
->setParameter('purchasePrize', 200)
->getQuery();
$q->getResult();
For even more complex scenarios take a look at the Expr() class.
You can also generate in a range [min, max] with something like
float float_rand( float min, float max )
{
float scale = rand() / (float) RAND_MAX; /* [0, 1.0] */
return min + scale * ( max - min ); /* [min, max] */
}
Instruction is base on the "icemelon" post. Link to the post:
how-do-i-compile-and-run-a-c-program-in-sublime-text-2
Use the link below to find out how to setup enviroment variable on your OS:
The instruction below was tested on the Windows 8.1 system and Sublime Text 3 - build 3065.
1) Install MinGW. 2) Add path to the "MinGW\bin" in the "PATH environment variable".
"System Properties -> Advanced -> Environment" variables and there update "PATH' variable.
3) Then check your PATH environment variable by the command below in the "Command Prompt":
echo %path%
4) Add new Build System to the Sublime Text.
My version of the code below ("C.sublime-build").
link to the code:
// Put this file here:
// "C:\Users\[User Name]\AppData\Roaming\Sublime Text 3\Packages\User"
// Use "Ctrl+B" to Build and "Crtl+Shift+B" to Run the project.
// OR use "Tools -> Build System -> New Build System..." and put the code there.
{
"cmd" : ["gcc", "$file_name", "-o", "${file_base_name}.exe"],
// Doesn't work, sublime text 3, Windows 8.1
// "cmd" : ["gcc $file_name -o ${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path",
// You could add path to your gcc compiler this and don't add path to your "PATH environment variable"
// "path" : "C:\\MinGW\\bin"
"variants" : [
{ "name": "Run",
"cmd" : ["${file_base_name}.exe"]
}
]
}
That's because they serve different purposes and they both should be used not just one over the other.
The "alt" is for what you guys already said, so you can see what's the image it's all about if the image can't be displayed (for whatever reason), it also allows visually impaired people to understand what's the image about.
The "title" attribute is the correct one to show the tooltip with a title for the image.
which(df==my.val, arr.ind=TRUE)
I solved this problem the following way:
If you have a non-conda pip as your default pip but conda python is your default python (as below)
>which -a pip
/home/<user>/.local/bin/pip
/home/<user>/.conda/envs/newenv/bin/pip
/usr/bin/pip
>which -a python
/home/<user>/.conda/envs/newenv/bin/python
/usr/bin/python
Then instead of just calling
pip install <package>
, you can use the module flag -m
with python so that it uses the anaconda python for the installation
python -m pip install <package>
This installs the package to the anaconda library directory rather than to the library directory associated with (the non-anaconda) pip
You comment:
valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....
If you are interested in each term, then write the code so it deals with each. For example.
for b in valeur<=0.6:
if b:
print ("this works")
else:
print ("valeur is too high")
This will write 2 lines.
The error is produced by numpy
code when you try to use it a context that expects a single, scalar, value. if b:...
can only do one thing. It does not, by itself, iterate through the elements of b
doing a different thing for each.
You could also cast that iteration as list comprehension, e.g.
['yes' if b else 'no' for b in np.array([True, False, True])]
>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4
"Long winded" way
>>> for i,c in enumerate(s):
... if "r"==c: print i
...
4
to get substring,
>>> s="mystring"
>>> s[4:10]
'ring'
I finally realized now that instead of
git fetch --all && git reset --hard origin/master
it should be
git fetch --all && git reset --hard origin/<branch_name>
instead (if one works on a different branch)
For small sized list we can create LinkedList
and then can make use of descending iterator as:
List<String> stringList = new ArrayList<>(Arrays.asList("One", "Two", "Three"));
stringList.stream().collect(Collectors.toCollection(LinkedList::new))
.descendingIterator().
forEachRemaining(System.out::println); // Three, Two, One
System.out.println(stringList); // One, Two, Three
One of the problems of doing automated testing for APIs is that many of the tools require you to have the API server up and running before you run your test suite. It can be a real advantage to have a unit testing framework that is capable of running and querying the APIs in a fully automated test environment.
An option that's good for APIs implemented with Node.JS / Express is to use mocha for automated testing. In addition to unit tests, its easy to write functional tests against the APIs, separated into different test suites. You can start up the API server automatically in the local test environment and set up a local test database. Using make, npm, and a build server, you can create a "make test" target and an incremental build that will run the entire test suite every time a piece of code is submitted to your repository. For the truly fastidious developer, it will even generate a nice HTML code-coverage report showing you which parts of your code base are covered by tests or not. If this sounds interesting, here's a blog post that provides all the technical details.
If you're not using node, then whatever the defacto unit testing framework for the language is (jUnit, cucumber/capybara, etc) - look at its support for spinning up servers in the local test environment and running the HTTP queries. If it's a large project, the effort to get automated API testing and continual integration working will pay off pretty quickly.
Hope that helps.
Figured I'd post a project I recently came across to get dominant color:
A script for grabbing the dominant color or a representative color palette from an image. Uses javascript and canvas.
The other solutions mentioning and suggesting dominant color never really answer the question in proper context ("in javascript"). Hopefully this project will help those who want to do just that.
You can do this with the "rebase" command. Let's call the branches "main" and "feature":
git checkout feature
git rebase main
The rebase command will replay all of the commits on "feature" as one commit with a parent equal to "main".
You might want to run git merge main
before git rebase main
if "main" has changed since "feature" was created (or since the most recent merge). That way, you still have your full history in case you had a merge conflict.
After the rebase, you can merge your branch to main, which should result in a fast-forward merge:
git checkout main
git merge feature
See the rebase page of Understanding Git Conceptually for a good overview
Either use a semi-transparent PNG image or use CSS 3:
background-color: rgba(255, 0, 0, 0.5);
Here's an article from css3.info, Opacity, RGBA and compromise (2007-06-03).
<p style="background-color: rgba(255, 0, 0, 0.5);">_x000D_
<span>Hello, World!</span>_x000D_
</p>
_x000D_
Here is a plugin for PhoneGap which solved the problem for me: https://build.phonegap.com/plugins/1031
I simply included it in my config.xml
Open port 9418 on your firewall - it's a custom port that Git uses to communicate on and it's often not open on a corporate or private firewall.
You can also use RedirectMatch directive to deny access to a folder.
To deny access to a folder, you can use the following RedirectMatch in htaccess :
RedirectMatch 403 ^/folder/?$
This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.
To deny access to everything inside the folder, You can use this :
RedirectMatch 403 ^/folder/.*$
This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.
set echo off
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
The BOM is generated by, say, File.WriteAllText() or StreamWriter when you don't specify an Encoding. The default is to use the UTF8 encoding and generate a BOM. You can tell the java compiler about this with its -encoding command line option.
The path of least resistance is to avoid generating the BOM. Do so by specifying System.Text.Encoding.Default, that will write the file with the characters in the default code page of your operating system and doesn't write a BOM. Use the File.WriteAllText(String, String, Encoding) overload or the StreamWriter(String, Boolean, Encoding) constructor.
Just make sure that the file you create doesn't get compiled by a machine in another corner of the world. It will produce mojibake.
I've solved building an apk using the Build option from the top window and Build APK. No need to do something weird.
Nothing worked for IE (Internet Explorer). My testers were able to break my modal by clicking off the popup window on buttons behind it. So, I listened for a click on my modal screen div and forced refocus on a popup button.
<div class="modal-backscreen" (click)="modalOutsideClick($event)">
</div>
modalOutsideClick(event: any) {
event.preventDefault()
// handle IE click-through modal bug
event.stopPropagation()
setTimeout(() => {
this.renderer.invokeElementMethod(this.myModal.nativeElement, 'focus')
}, 100)
}
You can do that using the descendant selectors:
$("#a #b")
However, id values are supposed to be unique on a page.
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "SexDrugsRocknroll";
char dest[5] = { 0 }; // 4 chars + terminator */
int len = strlen(src);
int i = 0;
while (i*4 < len) {
strncpy(dest, src+(i*4), 4);
i++;
printf("loop %d : %s\n", i, dest);
}
}
Try the following, not sure which will work for all browsers or the browser you are working with, but it would be best to try all:
<textarea style="overflow:auto"></textarea>
Or
<textarea style="overflow:hidden"></textarea>
...As suggested above
You can also try adding this, I never used it before, just saw it posted on a site today:
<textarea style="resize:none"></textarea>
This last option would remove the ability to resize the textarea
. You can find more information on the CSS resize
property here
I use fetchObject() here a small example using Symfony 4.4
<?php
use Doctrine\DBAL\Driver\Connection;
class MyController{
public function index($username){
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder
->select('id', 'name')
->from('app_user')
->where('name = ?')
->setParameter(0, $username)
->setMaxResults(1);
$stmUser = $queryBuilder->execute();
dump($stmUser->fetchObject());
//get_class_methods($stmUser) -> to see all methods
}
}
Response:
{
"id": "2", "name":"myuser"
}
SharePoint lists V: Techniques for managing large lists :
Tutorial By Microsoft
Level: Advanced
Length: 40 - 50 minutes
When a SharePoint list gets large, you might see warnings such as, “This list exceeds the list view threshold,” or “Displaying the newest results below.” Find out why these warnings occur, and learn ways to configure your large list so that it still provides useful information.
After completing this course you will be able to:
I found that in my code when I used a ration or percentage for line-height line-height;1.5;
My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px;
so that I could predict exactly how many pixels each page would take with a given number of lines.