I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.
Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.
new Vue({
methods: {
setValue: function() {
this.$data.oldPeople = _.cloneDeep(this.$data.people);
},
},
mounted() {
this.setValue();
},
el: '#app',
data: {
people: [
{id: 0, name: 'Bob', age: 27},
{id: 1, name: 'Frank', age: 32},
{id: 2, name: 'Joe', age: 38}
],
oldPeople: []
},
watch: {
people: {
handler: function (after, before) {
// Return the object that changed
var vm = this;
let changed = after.filter( function( p, idx ) {
return Object.keys(p).some( function( prop ) {
return p[prop] !== vm.$data.oldPeople[idx][prop];
})
})
// Log it
vm.setValue();
console.log(changed)
},
deep: true,
}
}
})
See the updated codepen
After Aug. 4, 2015, if you are using the official mysql Docker image, you can just ADD/COPY a file into the /docker-entrypoint-initdb.d/ directory and it will run with the container is initialized. See github: https://github.com/docker-library/mysql/commit/14f165596ea8808dfeb2131f092aabe61c967225 if you want to implement it on other container images
I solved the same issue by following steps:
Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10
After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap
In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",
Now after updating package.json, use the command npm update
After this use command ng serve and my error got resolved
Use:
InputStream in = /* Your InputStream */;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;
while ((read=br.readLine()) != null) {
//System.out.println(read);
sb.append(read);
}
br.close();
return sb.toString();
I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line. In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.
I have same idea with user KM. but do not need extra table Number. Just this function only.
CREATE FUNCTION [dbo].[FN_ListToTable]
(
@SplitOn char(1) --REQUIRED, the character to split the @List string on
,@List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
@ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
DECLARE @number int = 0
DECLARE @childString varchar(502) = ''
DECLARE @lengthChildString int = 0
DECLARE @processString varchar(502) = @SplitOn + @List + @SplitOn
WHILE @number < LEN(@processString)
BEGIN
SET @number = @number + 1
SET @lengthChildString = CHARINDEX(@SplitOn, @processString, @number + 1) - @number - 1
IF @lengthChildString > 0
BEGIN
SET @childString = LTRIM(RTRIM(SUBSTRING(@processString, @number + 1, @lengthChildString)))
IF @childString IS NOT NULL AND @childString != ''
BEGIN
INSERT INTO @ParsedList(ListValue) VALUES (@childString)
SET @number = @number + @lengthChildString - 1
END
END
END
RETURN
END
And here is the test:
SELECT ListValue FROM dbo.FN_ListToTable('/','a/////bb/c')
Result:
ListValue
______________________
a
bb
c
I found the perfect way to Ignore files in TFS like SVN does.
First of all, select the file that you want to ignore (e.g. the Web.config).
Now go to the menu tab and select:
File Source control > Advanced > Exclude web.config from source control
... and boom; your file is permanently excluded from source control.
Constructors don't return a type , just remove the return type which is void in your case. It would run fine then.
Mistake in original post is acquire() call set inside the try loop. Here is a correct approach to use "binary" semaphore (Mutex):
semaphore.acquire();
try {
//do stuff
} catch (Exception e) {
//exception stuff
} finally {
semaphore.release();
}
After all else failed...
My solution was to change the layout file from
= stylesheet_link_tag "reset-min", 'application'
to
= stylesheet_link_tag 'application'
And it worked! (You can put the reset file inside the manifest.)
function doSomething(element) {
var form = element.form;
}
and in the html, you need to find that element, and add the attribut "form" to connect to that form, please refer to http://www.w3schools.com/tags/att_input_form.asp but this form attr doesn't support IE, for ie, you need to pass form id directly.
@
before a function call suppresses any errors that may be reported during the function call.
Adding a @
before session_start
tells PHP to avoid printing error messages.
For example:
Using session_start()
after you've already printed something to the browser results in an error so PHP will display something like "headers cannot be sent: started at (line 12)", @session_start()
will still fail in this case, but the error message is not printed on screen.
Before including the files or redirecting to new page use the exit()
function, otherwise it will give an error.
This code can be used in all cases:
<?php
if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
session_start();
}
?>
Sorry guys.. maybe it's a bit late.. I've been using NoGray.. it's cool..
Try this?
encodeURIComponent('space word').replace(/%20/g,'+')
One equivalent of lsof could be combined output from Sysinternals' handle and listdlls, i.e.:
c:\SysInternals>handle
[...]
------------------------------------------------------------------------------
gvim.exe pid: 5380 FOO\alois.mahdal
10: File (RW-) C:\Windows
1C: File (RW-) D:\some\locked\path\OpenFile.txt
[...]
c:\SysInternals>listdlls
[...]
------------------------------------------------------------------------------
Listdlls.exe pid: 6840
Command line: listdlls
Base Size Version Path
0x00400000 0x29000 2.25.0000.0000 D:\opt\SysinternalsSuite\Listdlls.exe
0x76ed0000 0x180000 6.01.7601.17725 C:\Windows\SysWOW64\ntdll.dll
[...]
c:\SysInternals>listdlls
Unfortunately, you have to "run as Administrator" to be able to use them.
Also listdlls and handle do not produce continuous table-like form so filtering filename would hide PID. findstr /c:pid: /c:<filename>
should get you very close with both utilities, though
c:\SysinternalsSuite>handle | findstr /c:pid: /c:Driver.pm
System pid: 4 \<unable to open process>
smss.exe pid: 308 NT AUTHORITY\SYSTEM
avgrsa.exe pid: 384 NT AUTHORITY\SYSTEM
[...]
cmd.exe pid: 7140 FOO\alois.mahdal
conhost.exe pid: 1212 FOO\alois.mahdal
gvim.exe pid: 3408 FOO\alois.mahdal
188: File (RW-) D:\some\locked\path\OpenFile.txt
taskmgr.exe pid: 6016 FOO\alois.mahdal
[...]
Here we can see that gvim.exe is the one having this file open.
Since x!=x
returns the same boolean array with np.isnan(x)
(because np.nan!=np.nan
would return True
), you could also write:
np.argwhere(x!=x)
However, I still recommend writing np.argwhere(np.isnan(x))
since it is more readable. I just try to provide another way to write the code in this answer.
There are four ways to create a singleton in Java.
Eager initialization singleton
public class Test {
private static final Test test = new Test();
private Test() {
}
public static Test getTest() {
return test;
}
}
Lazy initialization singleton (thread safe)
public class Test {
private static volatile Test test;
private Test() {
}
public static Test getTest() {
if(test == null) {
synchronized(Test.class) {
if(test == null) {
test = new Test();
}
}
}
return test;
}
}
Bill Pugh singleton with holder pattern (preferably the best one)
public class Test {
private Test() {
}
private static class TestHolder {
private static final Test test = new Test();
}
public static Test getInstance() {
return TestHolder.test;
}
}
Enum singleton
public enum MySingleton {
INSTANCE;
private MySingleton() {
System.out.println("Here");
}
}
What just worked for was to delete the settings.xml in the .m2 folder: this file was telling the project to look for a versión of spring mvc and web that didn't exist.
You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION
superglobal. Like this:
<?php
session_start();
echo $_SESSION['youritem'];
?>
You forgot the Session HELPER.
Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html
Here is what i did and it works.
I just used a stringified object.
$scope.thread = [
{
mostRecent:{text:'hello world',timeStamp:12345678 }
allMessages:[]
}
{MoreThreads...}
{etc....}
]
<div ng-repeat="message in thread | orderBy : '-mostRecent.timeStamp'" >
if i wanted to sort by text i would do
orderBy : 'mostRecent.text'
rand(3..10)
When max is a Range, rand returns a random number where range.member?(number) == true.
but select-String doesn't seem to have this option.
Correct. PowerShell is not a clone of *nix shells' toolset.
However it is not hard to build something like it yourself:
$regexes = Get-Content RegexFile.txt |
Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }
$fileList | Get-Content | Where-Object {
foreach ($r in $regexes) {
if ($r.IsMatch($_)) {
$true
break
}
}
$false
}
In my case, none of above answers nor google's official documentation helped me to grab the concept of PendingIntent
class.
And then I found this video, Google I/O 2013, Beyond the Blue Dot session. In this video, ex-googler Jaikumar Ganesh explains what PendingIntent
is, and that was the thing gave me the big picture of this.
Below is just transcription of above video (from 15:24).
So what's a pending intent?
It's a token that your app process will give to the location process, and the location process will use it to wake up your app when an event of interest happens. So this basically means that your app in the background doesn't have to be always running. When something of interest happens, we will wake you up. This saves a lot of battery.
This explanation becomes more clear with this snippet of code(which is included in the session's slide).
PendingIntent mIntent = PendingIntent.getService(...);
mLocationClient.requestLocationUpdates(locationRequest, mIntent);
public void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_LOCATION.equals(action)) {
Location location = intent.getParcelableExtra(...)
}
}
CHAR(5)
or
MEDIUMINT (5) UNSIGNED ZEROFILL
The first takes 5 bytes per zip code.
The second takes only 3 bytes per zip code. The ZEROFILL option is necessary for zip codes with leading zeros.
You could use pandas
:
In [1]: import pandas as pd
In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]
In [3]: my_df = pd.DataFrame(a)
In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
This is not a new answer, but it helped me to understand the different aspects of the answers above (and it is too much for a comment).
Using Git Bash just try:
me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:11 ../
me@pc MINGW64 /c/Test
$ git init
Initialized empty Git repository in C:/Test/.git/
me@pc MINGW64 /c/Test (master)
$ ls -al
total 20
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:11 ../
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 .git/
me@pc MINGW64 /c/Test (master)
$ cd .git
me@pc MINGW64 /c/Test/.git (GIT_DIR!)
$ ls -al
total 15
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 ../
-rw-r--r-- 1 myid 1049089 130 Apr 1 11:35 config
-rw-r--r-- 1 myid 1049089 73 Apr 1 11:35 description
-rw-r--r-- 1 myid 1049089 23 Apr 1 11:35 HEAD
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 hooks/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 info/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 objects/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 refs/
Same with git --bare
:
me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:11 ../
me@pc MINGW64 /c/Test
$ git init --bare
Initialized empty Git repository in C:/Test/
me@pc MINGW64 /c/Test (BARE:master)
$ ls -al
total 23
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:11 ../
-rw-r--r-- 1 myid 1049089 104 Apr 1 11:36 config
-rw-r--r-- 1 myid 1049089 73 Apr 1 11:36 description
-rw-r--r-- 1 myid 1049089 23 Apr 1 11:36 HEAD
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 hooks/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 info/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 objects/
If you are using svn with Jenkins on a Windows Server, you must accept https certificate using the same Jenkins's Windows service user.
So , if your Jenkins service runs as "MYSERVER\Administrator", you must use this command before all others, only one time of course :
runas /user:MYSERVER\Administrator "svn --username user --password password list https://myserver/svn/REPO "
svn asks you to accept the certificate and stores it in the right path.
After this you'll be able to use svn in jenkins job directly in a Windows batch command step.
Here's my solution
if [[ "${cms}" != +(wordpress|magento|typo3) ]]; then
The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).
# now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')
Many times it does happen that cpan install command fails with the message like "make test had returned bad status, won't install without force"
In that case following is the way to install the module:
perl -MCPAN -e "CPAN::Shell->force(qw(install Foo::Bar));"
To get caller/called class name use below code, it works fine for me.
String callerClassName = new Exception().getStackTrace()[1].getClassName();
String calleeClassName = new Exception().getStackTrace()[0].getClassName();
As per Oracle Documentation:
"You cannot create arrays of parameterized types"
Instead, you could do:
ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);
As suggested by Tom Hawting - tackline, it is even better to do:
List<List<Individual>> group = new ArrayList<List<Individual>>(4);
For example:
const std::map<LogLevel, const char*> g_log_levels_dsc =
{
{ LogLevel::Disabled, "[---]" },
{ LogLevel::Info, "[inf]" },
{ LogLevel::Warning, "[wrn]" },
{ LogLevel::Error, "[err]" },
{ LogLevel::Debug, "[dbg]" }
};
If map is a data member of a class, you can initialize it directly in header by the following way (since C++17):
// Example
template<>
class StringConverter<CacheMode> final
{
public:
static auto convert(CacheMode mode) -> const std::string&
{
// validate...
return s_modes.at(mode);
}
private:
static inline const std::map<CacheMode, std::string> s_modes =
{
{ CacheMode::All, "All" },
{ CacheMode::Selective, "Selective" },
{ CacheMode::None, "None" }
// etc
};
};
A little more readable :)
public static <T> ArrayList<T> reverse(ArrayList<T> list) {
int length = list.size();
ArrayList<T> result = new ArrayList<T>(length);
for (int i = length - 1; i >= 0; i--) {
result.add(list.get(i));
}
return result;
}
.className{
width: auto;
height: 200px;
max-height: 200px;
max-width:200px
object-fit: contain;
}
For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, executable zip files and directories.
python myapp.zip
Where myapp.zip is a zip containing a __main__.py
file which is executed as the script file to be executed. Your package dependencies can also be included in the file:
__main__.py
mypackage/__init__.py
mypackage/someliblibfile.py
You can also execute an egg, but the incantation is not as nice:
# Bourn Shell and derivatives (Linux/OSX/Unix)
PYTHONPATH=myapp.egg python -m myapp
rem Windows
set PYTHONPATH=myapp.egg
python -m myapp
This puts the myapp.egg on the Python path and uses the -m argument to run a module. Your myapp.egg will likely look something like:
myapp/__init__.py
myapp/somelibfile.py
And python will run __init__.py
(you should check that __file__=='__main__'
in your app for command line use).
Egg files are just zip files so you might be able to add __main__.py
to your egg with a zip tool and make it executable in python 2.6 and run it like python myapp.egg
instead of the above incantation where the PYTHONPATH environment variable is set.
More information on executable zip files including how to make them directly executable with a shebang can be found on Michael Foord's blog post on the subject.
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
::-webkit-scrollbar {
width: 15px;
height: 15px;
}
::-webkit-scrollbar-thumb {
border-radius: 8px;
background-color: #C3C3C3;
border: 2px solid #eee;
}
Use this code, it work in ios/android APP webview; It delete some not portable css code;
You say your website is in http://localhost/mywebsite
, and let's say that your image is inside a subfolder named pictures/
:
Absolute path
If you use an absolute path, /
would point to the root of the site, not the root of the document: localhost
in your case. That's why you need to specify your document's folder in order to access the pictures folder:
"/mywebsite/pictures/picture.png"
And it would be the same as:
"http://localhost/mywebsite/pictures/picture.png"
Relative path
A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:
"pictures/picture.png"
But there are other perks with relative paths:
dot-slash (./
)
Dot (.
) points to the same directory and the slash (/
) gives access to it:
So this:
"pictures/picture.png"
Would be the same as this:
"./pictures/picture.png"
Double-dot-slash (../
)
In this case, a double dot (..
) points to the upper directory and likewise, the slash (/
) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:
"../picture.png"
You can play around with them as much as you want, a little example would be this:
Let's say you're on directory A
, and you want to access directory X
.
- root
|- a
|- A
|- b
|- x
|- X
Your URL would look either:
Absolute path
"/x/X/picture.png"
Or:
Relative path
"./../x/X/picture.png"
This might be useful https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships
Basically it sounds like they act as OR
If all you want to do is get rid of invalid hostname errors you can just do:
HttpClient httpClient = new DefaultHttpClient();
SSLSocketFactory sf = (SSLSocketFactory)httpClient.getConnectionManager()
.getSchemeRegistry().getScheme("https").getSocketFactory();
sf.setHostnameVerifier(new AllowAllHostnameVerifier());
Use DateTime.TryParseExact()
if you want to match against a specific date format
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
{
Console.WriteLine(dateTime);
}
else
{
Console.WriteLine("Not a date");
}
You should look at the members of the thrown exception, particularly .Message
and .InnerException
.
I would also see whether or not the documentation for InvokeMethod tells you whether it throws some more specialized Exception class than Exception - such as the Win32Exception suggested by @Preet. Catching and just looking at the Exception base class may not be particularly useful.
If you want to start with a file you can do this
[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName
def awgn(sinal):
regsnr=54
sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
sigpower=sigpower/len(sinal)
noisepower=sigpower/(math.pow(10,regsnr/10))
noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
return noise
I found the answer to this question here..... The problem was hosting server... I thank all who tried .... Hope this will help others
In my case I had a panda Series where the values are tuples of characters:
Out[67]
0 (H, H, H, H)
1 (H, H, H, T)
2 (H, H, T, H)
3 (H, H, T, T)
4 (H, T, H, H)
Therefore I could use indexing to filter the series, but to create the index I needed apply
. My condition is "find all tuples which have exactly one 'H'".
series_of_tuples[series_of_tuples.apply(lambda x: x.count('H')==1)]
I admit it is not "chainable", (i.e. notice I repeat series_of_tuples
twice; you must store any temporary series into a variable so you can call apply(...) on it).
There may also be other methods (besides .apply(...)
) which can operate elementwise to produce a Boolean index.
Many other answers (including accepted answer) using the chainable functions like:
.compress()
.where()
.loc[]
[]
These accept callables (lambdas) which are applied to the Series, not to the individual values in those series!
Therefore my Series of tuples behaved strangely when I tried to use my above condition / callable / lambda, with any of the chainable functions, like .loc[]
:
series_of_tuples.loc[lambda x: x.count('H')==1]
Produces the error:
KeyError: 'Level H must be same as name (None)'
I was very confused, but it seems to be using the Series.count series_of_tuples.count(...)
function , which is not what I wanted.
I admit that an alternative data structure may be better:
This creates a series of strings (i.e. by concatenating the tuple; joining the characters in the tuple on a single string)
series_of_tuples.apply(''.join)
So I can then use the chainable Series.str.count
series_of_tuples.apply(''.join).str.count('H')==1
use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish
while 1:
if condition1 and condition2:
break
...
...
if condition3: break
...
...
Here is an example of run process as administrator without Windows Prompt
Process p = new Process();
p.StartInfo.FileName = Server.MapPath("process.exe");
p.StartInfo.Arguments = "";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.Verb = "runas";
p.Start();
p.WaitForExit();
The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp
. A few resources include:
http://dev.mysql.com/doc/refman/5.1/en/datetime.html
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
How to store Java Date to Mysql datetime...?
EDIT:
As others have indicated, the suggestion of using strings may lead to issues.
Use config.to_prepare to load you monkey patches/extensions for every request in development mode.
config.to_prepare do |action_dispatcher|
# More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
Rails.logger.info "\n--- Loading extensions for #{self.class} "
Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
Rails.logger.info "Loading extension(s): #{entry}"
require_dependency "#{entry}"
end
Rails.logger.info "--- Loaded extensions for #{self.class}\n"
end
If you know the file is in your current directory, I would use:
ls -lt | head
This lists your most recently modified files and directories in order. In fact, I use it so much I have it aliased to 'lh'.
Do you want to iterate over characters or words?
For words, you'll have to split the words first, such as
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index
This prints the index of the word.
For the absolute character position you'd need something like
chars = 0
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
chars += len(word) + 1
In GVIM, The file can be browsed using open / read / write dialog;
:browse {command}
{command} - open / read / write
open - Opens the file read - Appends the file write - SaveAs dialog
sorted(x) == sorted(y)
Copying from here: Check if two unordered lists are equal
I think this is the best answer for this question because
With question 3, this article states that RESTful Services are appropiate in this scenarios:
While SOAP is the way to go when:
$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query = $this->db->get();
return $query->result_array();
In my case, I had the variable named "AWS_PROFILE" on Environment variables with an old value.
Solution that worked for me:
Consider an entity:
public class Foo{
private<user> user;
/* with getters and setters */
}
And consider an Business Logic class:
class Foo1{
List<User> user = new ArrayList<>();
user = foo.getUser();
}
Here the user and foo.getUser()
share the same reference. But saving the two references creates a conflict.
The proper usage should be:
class Foo1 {
List<User> user = new ArrayList<>();
user.addAll(foo.getUser);
}
This avoids the conflict.
Try this:
[Authorize]
public ActionResult SomeAction()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
...
}
Well, even the SELECT COUNT(*) FROM Table
will be fairly inefficient, especially on large tables, since SQL Server really can't do anything but do a full table scan (clustered index scan).
Sometimes, it's good enough to know an approximate number of rows from the database, and in such a case, a statement like this might suffice:
SELECT
SUM(used_page_count) * 8 AS SizeKB,
SUM(row_count) AS [RowCount],
OBJECT_NAME(OBJECT_ID) AS TableName
FROM
sys.dm_db_partition_stats
WHERE
OBJECT_ID = OBJECT_ID('YourTableNameHere')
AND (index_id = 0 OR index_id = 1)
GROUP BY
OBJECT_ID
This will inspect the dynamic management view and extract the number of rows and the table size from it, given a specific table. It does so by summing up the entries for the heap (index_id = 0) or the clustered index (index_id = 1).
It's quick, it's easy to use, but it's not guaranteed to be 100% accurate or up to date. But in many cases, this is "good enough" (and put much less burden on the server).
Maybe that would work for you, too? Of course, to use it in EF, you'd have to wrap this up in a stored proc or use a straight "Execute SQL query" call.
Marc
Ctrl + Break works, but only if the Build window is active. Also, interrupting the build will sometimes leave a corrupted .obj
file that will have to be manually deleted in order for the build to proceed.
It is in a folder with your application's name in Application Data folder in User's home folder (C:\documents and settings\user on xp and c:\users\user on Windows Vista).
There is some information here also.
PS:- try accessing it by %appdata% in run box!
os.Executable
: https://tip.golang.org/pkg/os/#Executable
filepath.EvalSymlinks
: https://golang.org/pkg/path/filepath/#EvalSymlinks
Full Demo:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
var dirAbsPath string
ex, err := os.Executable()
if err == nil {
dirAbsPath = filepath.Dir(ex)
fmt.Println(dirAbsPath)
return
}
exReal, err := filepath.EvalSymlinks(ex)
if err != nil {
panic(err)
}
dirAbsPath = filepath.Dir(exReal)
fmt.Println(dirAbsPath)
}
I'd suggest you do two things:
>>
in your shell script to append contents to particular file. The filename can be fixed or using some pattern.Try this:
DisplayMetrics dm = context.getResources().getDisplayMetrics();
int densityDpi = dm.densityDpi;
Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:
$rootScope.$digest()
-- i.e., check the full component tree$rootScope.$apply(callback)
-- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.$scope.$digest()
-- i.e., check only this component and its childrenYou will need to import and then inject ApplicationRef
, NgZone
, or ChangeDetectorRef
into your component.
For your particular scenario, I would recommend the last option if only a single component has changed.
I landed here because of an XCTestCase, in which I'd disabled most of the tests by prefixing them with 'no_' as in no_testBackgroundAdding. Once I noticed that most of the answers had something to do with locks and threading, I realized the test contained a few instances of XCTestExpectation with corresponding waitForExpectations. They were all in the disabled tests, but apparently Xcode was still evaluating them at some level.
In the end I found an XCTestExpectation that was defined as @property but lacked the @synthesize. Once I added the synthesize directive, the EXC_BAD_INSTRUCTION disappeared.
You can compare class tokens to each other, so you could use value.getClass() == Integer.class
. However, the simpler and more canonical way is to use instanceof
:
if (value instanceof Integer) {
System.out.println("This is an Integer");
} else if(value instanceof String) {
System.out.println("This is a String");
} else if(value instanceof Float) {
System.out.println("This is a Float");
}
Notes:
instanceof C
matches for subclasses of C
too. However, in this case all the classes listed are final
, so they have no subclasses. Thus instanceof
is probably fine here.as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.
System.out.println("This is a(n) " + value.getClass().getSimpleName());
You'll need to use a different SimpleDateFormat
object for each different pattern. That said, you don't need that many different ones, thanks to this:
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.
So, you'll need these formats:
"M/y"
(that covers 9/09
, 9/2009
, and 09/2009
)"M/d/y"
(that covers 9/1/2009
)"M-d-y"
(that covers 9-1-2009
)So, my advice would be to write a method that works something like this (untested):
// ...
List<String> formatStrings = Arrays.asList("M/y", "M/d/y", "M-d-y");
// ...
Date tryParse(String dateString)
{
for (String formatString : formatStrings)
{
try
{
return new SimpleDateFormat(formatString).parse(dateString);
}
catch (ParseException e) {}
}
return null;
}
Swift 4 & iOs 11+
@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, handler in
handler(true)
// handle deletion here
}
let more = UIContextualAction(style: .normal, title: "More") { _, _, handler in
handler(true)
// handle more here
}
return UISwipeActionsConfiguration(actions: [delete, more])
}
Some ideas in the following answer:
Steps in creating a web service using Axis2 - The client code
Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.
There are lots of web service frameworks out there...
Even shorter way, may require newer ASP.Net:
string authority = Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)
The UriComponents enum lets you specify which component(s) of the URI you want to include.
IMHO, hg strip -r 39
suits this case better.
It requires the mq extension to be enabled and has the same limitations as the "cloning repo method" recommended by Martin Geisler: If the changeset was somehow published, it will (probably) return to your repo at some point in time because you only changed your local repo.
Arrays have a property .length
that returns the number of elements.
var st =
{
"itema":{},
"itemb":
[
{"id":"s01","cd":"c01","dd":"d01"},
{"id":"s02","cd":"c02","dd":"d02"}
]
};
st.itemb.length // 2
You can try this solution.... It works great
function explodeX( $delimiters, $string )
{
return explode( chr( 1 ), str_replace( $delimiters, chr( 1 ), $string ) );
}
$list = 'Thing 1&Thing 2,Thing 3|Thing 4';
$exploded = explodeX( array('&', ',', '|' ), $list );
echo '<pre>';
print_r($exploded);
echo '</pre>';
Source : http://www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/
For those who have trouble achieving the same in the Android browser with the touch event, use:
html, body {
-webkit-touch-callout: none;
-webkit-user-select: none;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
-webkit-tap-highlight-color: transparent;
}
Use This way is Better
if LEN(ISNULL(@Value,''))=0
This check the field is empty
or NULL
try some thing like blow:
SString otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
References :
Just downloaded the latest mysqlworkbench which is compatible with the latest encryption:
https://downloads.mysql.com/archives/workbench/
Note: On Mac big Sur, the latest two versions: 8.0.22 and 8.0.23 are buggy and do not work.
Use 8.0.21 until these are fixed
if ( window.onsubmit ) {
//
} else {
alert("Function does not exist.");
}
[root@piwik-dev tmp]# mail -v root@localhost
Subject: Test
Hello world
Cc: <Ctrl+D>
root@localhost... Connecting to [127.0.0.1] via relay...
220 piwik-dev.example.com ESMTP Sendmail 8.13.8/8.13.8; Thu, 23 Aug 2012 10:49:40 -0400
>>> EHLO piwik-dev.example.com
250-piwik-dev.example.com Hello localhost.localdomain [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-DELIVERBY
250 HELP
>>> MAIL From:<[email protected]> SIZE=46
250 2.1.0 <[email protected]>... Sender ok
>>> RCPT To:<[email protected]>
>>> DATA
250 2.1.5 <[email protected]>... Recipient ok
354 Enter mail, end with "." on a line by itself
>>> .
250 2.0.0 q7NEneju002633 Message accepted for delivery
root@localhost... Sent (q7NEneju002633 Message accepted for delivery)
Closing connection to [127.0.0.1]
>>> QUIT
221 2.0.0 piwik-dev.example.com closing connection
I Solve it by changing the owner from root to my user-name
sudo chown -R me:me /home/me/.config/configstore/
change me with your user-name and group .
I was getting this env: node: No such file or directory
error when running the job through Jenkins.
What I did to fix it - added export PATH="$PATH:"/usr/local/bin/
at the beginning of the script that Jenkins job executes.
I know this is late info, but in jQuery, using .checked is possible and easy! If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object! ENJOY!
We know that the UDP is a connection-less protocol, so it is
Specific examples:
Swap using Bitwise
let a = 10;
let b = 20;
a ^= b;
y ^= a;
a ^= b;
Single line Swap "using Array"
[a, b] = [b, a]
For me he problem was that my script was called pandas.py
in the folder pandas
which obviously messed up my imports.
adding following to application.rb
works
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local # Or :utc
Use OleDB, you can create, read, and edit excel files pretty easily. Read the MSDN docs for more info:
http://msdn.microsoft.com/en-us/library/aa288452(VS.71).aspx
I've used OleDB to read from excel files and I know you can create them, but I haven't done it firsthand.
oh, that's a tough one. What you have here, basically, is two values for each item. Then you are trying to call them with a number as the key. Unfortunately, one of your values is already set as the key!
Try this:
colors = {1: ["blue", "5"], 2: ["red", "6"], 3: ["yellow", "8"]}
Now you can call the keys by number as if they are indexed like a list. You can also reference the color and number by their position within the list.
For example,
colors[1][0]
// returns 'blue'
colors[3][1]
// returns '8'
Of course, you will have to come up with another way of keeping track of what location each color is in. Maybe you can have another dictionary that stores each color's key as it's value.
colors_key = {'blue': 1, 'red': 6, 'yllow': 8}
Then, you will be able to also look up the colors key if you need to.
colors[colors_key['blue']][0] will return 'blue'
Something like that.
And then, while you're at it, you can make a dict with the number values as keys so that you can always use them to look up your colors, you know, if you need.
values = {5: [1, 'blue'], 6: [2, 'red'], 8: [3, 'yellow']}
Then, (colors[colors_key[values[5][1]]][0]) will return 'blue'.
Or you could use a list of lists.
Good luck!
I've always tested to find the MAX string length of an encrypted string and set that as the character length of a VARCHAR type. Depending on how many records you're going to have, it could really help the database size.
I landed up here, tried your ways and could not figure out.
I was actually working on a pregiven code where
pickle.load(path)
was used so i replaced it with
np.load(path, allow_pickle=True)
$web_url = 'http://www.writephponline.com?name=shubham&[email protected]';
$query = parse_url($web_url, PHP_URL_QUERY);
parse_str($query, $queryArray);
echo "Name: " . $queryArray['name']; // Result: shubham
echo "EMail: " . $queryArray['email']; // Result:[email protected]
Lines 1,2,3,4 will call the default constructor. They are different in the essence as 1,2 are dynamically created object and 3,4 are statically created objects.
In Line 7, you create an object inside the argument call. So its an error.
And Lines 5 and 6 are invitation for memory leak.
This is what I normally use, albeit a bit manual:
/* Add a 'temporary' UDDT with the new definition */
exec sp_addtype t_myudt_tmp, 'numeric(18,5)', NULL
/* Build a command to alter all the existing columns - cut and
** paste the output, then run it */
select 'alter table dbo.' + TABLE_NAME +
' alter column ' + COLUMN_NAME + ' t_myudt_tmp'
from INFORMATION_SCHEMA.COLUMNS
where DOMAIN_NAME = 't_myudt'
/* Remove the old UDDT */
exec sp_droptype t_mydut
/* Rename the 'temporary' UDDT to the correct name */
exec sp_rename 't_myudt_tmp', 't_myudt', 'USERDATATYPE'
DO it like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");
Do not forget the %
at the end
A working example:
$qb = $this->createQueryBuilder('a');
$query=$qb->getQuery();
// SHOW SQL:
echo $query->getSQL();
// Show Parameters:
echo $query->getParameters();
Use:
#import <QuartzCore/QuartzCore.h>
.......
[myView.layer removeAllAnimations];
An alternative General Plan, which I'm only adding as an independent Answer because the blasted "comment on an answer" won't take newlines without posting the entire edit, even though it isn't finished yet.
UPDATE table A
JOIN table B ON {join fields}
JOIN table C ON {join fields}
JOIN {as many tables as you need}
SET A.column = {expression}
Example:
UPDATE person P
JOIN address A ON P.home_address_id = A.id
JOIN city C ON A.city_id = C.id
SET P.home_zip = C.zipcode;
import serial
ser = serial.Serial(0) # open first serial port
print ser.portstr # check which port was really used
ser.write("hello") # write a string
ser.close() # close port
use https://pythonhosted.org/pyserial/ for more examples
try to use this
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<RadioButton
android:id="@+id/standard_delivery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Standard_delivery"
android:checked="true"
android:layout_marginTop="4dp"
android:layout_marginLeft="15dp"
android:textSize="12dp"
android:onClick="onRadioButtonClicked"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Midnight_delivery"
android:checked="false"
android:layout_marginRight="15dp"
android:layout_marginTop="4dp"
android:textSize="12dp"
android:onClick="onRadioButtonClicked"
android:id="@+id/midnight_delivery"
/>
</RadioGroup>
this is java class
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.standard_delivery:
if (checked)
Toast.makeText(DishActivity.this," standard delivery",Toast.LENGTH_LONG).show();
break;
case R.id.midnight_delivery:
if (checked)
Toast.makeText(DishActivity.this," midnight delivery",Toast.LENGTH_LONG).show();
break;
}
}
This code might work for non-.NET Core MVC controllers:
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);
To solve this issue more globally, here is another way using a directive:
import { Directive, HostListener, ElementRef } from "@angular/core";
@Directive({
selector: "[hrefExternalUrl]"
})
export class HrefExternalUrlDirective {
constructor(elementRef: ElementRef) {}
@HostListener("click", ["$event"])
onClick(event: MouseEvent) {
event.preventDefault();
let url: string = (<any>event.currentTarget).getAttribute("href");
if (url && url.indexOf("http") === -1) {
url = `//${url}`;
}
window.open(url, "_blank");
}
}
then it's as simple as using it like this:
<a [href]="url" hrefExternalUrl> Link </a>
and don't forget to declare the directive in your module.
IMHO, onclick is the preferred method over .click only when the following conditions are met:
I formed this opinion because of the fact that the JavaScript engines on mobile devices are 4 to 7 times slower than their desktop counterparts which were made in the same generation. I hate it when I visit a site on my mobile device and receive jittery scrolling because the jQuery is binding all of the events at the expense of my user experience and battery life. Another recent supporting factor, although this should only be a concern with government agencies ;) , we had IE7 pop-up with a message box stating that JavaScript process is taking to long...wait or cancel process. This happened every time there were a lot of elements to bind to via jQuery.
hopefully its work
SET foreign_key_checks = 0;
DROP TABLE table name
;
SET foreign_key_checks = 1;
this part :
"Your new price is: $"(float(price)
asks python to call this string:
"Your new price is: $"
just like you would a function:
function( some_args)
which will ALWAYS trigger the error:
TypeError: 'str' object is not callable
With ggplot2
:
p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)
Upcoming pandas 0.13 version will allow to add rows through loc
on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.
Description is here and this new feature is called Setting With Enlargement.
I haven't used it yet but I would take a look at http://www.zoneminder.com/ The documentation explains you can install it on a modest machine with linux and use IP cameras for remote recording.
Andrew
I came up with this idea and it works perfectly. Okay so basically we want to get rid of the videos first frame from the display and then resize the poster to the videos actual size. If we then set the dimensions we have completed one of these tasks. Then only one remains. So now, the only way I know to get rid of the first frame is to actually define a poster. However we are going to give the video a faked one, one that doesn't exist. This will result in a blank display with the background transparent. I.e. our parent div's background will be visible.
Simple to use, however it might not work with all web browsers if you want to resize the dimension of the background of the div to the dimension of the video since my code is using "background-size".
HTML/HTML5:
<div class="video_poster">
<video poster="dasdsadsakaslmklda.jpg" controls>
<source src="videos/myvideo.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<div>
CSS:
video{
width:694px;
height:390px;
}
.video_poster{
width:694px;
height:390px;
background-size:694px 390px;
background-image:url(images/myvideo_poster.jpg);
}
It's not possible to achieve the required level of control over presentation in a regular textarea
.
If you're OK with that, try CodeMirror or Ace or Monaco (used in MS VSCode).
From the duplicate thread - an obligatory wikipedia link: Comparison of JavaScript-based source code editors
EDIT:
The point with the nulls in the array has been cleared. Sorry for my comments.
Original:
Ehm... the line
array = list.toArray(array);
replaces all gaps in the array where the removed element has been with null. This might be dangerous, because the elements are removed, but the length of the array remains the same!
If you want to avoid this, use a new Array as parameter for toArray(). If you don`t want to use removeAll, a Set would be an alternative:
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
Set<String> asSet = new HashSet<String>(Arrays.asList(array));
asSet.remove("a");
array = asSet.toArray(new String[] {});
System.out.println(Arrays.toString(array));
Gives:
[a, bc, dc, a, ef]
[dc, ef, bc]
Where as the current accepted answer from Chris Yester Young outputs:
[a, bc, dc, a, ef]
[bc, dc, ef, null, ef]
with the code
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);
System.out.println(Arrays.toString(array));
without any null values left behind.
Your pattern does not correspond to the input string at all... It is not surprising that it does not work. This would probably work better:
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Then to print with your required format you need a second SimpleDateFormat:
Date parsedDate = sdf.parse(date);
SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
System.out.println(print.format(parsedDate));
Notes:
You need to escape quotes with double backslashes.
This fails (produced by PHP's json_encode):
<script>
var jsonString = '[{"key":"my \"value\" "}]';
var parsedJson = JSON.parse(jsonString);
</script>
This works:
<script>
var jsonString = '[{"key":"my \\"value\\" "}]';
var parsedJson = JSON.parse(jsonString);
</script>
I know this question has been answered but I also see there is another way missing which I would like to cover it.There are multiple ways to achieve this.
1- innerHTML
document.getElementById("ShowButton").innerHTML = 'Show Filter';
You can insert HTML into this. But the disadvantage of this method is, it has cross site security attacks. So for adding text, its better to avoid this for security reasons.
2- innerText
document.getElementById("ShowButton").innerText = 'Show Filter';
This will also achieve the result but its heavy under the hood as it requires some layout system information, due to which the performance decreases. Unlike innerHTML, you cannot insert the HTML tags with this. Check Performance Here
3- textContent
document.getElementById("ShowButton").textContent = 'Show Filter';
This will also achieve the same result but it doesn't have security issues like innerHTML as it doesn't parse HTML like innerText. Besides, it is also light due to which performance increases.
So if a text has to be added like above, then its better to use textContent.
Product Version
may be preferred if you're using versioning via GitVersion or other versioning software.
To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion
:
using System.Diagnostics;
using System.Reflection;
//...
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion
Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.
<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
jQuery("#" + id).html(jQuery("#loading").html());
jQuery("#" + id).show();
}
Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):
Public oConn As ADODB.Connection
Sub MySqlInit()
If oConn Is Nothing Then
Dim str As String
str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
Set oConn = New ADODB.Connection
oConn.Open str
End If
End Sub
The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\
Use ng-show
and toggle the value of a show
scope variable in the ng-click
handler.
Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/
<ul class="procedures">
<li ng-repeat="procedure in procedures">
<h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="show">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
We have come across this issue in desktop app.
Dev Environment: Windows 7 Ultimate - 64 bit .Net Framework 4.5 Provider=Microsoft.Jet.OLEDB.4.0
It has been resolved by changing Platform target to X86 from Any CPU. Project Properties >> Build >> Platform Target.
Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.
var updater = {};
function geoCodeCity(goocoord) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': goocoord
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
updater.currentLocation = results[1].formatted_address;
} else {
if (status == "ERROR") {
console.log(status);
}
}
});
};
select * from my_table where my_field Like '[a-z][a-z]%'
If the .htaccess
file not avilable create it on root folder and past this line of code.
Put this in .htaccess
file (tested working well for API)
<IfModule mod_php5.c>
php_value always_populate_raw_post_data -1
</IfModule>
You need to use table-layout:fixed
in order for CSS ellipsis to work on the table cells.
.table {
table-layout:fixed;
}
.table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
That sure must seem confusing. So this is what is going on. The first value of enumerate (in this case i) returns the next index value starting at 0 so 0, 1, 2, 3, ... It will always return these numbers regardless of what is in the dictionary. The second value of enumerate (in this case j) is returning the values in your dictionary/enumm (we call it a dictionary in Python). What you really want to do is what roadrunner66 responded with.
Docstring conventions are in PEP-257 with much more detail than PEP-8.
However, docstrings seem to be far more personal than other areas of code. Different projects will have their own standard.
I tend to always include docstrings, because they tend to demonstrate how to use the function and what it does very quickly.
I prefer to keep things consistent, regardless of the length of the string. I like how to code looks when indentation and spacing are consistent. That means, I use:
def sq(n):
"""
Return the square of n.
"""
return n * n
Over:
def sq(n):
"""Returns the square of n."""
return n * n
And tend to leave off commenting on the first line in longer docstrings:
def sq(n):
"""
Return the square of n, accepting all numeric types:
>>> sq(10)
100
>>> sq(10.434)
108.86835599999999
Raises a TypeError when input is invalid:
>>> sq(4*'435')
Traceback (most recent call last):
...
TypeError: can't multiply sequence by non-int of type 'str'
"""
return n*n
Meaning I find docstrings that start like this to be messy.
def sq(n):
"""Return the squared result.
...
If you installed the command line tools separately, delete them using:
sudo rm -rf /Library/Developer/CommandLineTools
The expression -z string
is true if the length of string is zero
.
You just need to find the right multiplier, which can be easily calculated from the hist
object.
myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist)
lines(mydensity)
A more complete version, with a normal density and lines at each standard deviation away from the mean (including the mean):
myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist)
lines(mydensity)
myx <- seq(min(mtcars$mpg), max(mtcars$mpg), length.out= 100)
mymean <- mean(mtcars$mpg)
mysd <- sd(mtcars$mpg)
normal <- dnorm(x = myx, mean = mymean, sd = mysd)
lines(myx, normal * multiplier[1], col = "blue", lwd = 2)
sd_x <- seq(mymean - 3 * mysd, mymean + 3 * mysd, by = mysd)
sd_y <- dnorm(x = sd_x, mean = mymean, sd = mysd) * multiplier[1]
segments(x0 = sd_x, y0= 0, x1 = sd_x, y1 = sd_y, col = "firebrick4", lwd = 2)
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
This works for me:
const from = '2019-01-01';_x000D_
const to = '2019-01-08';_x000D_
_x000D_
Math.abs(_x000D_
moment(from, 'YYYY-MM-DD')_x000D_
.startOf('day')_x000D_
.diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
) + 1_x000D_
);
_x000D_
mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.
I know this has been closed for a while, but I thought it might be useful to promote another async solution built on the requests library.
list_of_requests = ['http://moop.com', 'http://doop.com', ...]
from simple_requests import Requests
for response in Requests().swarm(list_of_requests):
print response.content
The docs are here: http://pythonhosted.org/simple-requests/
CODE:
import codecs
path="D:\\Users\\html\\abc.html"
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)
In windows all you have to do is to go to windows search Allow an app through Windows Firewall.click on Allow another app select Apache and mark public and private both . Open cmd by pressing windows button+r write cmd than in cmd write ipconfig find out your ip . than open up your browser write down your ip http://172.16..x and you will be on the xampp startup page.if you want to access your local site simply put / infront of your ip e.g http://192.168.1.x/yousite. Now you are able to access your website in private network computers .
i hope this will resolve your problem
Yes, You can do it in a simple way. See below code of lines.
URL - http://localhost:8080/get/request/multiple/param/by/map?name='abc' & id='123'
@GetMapping(path = "/get/request/header/by/map")
public ResponseEntity<String> getRequestParamInMap(@RequestParam Map<String,String> map){
// Do your business here
return new ResponseEntity<String>(map.toString(),HttpStatus.OK);
}
Set both DATE_FORMAT
and USE_L10N
To make changes for the entire site in Django 1.4.1 add:
DATE_FORMAT = "Y-m-d"
to your settings.py
file and edit:
USE_L10N = False
since l10n overrides DATE_FORMAT
This is documented at: https://docs.djangoproject.com/en/dev/ref/settings/#date-format
I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt
performs faster than indexOf
or Regex
. The code and proof is available at JSPerf.
ETA: indexOf
and charAt
both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com
You can try too to put this into your ~/.vimrc
file:
colorscheme Solarized
I don't know ASP.NET very well, but can you use the ternary operator?
http://en.wikipedia.org/wiki/Ternary_operation
Something like: (x=Eval("item")) == Null ? 0 : x
It’s quite common to define navigational properties in a model to be virtual. When a navigation property is defined as virtual, it can take advantage of certain Entity Framework functionality. The most common one is lazy loading.
Lazy loading is a nice feature of many ORMs because it allows you to dynamically access related data from a model. It will not unnecessarily fetch the related data until it is actually accessed, thus reducing the up-front querying of data from the database.
From book "ASP.NET MVC 5 with Bootstrap and Knockout.js"
bool
is just a macro that expands to _Bool
. You can use _Bool
with no #include
very much like you can use int
or double
; it is a C99 keyword.
The macro is defined in <stdbool.h>
along with 3 other macros.
The macros defined are
bool
: macro expands to _Bool
false
: macro expands to 0
true
: macro expands to 1
__bool_true_false_are_defined
: macro expands to 1
if the string is mutable, then you can transform it in place using this form:
[string replaceOccurrencesOfString:@" "
withString:@""
options:0
range:NSMakeRange(0, string.length)];
this is also useful if you would like the result to be a mutable instance of an input string:
NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:@" "
withString:@""
options:0
range:NSMakeRange(0, string.length)];
I use this function as a universal solution:
function isPromise(value) {
return value && value.then && typeof value.then === 'function';
}
You can use closures to pass parameters:
iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);
However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):
document.getElementById("myFrame").contentDocument.addEventListener(...);
The selected answer did not work for me as Excel was still not converting the text to date. Here is my solution.
Say that in the first column, A, you have data of the type 2016/03/25 21:20:00
but is stored as text. Then in column B write =DATEVALUE(A1)
and in column C write =TIMEVALUE(A1)
.
Then in column D do =B1+C1
to add the numerical formats of the date and time.
Finally, copy the values from D into column E by right clicking in column E and select Paste Special -> Paste as Values
.
Highlight the numerical values in column E and change the data type to date - I prefer using a custom date of the form YYYY-MM-DD HH:MM:SS
.
Old question, but in case anyone sees this, the best answer in my opinion is to convert the video into an animated GIF. This gives you much more control and you can just treat it like an image. It's also the only way for it to work on mobile, since you can't autoplay videos. I know the question is asking to do it in an <img>
tag, but I don't really see the downside of using a <div>
and doing background-size: cover
Because this is related to something I was doing, I'll share here.
What if we're not sure if there's a header and you also don't feel like importing sniffer and other things?
If your task is basic, such as printing or appending to a list or array, you could just use an if statement:
# Let's say there's 4 columns
with open('file.csv') as csvfile:
csvreader = csv.reader(csvfile)
# read first line
first_line = next(csvreader)
# My headers were just text. You can use any suitable conditional here
if len(first_line) == 4:
array.append(first_line)
# Now we'll just iterate over everything else as usual:
for row in csvreader:
array.append(row)
date.toLocaleDateString('en-US')
works great. Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.
You can call controller and get the page content and you can show that in your modal.
below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...
index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function loadme(){
//alert("loadig");
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
}
</script>
</head>
<body>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body" id="contentBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
registration.html
--------------------
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {
border: 3px solid #f1f1f1;
font-family: Arial;
}
.container {
padding: 20px;
background-color: #f1f1f1;
width: 560px;
}
input[type=text], input[type=submit] {
width: 100%;
padding: 12px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
input[type=checkbox] {
margin-top: 16px;
}
input[type=submit] {
background-color: #4CAF50;
color: white;
border: none;
}
input[type=submit]:hover {
opacity: 0.8;
}
</style>
<body>
<h2>CSS Newsletter</h2>
<form action="/action_page.php">
<div class="container">
<h2>Subscribe to our Newsletter</h2>
<p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
</div>
<div class="container" style="background-color:white">
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
</label>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
</form>
</body>
</html>
This may or may not be a sub-optimal way of doing things, but the simplest solution to the multi-page problem I found was to ensure all rendering is done before calling the jsPDFObj.save method.
As for rendering hidden articles, this is solved with a similar fix to css image text replacement, I position absolutely the element to be rendered -9999px off the page left,
this doesn't affect layout and allows for the elem to be visible to html2pdf, especially when using tabs, accordions and other UI components that depend on {display: none}
.
This method wraps the prerequisites in a promise and calls pdf.save()
in the finally()
method. I cannot be sure that this is foolproof, or an anti-pattern, but it would seem that it works in most cases I have thrown at it.
// Get List of paged elements._x000D_
let elems = document.querySelectorAll('.elemClass');_x000D_
let pdf = new jsPDF("portrait", "mm", "a4");_x000D_
_x000D_
// Fix Graphics Output by scaling PDF and html2canvas output to 2_x000D_
pdf.scaleFactor = 2;_x000D_
_x000D_
// Create a new promise with the loop body_x000D_
let addPages = new Promise((resolve,reject)=>{_x000D_
elems.forEach((elem, idx) => {_x000D_
// Scaling fix set scale to 2_x000D_
html2canvas(elem, {scale: "2"})_x000D_
.then(canvas =>{_x000D_
if(idx < elems.length - 1){_x000D_
pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
pdf.addPage();_x000D_
} else {_x000D_
pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
console.log("Reached last page, completing");_x000D_
}_x000D_
})_x000D_
_x000D_
setTimeout(resolve, 100, "Timeout adding page #" + idx);_x000D_
})_x000D_
_x000D_
addPages.finally(()=>{_x000D_
console.log("Saving PDF");_x000D_
pdf.save();_x000D_
});
_x000D_
If you have multiple columns in your dataframe and would like to remove all rows that have outliers in at least one column, the following expression would do that in one shot.
df = pd.DataFrame(np.random.randn(100, 3))
from scipy import stats
df[(np.abs(stats.zscore(df)) < 3).all(axis=1)]
description:
zscore
, df[0]
for example, and remove .all(axis=1)
.df[(np.abs(stats.zscore(df[0])) < 3)]
If you are using AndroidX, use below code to check Location Service is enabled or not:
fun isNetworkServiceEnabled(context: Context) = LocationManagerCompat.isLocationEnabled(context.getSystemService(LocationManager::class.java))
Though static keyword not supported in interface in Typescript
but we can achieve it by creating a function interface
that has static member.
In my following code I have created a function interface Factory
that has two static members serialNumber
and printSerial.
// factory is a function interface
interface Factory<T> {
(name: string, age: number): T;
//staic property
serialNumber: number;
//static method
printSrial: () => void;
}
class Dog {
constructor(public name: string, public age: number) { }
}
const dogFactory: Factory<Dog> = (name, age) => {
return new Dog(name, age);
}
// initialising static members
dogFactory.serialNumber = 1234;
dogFactory.printSrial = () => console.log(dogFactory.serialNumber);
//instance of Dog that DogFactory creates
const myDog = dogFactory("spike", 3);
//static property that returns 1234
console.log(dogFactory.serialNumber)
//static method that prints the serial 1234
dogFactory.printSrial();
In ASP.net MVC, you can use a FileContentResult
and the File
method:
public FileContentResult DownloadManifest() {
byte[] csvData = getCsvData();
return File(csvData, "text/csv", "filename.csv");
}
I didn't want to disable notice because it's helpful, but wanted to avoid too much typing.
My solution was this function:
function ifexists($varname)
{
return(isset($$varname)?$varname:null);
}
So if I want to reference to $name and echo if exists, I simply write:
<?=ifexists('name')?>
For array elements:
function ifexistsidx($var,$index)
{
return(isset($var[$index])?$var[$index]:null);
}
In page if I want to refer to $_REQUEST['name']:
<?=ifexistsidx($_REQUEST,'name')?>
Creating Custom ProgressBar like hotstar.
activity_main.xml
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/player_progressbar"
android:indeterminateDrawable="@drawable/custom_progress_bar"
/>
custom_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="1080" >
<shape
android:innerRadius="35dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false" >
<size
android:height="80dp"
android:width="80dp" />
<gradient
android:centerColor="#80b7b4b2"
android:centerY="0.5"
android:endColor="#f4eef0"
android:startColor="#00938c87"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].
Here is an in-place quicksort in Swift Beta:
func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
if (end - start < 2){
return
}
var p = a[start + (end - start)/2]
var l = start
var r = end - 1
while (l <= r){
if (a[l] < p){
l += 1
continue
}
if (a[r] > p){
r -= 1
continue
}
var t = a[l]
a[l] = a[r]
a[r] = t
l += 1
r -= 1
}
quicksort_swift(&a, start, r + 1)
quicksort_swift(&a, r + 1, end)
}
And the same in C:
void quicksort_c(int *a, int n) {
if (n < 2)
return;
int p = a[n / 2];
int *l = a;
int *r = a + n - 1;
while (l <= r) {
if (*l < p) {
l++;
continue;
}
if (*r > p) {
r--;
continue;
}
int t = *l;
*l++ = *r;
*r-- = t;
}
quicksort_c(a, r - a + 1);
quicksort_c(l, a + n - l);
}
Both work:
var a_swift:CInt[] = [0,5,2,8,1234,-1,2]
var a_c:CInt[] = [0,5,2,8,1234,-1,2]
quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))
// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]
Both are called in the same program as written.
var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
x_swift[i] = CInt(random())
x_c[i] = CInt(random())
}
let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)
let swift_stop:UInt64 = mach_absolute_time();
let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();
This converts the absolute times to seconds:
static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;
mach_timebase_info_data_t timebase_info;
uint64_t abs_to_nanos(uint64_t abs) {
if ( timebase_info.denom == 0 ) {
(void)mach_timebase_info(&timebase_info);
}
return abs * timebase_info.numer / timebase_info.denom;
}
double abs_to_seconds(uint64_t abs) {
return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}
Here is a summary of the compiler's optimazation levels:
[-Onone] no optimizations, the default for debug.
[-O] perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.
Time in seconds with [-Onone] for n=10_000:
Swift: 0.895296452
C: 0.001223848
Here is Swift's builtin sort() for n=10_000:
Swift_builtin: 0.77865783
Here is [-O] for n=10_000:
Swift: 0.045478346
C: 0.000784666
Swift_builtin: 0.032513488
As you can see, Swift's performance improved by a factor of 20.
As per mweathers' answer, setting [-Ofast] makes the real difference, resulting in these times for n=10_000:
Swift: 0.000706745
C: 0.000742374
Swift_builtin: 0.000603576
And for n=1_000_000:
Swift: 0.107111846
C: 0.114957179
Swift_sort: 0.092688548
For comparison, this is with [-Onone] for n=1_000_000:
Swift: 142.659763258
C: 0.162065333
Swift_sort: 114.095478272
So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.
It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:
A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.
They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance and overflow checks / precise arithmetic then choose another language for now.
BETA 3 UPDATE:
n=10_000 with [-O]:
Swift: 0.019697268
C: 0.000718064
Swift_sort: 0.002094721
Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.
FINAL UPDATE:
[-Onone]:
Swift: 0.678056695
C: 0.000973914
[-O]:
Swift: 0.001158492
C: 0.001192406
[-Ounchecked]:
Swift: 0.000827764
C: 0.001078914
Code To insert Data in Access Db using c#
Code:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace access_db_csharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public SqlConnection con = new SqlConnection(@"Place Your connection string");
private void Savebutton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
con.ConnectionString = connectionstring;
con.Open();
}
}
}
You can pass lists just like other types:
l = [1,2,3]
def stuff(a):
for x in a:
print a
stuff(l)
This prints the list l. Keep in mind lists are passed as references not as a deep copy.
RMI is based on Proxy.
Should be possible to cite one for most of the 23 patterns in GoF:
I can't think of examples in Java for 10 out of the 23, but I'll see if I can do better tomorrow. That's what edit is for.
I had the same problem, after loads of research and Googling, I found the following solution worked best for me! plenty of trial and error went into this one.
--- SOLVED / SOLUTION ---
JS
$(document).ready(function() {
$("header").delay(5000).queue(function(){
$(this).css({"background-image":"url(<?php bloginfo('template_url') ?>/img/header-boy-hover.jpg)"});
});
});
CSS
header {
-webkit-transition:all 1s ease-in;
-moz-transition:all 1s ease-in;
-o-transition:all 1s ease-in;
-ms-transition:all 1s ease-in;
transition:all 1s ease-in;
}
Include the type specifier in your format expression:
>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
Do you mean these hex values?
.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
...
You can find these in glyphicons.css
here:
http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css
(If you only want to know the Glyphicons classes: http://getbootstrap.com/components/#glyphicons)
What I learn about promises is to use it only as return values avoid referencing them if possible. async/await syntax is particularly practical for that. Today all latest browsers and node support it: https://caniuse.com/#feat=async-functions , is a simple behavior and the code is like reading synchronous code, forget about callbacks...
In cases I do need to reference a promises is when creation and resolution happen at independent/not-related places. So instead an artificial association and probably an event listener just to resolve the "distant" promise, I prefer to expose the promise as a Deferred, which the following code implements it in valid es5
/**
* Promise like object that allows to resolve it promise from outside code. Example:
*
```
class Api {
fooReady = new Deferred<Data>()
private knower() {
inOtherMoment(data=>{
this.fooReady.resolve(data)
})
}
}
```
*/
var Deferred = /** @class */ (function () {
function Deferred(callback) {
var instance = this;
this.resolve = null;
this.reject = null;
this.status = 'pending';
this.promise = new Promise(function (resolve, reject) {
instance.resolve = function () { this.status = 'resolved'; resolve.apply(this, arguments); };
instance.reject = function () { this.status = 'rejected'; reject.apply(this, arguments); };
});
if (typeof callback === 'function') {
callback.call(this, this.resolve, this.reject);
}
}
Deferred.prototype.then = function (resolve) {
return this.promise.then(resolve);
};
Deferred.prototype.catch = function (r) {
return this.promise.catch(r);
};
return Deferred;
}());
transpiled form a typescript project of mine:
For more complex cases I often use these guy small promise utilities without dependencies tested and typed. p-map has been useful several times. I think he covered most use cases:
https://github.com/sindresorhus?utf8=%E2%9C%93&tab=repositories&q=promise&type=source&language=
#$computerList = "Server Name"
#$regVar = "Name of the package "
#$packageName = "Packe name "
$computerList = $args[0]
$regVar = $args[1]
$packageName = $args[2]
foreach ($computer in $computerList)
{
Write-Host "Connecting to $computer...."
Invoke-Command -ComputerName $computer -Authentication Kerberos -ScriptBlock {
param(
$computer,
$regVar,
$packageName
)
Write-Host "Connected to $computer"
if ([IntPtr]::Size -eq 4)
{
$registryLocation = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\"
Write-Host "Connected to 32bit Architecture"
}
else
{
$registryLocation = Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"
Write-Host "Connected to 64bit Architecture"
}
Write-Host "Finding previous version of `enter code here`$regVar...."
foreach ($registryItem in $registryLocation)
{
if((Get-itemproperty $registryItem.PSPath).DisplayName -match $regVar)
{
Write-Host "Found $regVar" (Get-itemproperty $registryItem.PSPath).DisplayName
$UninstallString = (Get-itemproperty $registryItem.PSPath).UninstallString
$match = [RegEx]::Match($uninstallString, "{.*?}")
$args = "/x $($match.Value) /qb"
Write-Host "Uninstalling $regVar...."
[diagnostics.process]::start("msiexec", $args).WaitForExit()
Write-Host "Uninstalled $regVar"
}
}
$path = "\\$computer\Msi\$packageName"
Write-Host "Installaing $path...."
$args = " /i $path /qb"
[diagnostics.process]::start("msiexec", $args).WaitForExit()
Write-Host "Installed $path"
} -ArgumentList $computer, $regVar, $packageName
Write-Host "Deployment Complete"
}
Whenever you want to convert a String to Date object then use SimpleDateFormat#parse
Try to use
String dateInString = new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
.format(cal.getTime())
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss");
Date parsedDate = formatter.parse(dateInString);
.Additional thing is if you want to convert a Date
to String
then you should use SimpleDateFormat#format
function.
Now the Point for you is
new Date(String)
is deprecated and not recommended now.Now whenever anyone wants to parse , then he/she should use SimpleDateFormat#parse
.
refer the official doc for more Date and Time Patterns used in SimpleDateFormat options.
The "why" is to avoid accidental fall-through, for which I'm grateful. This is a not uncommon source of bugs in C and Java.
The workaround is to use goto, e.g.
switch (number.ToString().Length)
{
case 3:
ans += string.Format("{0} hundred and ", numbers[number / 100]);
goto case 2;
case 2:
// Etc
}
The general design of switch/case is a little bit unfortunate in my view. It stuck too close to C - there are some useful changes which could be made in terms of scoping etc. Arguably a smarter switch which could do pattern matching etc would be helpful, but that's really changing from switch to "check a sequence of conditions" - at which point a different name would perhaps be called for.
For the 10 MB memory constraint:
When finished, just take a path that has not been created before to create the requested number.
4 billion number = 2^32, meaning 10 MB might not be sufficient.
EDIT
An optimization is possible, if two ends leafs have been created and have a common parent, then they can be removed and the parent flagged as not a solution. This cuts branches and reduces the need for memory.
EDIT II
There is no need to build the tree completely too. You only need to build deep branches if numbers are similar. If we cut branches too, then this solution might work in fact.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
Example for String Methods
Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
if i.endswith(".hpp"):
x = i.replace("hpp", "h")
newfilenames.append(x)
else:
newfilenames.append(i)
print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
thank you, your first error guides me here and the solution solve mine too!
for permission error, f = open('output', 'w+')
, change it into f = open(output+'output', 'w+')
.
or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.
for sure, you could probably running python/your script as administrator to pass permission error though
Oxi's answer is just wrong.¹
What you want is:
var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;
Working example:
(function (){
var i = 20, l = 20, html = '';
while (i--){
html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
html += '[ Scroll to #DIV' +i+ ' ]</a>';
html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
}
document.write( html );
})();
¹ I haven't got enough reputation to comment on his answer
svick's answer is (as usual) excellent.
However, I find Dataflow to be more useful when you actually have large amounts of data to transfer. Or when you need an async
-compatible queue.
In your case, a simpler solution is to just use the async
-style parallelism:
var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var customerTasks = ids.Select(i =>
{
ICustomerRepo repo = new CustomerRepo();
return repo.GetCustomer(i);
});
var customers = await Task.WhenAll(customerTasks);
foreach (var customer in customers)
{
Console.WriteLine(customer.ID);
}
Console.ReadKey();
At least some versions of SQL (Oracle, Informix, DB2, ISO Standard) support:
WHERE MOD(value, 2) = 1
MySQL supports '%' as the modulus operator:
WHERE value % 2 = 1
Neither the question nor the answers really fit my simple way of thinking about it. I'm a consultant and have synchronized these definitions with a number of Dev teams and DevOps people, but am curious about how it matches with the industry at large:
Basically I think of the agile practice of continuous delivery like a continuum:
Not continuous (everything manual) 0% ----> 100% Continuous Delivery of Value (everything automated)
Steps towards continuous delivery:
Zero. Nothing is automated when devs check in code... You're lucky if they have compiled, run, or performed any testing prior to check-in.
Continuous Build: automated build on every check-in, which is the first step, but does nothing to prove functional integration of new code.
Continuous Integration (CI): automated build and execution of at least unit tests to prove integration of new code with existing code, but preferably integration tests (end-to-end).
Continuous Deployment (CD): automated deployment when code passes CI at least into a test environment, preferably into higher environments when quality is proven either via CI or by marking a lower environment as PASSED after manual testing. I.E., testing may be manual in some cases, but promoting to next environment is automatic.
Continuous Delivery: automated publication and release of the system into production. This is CD into production plus any other configuration changes like setup for A/B testing, notification to users of new features, notifying support of new version and change notes, etc.
EDIT: I would like to point out that there's a difference between the concept of "continuous delivery" as referenced in the first principle of the Agile Manifesto (http://agilemanifesto.org/principles.html) and the practice of Continuous Delivery, as seems to be referenced by the context of the question. The principle of continuous delivery is that of striving to reduce the Inventory waste as described in Lean thinking (http://www.miconleansixsigma.com/8-wastes.html). The practice of Continuous Delivery (CD) by agile teams has emerged in the many years since the Agile Manifesto was written in 2001. This agile practice directly addresses the principle, although they are different things and apparently easily confused.
cgi.escape
extendedThis version improves cgi.escape
. It also preserves whitespace and newlines. Returns a unicode
string.
def escape_html(text):
"""escape strings for display in HTML"""
return cgi.escape(text, quote=True).\
replace(u'\n', u'<br />').\
replace(u'\t', u' ').\
replace(u' ', u' ')
>>> escape_html('<foo>\nfoo\t"bar"')
u'<foo><br />foo "bar"'
Taking advantage of str.split's behavior with no sep parameter:
>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'
If you just want to remove spaces instead of all whitespace:
>>> s.replace(" ", "")
'\tfoo\nbar'
Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:
$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop
Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:
$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop
Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.
One other thing. You may need to specify the -L option as well - eg
-Wl,-rpath,/path/to/foo -L/path/to/foo -lbaz
or you may end up with an error like
ld: cannot find -lbaz
As the other answers said, the function you need is cv2.rectangle()
, but keep in mind that the coordinates for the bounding box vertices need to be integers if they are in a tuple, and they need to be in the order of (left, top)
and (right, bottom)
. Or, equivalently, (xmin, ymin)
and (xmax, ymax)
.
You can use a JSON as well to store and send JS functions.
Check the following:
var myJSON =
{
"myFunc1" : function (){
alert("a");
},
"myFunc2" : function (functionParameter){
functionParameter();
}
}
function main(){
myJSON.myFunc2(myJSON.myFunc1);
}
This will print 'a'.
The following has the same effect with the above:
var myFunc1 = function (){
alert('a');
}
var myFunc2 = function (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
Which is also has the same effect with the following:
function myFunc1(){
alert('a');
}
function myFunc2 (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
And a object paradigm using Class as object prototype:
function Class(){
this.myFunc1 = function(msg){
alert(msg);
}
this.myFunc2 = function(callBackParameter){
callBackParameter('message');
}
}
function main(){
var myClass = new Class();
myClass.myFunc2(myClass.myFunc1);
}
I have just written a blog article that addresses exactly this, which you may find useful: http://seewah.blogspot.com/2009/10/circle-overlay-on-google-map.html
Basically, you need to create a GGroundOverlay with the correct GLatLngBounds. The tricky bit is in working out the southwest corner coordinate and the northeast corner coordinate of this imaginery square (the GLatLngBounds) bounding this circle, based on the desired radius. The math is quite complicated, but you can just refer to getDestLatLng function in the blog. The rest should be pretty straightforward.
public enum NewEnum {
ONE("test"),
TWO("test");
private String s;
private NewEnum(String s) {
this.s = s);
}
public String getS() {
return this.s;
}
}
How about making the <div id="mainWrapperDivWithBGImage">
as three divs, where the two outside divs hold the rounded corners images, and the middle div simply has a background-color to match the rounded corner images. Then you could simply place the other elements inside the middle div, or:
#outside_left{width:10px; float:left;}
#outside_right{width:10px; float:right;}
#middle{background-color:#color of rnd_crnrs_foo.gif; float:left;}
Then
HTML:
<div id="mainWrapperDivWithBGImage">
<div id="outside_left><img src="rnd_crnrs_left.gif" /></div>
<div id="middle">
<div id="another_div"><img src="foo.gif" /></div>
<div id="outside_right><img src="rnd_crnrs_right.gif" /></div>
</div>
You may have to do position:relative; and such.
If you think you'll be using more than 1 db for any reason, go with the variable because you'll be able to change one parameter to switch to an entirely different db. I.e. for testing , autobackup, etc.
You can just do it like this:
#content {
position: relative;
}
#content img {
position: absolute;
top: 0px;
right: 0px;
}
<div id="content">
<img src="images/ribbon.png" class="ribbon"/>
<div>some text...</div>
</div>
simple
COPY README.md package.json gulpfile.js __BUILD_NUMBER ./
from the doc
If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.
Most of the times it should not be used as the primary key for a table because it really hit the performance of the database. useful links regarding GUID impact on performance and as a primary key.
None of the answers helped in my situation. If you are developing for Windows, you likely don't have svn. In many situations one can't count on users to have Git installed either, or don't want to download entire repositories for other reasons. Some of the people that answered this question, such as Willem van Ketwich and aztack, made tools to accomplish this task. However, if the tool isn't written for the language you are using, or you don't want to install a third party library, these don't work.
However, there is a much easier way. GitHub has an API that allows you to download a single file or an entire directory's contents using GET requests. You can access a directory using https://api.github.com/repos/:owner/:repo_name/contents/:path
that returns a JSON object enumerating all the files in the directory. Included in the enumeration is a link to the raw content of the file, the download_url
parameter. The file can then be downloaded using that URL.
It's a two step process that requires the ability to make GET requests, but this can be implemented in pretty much any language, on any platform. It can be used to get files or directories.
To avoid the TOCTOU issue highlighted by Éric Araujo's comment, you can catch an exception to call the correct method:
def remove_file_or_dir(path: str) -> None:
""" Remove a file or directory """
try:
shutil.rmtree(path)
except NotADirectoryError:
os.remove(path)
Since shutil.rmtree()
will only remove directories and os.remove()
or os.unlink()
will only remove files.
I know it's not for everyone but: why not to do a graceful Apache restart?
For e.g. in case of Centos/RedHat Linux:
sudo service httpd graceful
Ubuntu:
sudo service apache2 graceful
Google's Guava library handles this in the IntMath class:
IntMath.divide(numerator, divisor, RoundingMode.CEILING);
Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.
It depends on the context. For the content, it is < and &, and ]]> (though a string of three instead of one character).
For attribute values, it is <, &, ", and '.
For CDATA, it is ]]>.
the solution:
at >nul
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )
does not work under Windows 10
for all versions of Windows can be do so:
openfiles >nul 2>&1
if %ErrorLevel% equ 0 ( echo Administrator ) else ( echo NOT Administrator )
Functionally the same as rinku's answer but with IDE warning prevention
numericOnly(event): boolean {
// noinspection JSDeprecatedSymbols
const charCode = (event.which) ? event.which : event.key || event.keyCode; // keyCode is deprecated but needed for some browsers
return !(charCode === 101 || charCode === 69 || charCode === 45 || charCode === 43);
}
The warning message
[WARNING] The requested profile "pom.xml" could not be activated because it does not exist.
means that you somehow passed -P pom.xml
to Maven which means "there is a profile called pom.xml
; find it and activate it". Check your environment and your settings.xml
for this flag and also look at all <profile>
elements inside the various XML files.
Usually, mvn help:effective-pom
is also useful to see what the real POM would look like.
Now the error means that you tried to configure Maven to build Java 8 code but you're not using a Java 8 runtime. Solutions:
JAVA_HOME
is your friendpom.xml
to a Java version which you actually have.Related: