This not something that is usually done, so I would reconsider. But having said that, the fundamental operations are: int --> enum using EnumType.values()[intNum], and enum --> int using enumInst.ordinal().
However, since any implementation of values() has no choice but to give you a copy of the array (java arrays are never read-only), you would be better served using an EnumMap to cache the enum --> int mapping.
There is nothing in JDK to do this.
static String[] suffixes =
// 0 1 2 3 4 5 6 7 8 9
{ "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
// 10 11 12 13 14 15 16 17 18 19
"th", "th", "th", "th", "th", "th", "th", "th", "th", "th",
// 20 21 22 23 24 25 26 27 28 29
"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
// 30 31
"th", "st" };
Date date = new Date();
SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d");
int day = Integer.parseInt(formatDateOfMonth.format(date));
String dayStr = day + suffixes[day];
Or using Calendar:
Calendar c = Calendar.getInstance();
c.setTime(date);
int day = c.get(Calendar.DAY_OF_MONTH);
String dayStr = day + suffixes[day];
Per comments by @thorbjørn-ravn-andersen, a table like this can be helpful when localizing:
static String[] suffixes =
{ "0th", "1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th",
"10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th",
"20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th",
"30th", "31st" };
Pointing to Best Practices for Using Strings in the .NET Framework:
StringComparison.Ordinal
or StringComparison.OrdinalIgnoreCase
for comparisons as your safe default for culture-agnostic string matching.StringComparison.Ordinal
or StringComparison.OrdinalIgnoreCase
for better performance.StringComparison.Ordinal
or StringComparison.OrdinalIgnoreCase
values instead of string operations based on CultureInfo.InvariantCulture
when the comparison is linguistically irrelevant (symbolic, for example).And finally:
StringComparison.InvariantCulture
in most cases. One of the few exceptions is when you are persisting linguistically meaningful but culturally agnostic data.If you configure your gitconfig with this option, you will later have a problem cloning other repos of GitHub
git config --global --add url. "[email protected]". Instead, "https://github.com/"
Instead, I recommend that you use this option
echo "export GIT_TERMINAL_PROMPT=1" >> ~/.bashrc || ~/.zshrc
and do not forget to generate an access token from your private repository. When prompted to enter your password, just paste the access token. Happy clone :)
To see a list of the Eclipse release name and it's corresponding version number go to this website. http://en.wikipedia.org/wiki/Eclipse_%28software%29#Release
I too dislike the way that the Eclipse foundation DOES NOT use the version number for their downloads or on the Help -> About Eclipse dialog. They do display the version on the download webpage, but the actual file name is something like:
But over time, you forget what release name goes with what version number. I would much prefer a file naming convention like:
This way you get BOTH from the file name and it is sortable in a directory listing. Fortunately, they mostly choose names are alphabetically after the previous one (except for 3.4-Ganymede vs the newer 3.5-Galileo).
Ryan, I am changing this to be an answer instead of a comment, since it appears I was too brief. Do all of this in "Terminal".
To use the G++ compiler, you need to do this:
Navigate to the directory in which you stored the *.cpp file.
cd ~/programs/myprograms/
(the ~ is a shortcut for your home, i.e. /Users/Ryan/programs/myprograms/, replace with the location you actually used.)
Compile it
g++ input.cpp -o output.bin
(output.bin can be anything with any extension, really. bin is just common on unix.)
There should be NOTHING returned if it was successful, and that is okay. Generally you get returns on failures.
However, if you type ls
, you will see the list of files in the same directory. For example you would see the other folders, input.cpp and output.bin
From inside the directory, now execute it with ./outbut.bin
I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.
Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.
In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.
Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.
For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :
20/2 = 10
10/2 = 5
Hence our answer is 5 + 1 + 1 = 7
. (The 1 + 1 because we divided the number 20 twice).
The __dict__
property of the object is a dictionary of all its other defined properties. Note that Python classes can override getattr
and make things that look like properties but are not in__dict__
. There's also the builtin functions vars()
and dir()
which are different in subtle ways. And __slots__
can replace __dict__
in some unusual classes.
Objects are complicated in Python. __dict__
is the right place to start for reflection-style programming. dir()
is the place to start if you're hacking around in an interactive shell.
To Write
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\listfile.txt",2,true)
objFileToWrite.WriteLine(data)
objFileToWrite.Close
Set objFileToWrite = Nothing
OpenTextFile parameters:
<filename>, IOMode (1=Read,2=write,8=Append), Create (true,false), Format (-2=System Default,-1=Unicode,0=ASCII)
To Read the entire file
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\listfile.txt",1)
strFileText = objFileToRead.ReadAll()
objFileToRead.Close
Set objFileToRead = Nothing
To Read line by line
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\listfile.txt",1)
Dim strLine
do while not objFileToRead.AtEndOfStream
strLine = objFileToRead.ReadLine()
'Do something with the line
loop
objFileToRead.Close
Set objFileToRead = Nothing
I had a similar error type. First, I tried to add the meta tags in the code, but it didn't work.
I found out that on the nginx web server you may have a security setting that may block external code to run:
# Security directives
server_tokens off;
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ajax.googleapis.com https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://assets.zendesk.com; font-src 'self' https://fonts.gstatic.com https://themes.googleusercontent.com; frame-src https://player.vimeo.com https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";
Check the Content-Security-Policy. You may need to add the source reference.
the point is that in toad u have to write table name capital, like this:
select *
FROM all_tab_columns
where table_name like 'IDECLARATION';
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
If you mean a minimal form, go with this:
if (not a or not b or not c) and (a or b or c):
Which translates the title of your question.
UPDATE: as correctly said by Volatility and Supr, you can apply De Morgan's law and obtain equivalent:
if (a or b or c) and not (a and b and c):
My advice is to use whichever form is more significant to you and to other programmers. The first means "there is something false, but also something true", the second "There is something true, but not everything". If I were to optimize or do this in hardware, I would choose the second, here just choose the most readable (also taking in consideration the conditions you will be testing and their names). I picked the first.
These steps worked for me.
You can use sp_rename
to rename a column.
USE YourDatabase;
GO
EXEC sp_rename 'TableName.OldColumnName', 'NewColumnName', 'COLUMN';
GO
The first parameter is the object to be modified, the second parameter is the new name that will be given to the object, and the third parameter COLUMN informs the server that the rename is for the column
, and can also be used to rename tables
, index
and alias data type
.
As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):
public function parent(){
return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}
and if you want to have all of children IDs as an Array , This approach is fine and working for me :
public function allChildren()
{
$allChildren = [];
if ($this->has_branch) {
foreach ($this->children as $child) {
$subChildren = $child->allChildren();
if (count($subChildren) == 1) {
$allChildren [] = $subChildren[0];
} else if (count($subChildren) > 1) {
$allChildren += $subChildren;
}
}
}
$allChildren [] = $this->id;//adds self Id to children Id list
return $allChildren;
}
the allChildren() returns , all of childrens as a simple Array .
Here's a list of the environment variables. I think you might want CURRENT_VARIANT
. See also BUILD_VARIANTS
.
Java is faster than Python. Easily.
Python is favorable for many things; speed isn't necessarily one of them.
var audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
base64data = reader.result;
console.log(base64data);
}
It should be like:
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
Explanation:
TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours with out consideration for days. Minus the hours for days you already got i.e, day*24. You now got remaining hours. Same for minute and second. You need to minus the already got hour and minutes respectively.
One could also use the JQuery filter for objects
var newobj = $(obj).filter(function(key) {
return $(this)[key]!== undefined;
})[0];
Demo here
I have subscribed to quite a few podcasts but the ones I try and listen to weekly are:
I have a 35 minute commute to work each morning (bus) and I like watching the Channel 9 feed on my zune.
SELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias
Or more idiomatic:
SELECT coalesce(field, 'Empty') AS field_alias
I struggled a lot with something similar. Try the following:
If this doesn't help, take a look at this article. It's on PHP, but it describes exactly which headers must be set to which values for CORS to work.
In addition to solutions proposed, and in case you have a 1D range to 1D array, i prefer to process it through a function like below. The reason is simple: If for any reason your range is reduced to 1 element range, as far as i know the command Range().Value will not return a variant array but just a variant and you will not be able to assign a variant variable to a variant array (previously declared).
I had to convert a variable size range to a double array, and when the range was of 1 cell size, i was not able to use a construct like range().value so i proceed with a function like below.
Public Function Rng2Array(inputRange As Range) As Double()
Dim out() As Double
ReDim out(inputRange.Columns.Count - 1)
Dim cell As Range
Dim i As Long
For i = 0 To inputRange.Columns.Count - 1
out(i) = inputRange(1, i + 1) 'loop over a range "row"
Next
Rng2Array = out
End Function
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
Way simplest: copy and paste this into Terminal (but be sure to read more first):
bash <(curl -Ls http://git.io/eUx7rg)
This will install and configure everything automagically. The script is provided by MacMiniVault and is available on Github. More information about the mySQL install script on http://www.macminivault.com/mysql-yosemite/.
The two code snippets you've posted there will, for almost all purposes, behave the same way.
However, the difference in behaviour is that with the first variant (var functionOne = function() {}
), that function can only be called after that point in the code.
With the second variant (function functionTwo()
), the function is available to code that runs above where the function is declared.
This is because with the first variant, the function is assigned to the variable foo
at run time. In the second, the function is assigned to that identifier, foo
, at parse time.
More technical information
JavaScript has three ways of defining functions.
eval()
, which has its problems.This likely has very little to do with Laravel and everything to do with your Apache configs.
Do you have access to your Apache server config? If so, check this out, from the docs:
In general, you should only use .htaccess files when you don't have access to the main server configuration file. There is, for example, a common misconception that user authentication should always be done in .htaccess files, and, in more recent years, another misconception that mod_rewrite directives must go in .htaccess files. This is simply not the case. You can put user authentication configurations in the main server configuration, and this is, in fact, the preferred way to do things. Likewise, mod_rewrite directives work better, in many respects, in the main server configuration.
... In general, use of .htaccess files should be avoided when possible. Any configuration that you would consider putting in a .htaccess file, can just as effectively be made in a section in your main server configuration file.
Source: Apache documentation.
The reason why I mention this first is because it is best to get rid of .htaccess
completely if you can,and use a Directory
tag inside a VirtualHost
tag. That being said, the rest of this is going to assume you are sticking with the .htaccess
route for whatever reason.
To break this down, a couple things could be happening:
I note, perhaps pointlessly, that your file is named .htacces
in your question. My guess is that it is a typo but on the off chance you overlooked it and it is in fact just missing the second s, this is exactly the sort of minor error that would leave me banging my head against the wall looking for something more challenging.
Your server could not be allowing .htaccess
. To check this, go to your Apache configuration file. In modern Apache builds this is usually not in one config file so make sure you're using the one that points to your app, wherever it exists. Change
AllowOverride none
to
AllowOverride all
As a followup, the Apache documents also recommend that, for security purposes, you don't do this for every folder if you are going to go for .htaccess
for rewriting. Instead, do it for the folders you need to add .htaccess
to.
Do you have mod_rewrite
enabled? That could be causing the issues. I notice you have the tag at the top <IfModule mod_rewrite.c>
. Try commenting out those tags and restart Apache. If you get an error then it is probably because you need to enable mod_rewrite
:
How to enable mod_rewrite for Apache 2.2
Hope this helps. I've named some of the most common issues but there are several others that could be more mundane or unique. Another suggestion on a dev server? Re-install Apache. If possible, do so from a different source with a good tutorial.
Say if you have an application which has similar functionality as that of mine. Where your app is mostly offline and you want to render the Images one after the other. Then below is the approach that worked for me in React Native version 0.60.
const Images = { 'image1': require('./1.png'), 'image2': require('./2.png'), 'image3': require('./3.png') }
import React from 'react'; import { Image, Dimensions } from 'react-native'; import Images from './Index'; const ImageView = ({ index }) => { return ( <Image source={Images['image' + index]} /> ) } export default ImageView;
Now from the component wherever you want to render the Static Images dynamically, just use the ImageView component and pass the index.
< ImageView index={this.qno + 1} />
Basically a modified syntax of function declaration/definitions:
a2dd.h
class A2DD
{
private:
int gx;
int gy;
public:
A2DD(int x,int y);
int getSum();
};
a2dd.cpp
A2DD::A2DD(int x,int y)
{
gx = x;
gy = y;
}
int A2DD::getSum()
{
return gx + gy;
}
Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.
private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);
public static Document loadXMLFrom(String xml) throws Exception {
InputSource is= new InputSource(new StringReader(xml));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
return doc;
}
As we were already using jQuery for a graphical eye-candy feature we ended up using this. A code like
$(document).ready(function() {
// any code goes here
init();
});
did everything we wanted and cares about browser incompatibilities at its own.
A bit more detail to Joachim Sauer's answer:
On Ubuntu at least, the metapackage tomcat6
depends on metapackage tomcat6-common
(and others), which depends on metapackage libtomcat6-java
, which depends on package libservlet2.5-java
(and others). It contains, among others, the files /usr/share/java/servlet-api-2.5.jar
and /usr/share/java/jsp-api-2.1.jar
, which are the servlet and JSP libraries you need. So if you've installed Tomcat 6 through apt-get or the Ubuntu Software Centre, you already have the libraries; all that's left is to get Tomcat to use them in your project.
Place libraries /usr/share/java/servlet-api-2.5.jar
and /usr/share/java/jsp-api-2.1.jar
on the class path like this:
For all projects, by configuring Eclipse by selecting Window -> Preferences -> Java -> Installed JREs, then selecting the JRE you're using, pressing Edit, then pressing Add External JARs, and then by selecting the files from the locations given above.
For just one project, by right-clicking on the project in the Project Explorer pane, then selecting Properties -> Java Build Path, and then pressing Add External JARs, and then by selecting the files from the locations given above.
Further note 1: These are the correct versions of those libraries for use with Tomcat 6; for the other Tomcat versions, see the table on page http://tomcat.apache.org/whichversion.html, though I would suppose each Tomcat version includes the versions of these libraries that are appropriate for it.
Further note 2: Package libservlet2.5-java
's description (dpkg-query -s libservlet2.5-java
) says: 'Apache Tomcat implements the Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystems, and provides a "pure Java" HTTP web server environment for Java code to run. This package contains the Java Servlet and JSP library.'
There are a lot of interesting answers here and in similar questions. The only things that I can add from personal experience are:
Put your audit table in another database. Ideally, you want separation from the original data. If you need to restore your database, you don't really want to restore the audit trail.
Denormalize as much as reasonably possible. You want the table to have as few dependencies as possible to the original data. The audit table should be simple and lightning fast to retrieve data from. No fancy joins or lookups across other tables to get to the data.
From your Activity
, just pass in this
as the Context
for your layout:
ProfileView pv = new ProfileView(this, null, temp, tempPd);
Afterwards you will have a Context
in the layout, but you will know it is actually your Activity
and you can cast it so that you have what you need:
Activity activity = (Activity) context;
The best way around this is (and many other situations) in my experience, is to use cntlm which is a local no-authentication proxy which points to a remote authentication proxy. You can then just set WinHTTP to point to your local CNTLM (usually localhost:3128), and you can set CNTLM itself to point to the remote authentication proxy. CNTLM has a "magic NTLM dialect detection" option which generates password hashes to be put into the CNTLM configuration files.
Try checking the IsDisposed property before accessing the control. You can also check it on the FormClosing event, assuming you're using the FormClosed event.
We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.
Calling GC.Collect before checking IsDisposed may help, but be careful with this. Read this article by Rico Mariani "When to call GC.Collect()".
To find IP address list I have used this solution
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
But I personally like below solution to get local valid IP address
public static IPAddress GetIPAddress(string hostName)
{
Ping ping = new Ping();
var replay = ping.Send(hostName);
if (replay.Status == IPStatus.Success)
{
return replay.Address;
}
return null;
}
public static void Main()
{
Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
Console.WriteLine("Google IP:" + GetIPAddress("google.com");
Console.ReadLine();
}
Updating Sven Marnach's answer to work in Python 3.4:
row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
print(row_format.format(team, *row))
I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>
in .Net 3.5 and after you could use the activator class:
(T)Activator.CreateInstance(typeof(T), args)
import org.apache.commons.io.filefilter.WildcardFileFilter;
.........
.........
File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);
The code above works great for me
update as you loading contents dynamically so you use.
$(document).on('click', 'span', function () {
alert(this.id);
});
old code
$('span').click(function(){
alert(this.id);
});
or you can use .on
$('span').on('click', function () {
alert(this.id);
});
this
refers to current span element clicked
this.id
will give the id
of the current span clicked
function getalllinks($url) {
$links = array();
if ($fp = fopen($url, 'r')) {
$content = '';
while ($line = fread($fp, 1024)) {
$content. = $line;
}
}
$textLen = strlen($content);
if ($textLen > 10) {
$startPos = 0;
$valid = true;
while ($valid) {
$spos = strpos($content, '<a ', $startPos);
if ($spos < $startPos) $valid = false;
$spos = strpos($content, 'href', $spos);
$spos = strpos($content, '"', $spos) + 1;
$epos = strpos($content, '"', $spos);
$startPos = $epos;
$link = substr($content, $spos, $epos - $spos);
if (strpos($link, 'http://') !== false) $links[] = $link;
}
}
return $links;
}
try this code....
Inspired by Jon's answer, how about this one
word = 'hello'
q = deque(word)
''.join(q.pop() for _ in range(len(word)))
Allthough it's now a native type, it's still defined behind the scenes as an integer (int I think) where the literal false
is 0 and true
is 1. But I think all logic still consider anything but 0 as true, so strictly speaking the true literal is probably a keyword for the compiler to test if something is not false.
if(someval == true){
probably translates to:
if(someval !== false){ // e.g. someval !== 0
by the compiler
In short: It is not possible, and as it seems won't ever be supported (see here https://github.com/npm/npm/issues/775).
There are some hacky work-arrounds with using the CLI or ENV-Variables (see the current selected answer), .npmrc-Config-Files or npm link
- what they all have in common: They are never just project-specific, but always some kind of global
Solutions.
For me, none of those solutions are really clean because contributors to your project always need to create some special configuration or have some special knowledge - they can't just npm install
and it works.
So: Either you will have to put your package.json in the same directory where you want your node_modules installed, or live with the fact that they will always be in the root-dir of your project.
In my case, In a loop, I put res.render()
so might have been tried to call multiple times.
I've had the same problem, and I tried and tried... Finally I used:
powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'"
And put this line in a batch-file, and this works.
PHP 7 improved query.........
$sql = mysqli_query($conn, "SELECT * from users WHERE user_uid = '$uid'");
if (mysqli_num_rows($sql) > 0) {
echo 'Username taken.';
}
Can't find this in actual MSDN documentation, but a moderator in the forums said
I am afraid that OLEDB does not preserve the sheet order as they were in Excel
Excel Sheet Names in Sheet Order
Seems like this would be a common enough requirement that there would be a decent workaround.
You can use the version in Windows SDK but sometimes it might not be the same version of the .NET Framework your using, getting you the following error:
Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
In .NET 4.0 you'll need to search inside Microsoft SDK v8.0A, e.g.: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools (in my case I only have the 32 bit version installed by Visual Studio 2012).
It's not in standard C, so the behavior is undefined.
Some implementation uses it to clear stdin
buffer.
From C11 7.21.5.2 The fflush function, fflush
works only with output/update stream, not input stream.
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
Try the below script to find last argument
# cat arguments.sh
#!/bin/bash
if [ $# -eq 0 ]
then
echo "No Arguments supplied"
else
echo $* > .ags
sed -e 's/ /\n/g' .ags | tac | head -n1 > .ga
echo "Last Argument is: `cat .ga`"
fi
Output:
# ./arguments.sh
No Arguments supplied
# ./arguments.sh testing for the last argument value
Last Argument is: value
Thanks.
A better idea,
if you want to put the error message just beneath the text field, you can do like this
.row.spacer20top
.col-sm-6.form-group
= f.label :first_name, "*Your First Name:"
= f.text_field :first_name, :required => true, class: "form-control"
= f.error_message_for(:first_name)
What is error_message_for
?
--> Well, this is a beautiful hack to do some cool stuff
# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
def error_message_for(field_name)
if self.object.errors[field_name].present?
model_name = self.object.class.name.downcase
id_of_element = "error_#{model_name}_#{field_name}"
target_elem_id = "#{model_name}_#{field_name}"
class_name = 'signup-error alert alert-danger'
error_declaration_class = 'has-signup-error'
"<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
"#{self.object.errors[field_name].join(', ')}"\
"</div>"\
"<!-- Later JavaScript to add class to the parent element -->"\
"<script>"\
"document.onreadystatechange = function(){"\
"$('##{id_of_element}').parent()"\
".addClass('#{error_declaration_class}');"\
"}"\
"</script>".html_safe
end
rescue
nil
end
end
Markup Generated after error
<div id="error_user_email" for="user_email" class="signup-error alert alert-danger">has already been taken</div>
<script>document.onreadystatechange = function(){$('#error_user_email').parent().addClass('has-signup-error');}</script>
Corresponding SCSS
.has-signup-error{
.signup-error{
background: transparent;
color: $brand-danger;
border: none;
}
input, select{
background-color: $bg-danger;
border-color: $brand-danger;
color: $gray-base;
font-weight: 500;
}
&.checkbox{
label{
&:before{
background-color: $bg-danger;
border-color: $brand-danger;
}
}
}
Note: Bootstrap variables used here
^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$
Regular expression to match valid UK postcodes. In the UK postal system not all letters are used in all positions (the same with vehicle registration plates) and there are various rules to govern this. This regex takes into account those rules. Details of the rules: First half of postcode Valid formats [A-Z][A-Z][0-9][A-Z] [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9] [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z] [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions Position - First. Contraint - QVX not used Position - Second. Contraint - IJZ not used except in GIR 0AA Position - Third. Constraint - AEHMNPRTVXY only used Position - Forth. Contraint - ABEHMNPRVWXY Second half of postcode Valid formats [0-9][A-Z][A-Z] Exceptions Position - Second and Third. Contraint - CIKMOV not used
It's specified in the function type. When you have a function pointer, it's assumed to be cdecl if not explicitly stdcall. This means that if you get a stdcall pointer and a cdecl pointer, you can't exchange them. The two function types can call each other without issues, it's just getting one type when you expect the other. As for speed, they both perform the same roles, just in a very slightly different place, it's really irrelevant.
Consider:
if(rsData.Read()) {
int index = rsData.GetOrdinal("columnName"); // I expect, just "ursrdaystime"
if(rsData.IsDBNull(index)) {
// is a null
} else {
// access the value via any of the rsData.Get*(index) methods
}
} else {
// no row returned
}
Also: you need more using
;p
If your use-case is that you're caching values in Redis and are tolerant of stale values but would like to refresh them occasionally so that they don't get too stale, a hacky workaround is to just include a timestamp in the field value and handle expirations in whatever place you're accessing the value.
This allows you to keep using Redis hashes normally without needing to worry about any complications that might arise from the other approaches. The only cost is a bit of extra logic and parsing on the client end. Not a perfect solution, but it's what I typically do as I haven't needed TTL for any other reason and I'm usually needing to do extra parsing on the cached value anyways.
So basically it'll be something like this:
In Redis:
hash_name
- field_1: "2021-01-15;123"
- field_2: "2021-01-20;125"
- field_2: "2021-02-01;127"
Your (pseudo)code:
val = redis.hget(hash_name, field_1)
timestamp = val.substring(0, val.index_of(";"))
if now() > timestamp:
new_val = get_updated_value()
new_timestamp = now() + EXPIRY_LENGTH
redis.hset(hash_name, field_1, new_timestamp + ";" + new_val)
val = new_val
else:
val = val.substring(val.index_of(";"))
// proceed to use val
The biggest caveat imo is that you don't ever remove fields so the hash can grow quite large. Not sure there's an elegant solution for that - I usually just delete the hash every once in a while if it feels too big. Maybe you could keep track of everything you've stored somewhere and remove them periodically (though at that point, you might as well just be using that mechanism to expire the fields manually...).
use below code
Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));
I use
file_age() {
local filename=$1
echo $(( $(date +%s) - $(date -r $filename +%s) ))
}
is_stale() {
local filename=$1
local max_minutes=20
[ $(file_age $filename) -gt $(( $max_minutes*60 )) ]
}
if is_stale /my/file; then
...
fi
If you are not worrying about opening a console on-command, you can go into the properties for your project and change it to Console Application
This will still show your form as well as popping up a console window. You can't close the console window, but it works as an excellent temporary logger for debugging.
Just remember to turn it back off before you deploy the program.
Take a look at jsHybugger. It will allow you to remotely debug your js code for:
How this works (more details and alternatives on the projects site, this was what I found to be the best way).
Again, with Chrome on Android use the ADB extension without jsHybugger. I think this already described in the accepted answer to this question.
First you need to determine the revision ID of the last known commit. You can use HEAD^
or HEAD~{1}
if you know you need to reverse exactly one commit.
git reset --hard <revision_id_of_last_known_good_commit>
git push --force
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
$('input').keypress(function(e) {
e.preventDefault();
});
Without jQuery updated
document.querySelectorAll('.testimonial').forEach(function (element, index) {_x000D_
element.innerHTML = 'Testimonial ' + (index + 1);_x000D_
});
_x000D_
<div class="testimonial"></div>_x000D_
<div class="testimonial"></div>
_x000D_
I stumbled upon another solution, which is quite nice.
Basically, only do step 2 from the blog posted mentioned, and define a custom ObjectMapper as a Spring @Component
. (Things started working when I just removed all the AnnotationMethodHandlerAdapter stuff from step 3.)
@Component
@Primary
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
setSerializationInclusion(JsonInclude.Include.NON_NULL);
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
}
Works as long as the component is in a package scanned by Spring. (Using @Primary
is not mandatory in my case, but why not make things explicit.)
For me there are two benefits compared to the other approach:
Jackson2ObjectMapperBuilder
.new CustomObjectMapper()
instead of new ObjectMapper()
.CREATE TABLE people (
first_name varchar(20),
age integer,
last_name varchar(20)
);
"first_name","age","last_name" Ivan,23,Poupkine Eugene,,Pirogov
copy people from 'file.csv'
with (delimiter ';', null '');
select * from people;
Just in first column.....
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1')
change day/month position.
Here's a method for getting the version from the pom.properties, falling back to getting it from the manifest
public synchronized String getVersion() {
String version = null;
// try to load from maven properties first
try {
Properties p = new Properties();
InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");
if (is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch (Exception e) {
// ignore
}
// fallback to using Java API
if (version == null) {
Package aPackage = getClass().getPackage();
if (aPackage != null) {
version = aPackage.getImplementationVersion();
if (version == null) {
version = aPackage.getSpecificationVersion();
}
}
}
if (version == null) {
// we could not compute the version so use a blank
version = "";
}
return version;
}
Try this-
CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
insert into student (name,user_name,branch) values (name ,user_name,branch);
END
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + "/" + month + "/" + day;
or you can set new date and give the above values
Yep, draw a box and give it a border radius that is half the width of the box:
#circle {
background: #f00;
width: 200px;
height: 200px;
border-radius: 50%;
}
Working demo:
#circle {_x000D_
background: #f00;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<div id="circle"></div>
_x000D_
For me i started getting this problem when I upgraded to java 8, and then reverted back to java 7. Upgraded again to java 8 and the problem got resolved.
With jQuery:
$('form').submit(function () {
// Validate here
if (pass)
return true;
else
return false;
});
Using Java:
private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.id("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.ENTER);
Using C#:
private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));
element.SendKeys(Keys.Tab);
element.SendKeys(Keys.Enter);
The differences in speed in a for
- and a foreach
-loop are tiny when you're looping through common structures like arrays, lists, etc, and doing a LINQ
query over the collection is almost always slightly slower, although it's nicer to write! As the other posters said, go for expressiveness rather than a millisecond of extra performance.
What hasn't been said so far is that when a foreach
loop is compiled, it is optimised by the compiler based on the collection it is iterating over. That means that when you're not sure which loop to use, you should use the foreach
loop - it will generate the best loop for you when it gets compiled. It's more readable too.
Another key advantage with the foreach
loop is that if your collection implementation changes (from an int array
to a List<int>
for example) then your foreach
loop won't require any code changes:
foreach (int i in myCollection)
The above is the same no matter what type your collection is, whereas in your for
loop, the following will not build if you changed myCollection
from an array
to a List
:
for (int i = 0; i < myCollection.Length, i++)
Two other ways are strcpy(str, "");
and string[0] = 0
To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.
#include <string.h>
...
int i=0;
for(i=0;i<strlen(string);i++)
{
string[i] = 0;
}
In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.
At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.
It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)
I hope this was useful for anybody ;)
You may need to disable the hypervisor.
So, follow the next steps:
1) Open command prompt as Administrator
2) Run bcdedit to check hypervisor status:
bcdedit
3) Check hypervisor launch type:
4) If is set to auto then disable it:
bcdedit /set hypervisorlaunchtype off
5) Reboot host machine and launch VirtualBox again
You can use .indexOf()
and .substr()
like this:
var val = $("input").val();
var myString = val.substr(val.indexOf("?") + 1)
You can test it out here. If you're sure of the format and there's only one question mark, you can just do this:
var myString = $("input").val().split("?").pop();
String[] a= {"tube", "are", "fun"};
Arrays.asList(a).contains("any");
in order to center the canvas within the window +"px" should be added to el.style.top
and el.style.left
.
el.style.top = (viewportHeight - canvasHeight) / 2 +"px";
el.style.left = (viewportWidth - canvasWidth) / 2 +"px";
You need to use the doubleValue()
method to get the double value from a BigDecimal object.
BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want
Is caching a dynamically generated function/dictionary permissable?
Because you don't (appear to) know the type of the enum ahead of time, the first execution could generate something subsequent executions could take advantage of.
You could even cache the result of Enum.GetNames()
Are you trying to optimize for CPU or Memory? Do you really need to?
It Seems the Port 80 is already in use. Try to Use some other Port which is not in use by any other application in your System.
You shouldn't need a $watch. Just bind to resize event on window:
'use strict';
var app = angular.module('plunker', []);
app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'E',
template: '<div>window size: {{width}}px</div>'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
angular.element($window).bind('resize', function(){
scope.width = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
scope.$digest();
});
}
}]);
SELECT id, user_id, video_name
FROM sa_created_videos
ORDER BY LENGTH(id) ASC, LENGTH(user_id) DESC
Packet Capture is the best tool to track network data on the android. DOesnot need any root access and easy to read and save the calls based on application. Check this out
Try this: Adding users to MySQL
You need grant privileges to the user if you want external acess to database(ie. web pages).
One can also use a lambda function.
auto Compare = [](Node &a, Node &b) { //compare };
std::priority_queue<Node, std::vector<Node>, decltype(Compare)> openset(Compare);
If your database is down then during login as SYSDBA you can assume this. While login command will be executed like sqlplus sys/sys_password as sysdba that time you will get "connected to idle instance" reply from database. This message indicates your database is down. You should need to check first alert.log file about why database is down. If you found it was downed normally then you can issue "startup" command for starting database and after that execute your create user command. If you found database is having issue like missing datafile or something else then you need to recover database first and open database for executing your create user command.
"alter database open" command only accepted by database while it is on Mount stage. If database is down then it won't accept "alter database open" command.
Visual studio community edition is bundled with xamarin and which is free as well.
The easiest way to do this is to let bash
do it:
set -x
Or run it explicitly as bash -x myscript
.
If lakes
is your DataFrame
, you can do something like
area_dict = dict(zip(lakes.area, lakes.count))
.resizeme {_x000D_
resize: both;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
height: 75px;_x000D_
width: 500px;_x000D_
background-color: lightblue;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="resizeme">_x000D_
<svg_x000D_
width="100%"_x000D_
height="100%"_x000D_
viewBox="0 0 500 75"_x000D_
preserveAspectRatio="xMinYMid meet"_x000D_
style="background-color:green"_x000D_
xmlns="http://www.w3.org/2000/svg"_x000D_
xmlns:xlink="http://www.w3.org/1999/xlink"_x000D_
>_x000D_
<text_x000D_
x="0"_x000D_
y="75"_x000D_
font-size="75"_x000D_
fill="black"_x000D_
>¦Resize This¦</text>_x000D_
</svg>_x000D_
</div>
_x000D_
foreignObject
:.resizeme {_x000D_
resize: both;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
height: 200px;_x000D_
width: 500px;_x000D_
background-color: lightblue;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="resizeme">_x000D_
<svg_x000D_
width="100%"_x000D_
height="100%"_x000D_
viewBox="0 0 500 200"_x000D_
preserveAspectRatio="xMinYMin meet"_x000D_
>_x000D_
<foreignObject width="100%" height="100%" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<div xmlns="http://www.w3.org/1999/xhtml" style="background-color:lightgreen;">_x000D_
<h1>heading</h1>_x000D_
<p>Resize the blue box.</p>_x000D_
</div>_x000D_
</foreignObject>_x000D_
</svg>_x000D_
</div>
_x000D_
A single element in a JavaScript String is considered to be a single UTF-16 code unit. That is to say, Strings characters are stored in 16-bit (1 code unit), and 16-bit is equal to 2 bytes (8-bit = 1 byte).
The charCodeAt()
method can be used to return an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
The codePointAt()
can be used to return the entire code point value for Unicode characters, e.g. UTF-32.
When a UTF-16 character can't be represented in a single 16-bit code unit, it will have a surrogate pair and therefore use two code units( 2 x 16-bit = 4 bytes)
See Unicode encodings for different encodings and their code ranges.
Light red fill with dark red text.
{'bg_color': '#FFC7CE', 'font_color': '#9C0006'})
Light yellow fill with dark yellow text.
{'bg_color': '#FFEB9C', 'font_color': '#9C6500'})
Green fill with dark green text.
{'bg_color': '#C6EFCE', 'font_color': '#006100'})
You can use Func<T, TResult>
generic delegate. (See MSDN)
Func<MyType, ReturnType> func = (db) => { return new MyType(); }
Also there are useful generic delegates which considers a return value:
Method:
public MyType SimpleUsing.DoUsing<MyType>(Func<TInput, MyType> myTypeFactory)
Generic delegate:
Func<InputArgumentType, MyType> createInstance = db => return new MyType();
Execute:
MyType myTypeInstance = SimpleUsing.DoUsing(
createInstance(new InputArgumentType()));
OR explicitly:
MyType myTypeInstance = SimpleUsing.DoUsing(db => return new MyType());
<?php
$var1 = "Line 1 info blah blah <br /> Line 2 info blah blah";
$var1 = str_replace("<br />", "\n", $var1);
?>
<textarea><?php echo $var1; ?></textarea>
I didn't mean to copy the same answer, that is why I didn't accept my own answer.
Actually when I add use DateTime
in top of the controller solves this problem.
One word answer: MONEY :D
1 GB to store in US-East-1: (Updated at 2016.dec.20)
Further storage options, which may be used for temporary storing data while/before processing it:
The costs above are just samples. There can be differences by region, and it can change at any point. Also there are extra costs for data transfer (out to the internet). However they show a ratio between the prices of the services.
There are a lot more differences between these services:
EFS is:
EBS is:
S3 is:
Glacier is:
As it got mentioned in JDL's comment, there are several interesting aspects in terms of pricing. For example Glacier, S3, EFS allocates the storage for you based on your usage, while at EBS you need to predefine the allocated storage. Which means, you need to over estimate. ( However it's easy to add more storage to your EBS volumes, it requires some engineering, which means you always "overpay" your EBS storage, which makes it even more expensive.)
Source: AWS Storage Update – New Lower Cost S3 Storage Option & Glacier Price Reduction
I know this is old, but i stumbled on it with Google.
If you have a return value in your stored procedure say "Return 1" - not using output parameters.
You can do the following - "@RETURN_VALUE" is silently added to every command object. NO NEED TO EXPLICITLY ADD
cmd.ExecuteNonQuery();
rtn = (int)cmd.Parameters["@RETURN_VALUE"].Value;
I had the same problem. I'm no expert but this is the solution we used: Before you filter your data, first create a temporary column to populate your entire data set with your original sort order. Auto number the temporary "original sort order" column. Now filter your data. Copy and paste the filtered data into a new worksheet. This will move only the filtered data to the new sheet so that your row numbers will become consecutive. Now auto number your desired field. Go back to your original worksheet and delete the filtered rows. Copy and paste the newly numbered data from the secondary sheet onto the bottom of your original worksheet. Then clear your filter and sort the worksheet by the temporary "original sort order" column. This will put your newly numbered data back into its original order and you can then delete the temporary column.
Change <?php echo $proxy ?>
to ' . $proxy . '
.
You use <?php
when you're outputting HTML by leaving PHP mode with ?>
. When you using echo
, you have to use concatenation, or wrap your string in double quotes and use interpolation.
You could use get
twice:
example_dict.get('key1', {}).get('key2')
This will return None
if either key1
or key2
does not exist.
Note that this could still raise an AttributeError
if example_dict['key1']
exists but is not a dict (or a dict-like object with a get
method). The try..except
code you posted would raise a TypeError
instead if example_dict['key1']
is unsubscriptable.
Another difference is that the try...except
short-circuits immediately after the first missing key. The chain of get
calls does not.
If you wish to preserve the syntax, example_dict['key1']['key2']
but do not want it to ever raise KeyErrors, then you could use the Hasher recipe:
class Hasher(dict):
# https://stackoverflow.com/a/3405143/190597
def __missing__(self, key):
value = self[key] = type(self)()
return value
example_dict = Hasher()
print(example_dict['key1'])
# {}
print(example_dict['key1']['key2'])
# {}
print(type(example_dict['key1']['key2']))
# <class '__main__.Hasher'>
Note that this returns an empty Hasher when a key is missing.
Since Hasher
is a subclass of dict
you can use a Hasher in much the same way you could use a dict
. All the same methods and syntax is available, Hashers just treat missing keys differently.
You can convert a regular dict
into a Hasher
like this:
hasher = Hasher(example_dict)
and convert a Hasher
to a regular dict
just as easily:
regular_dict = dict(hasher)
Another alternative is to hide the ugliness in a helper function:
def safeget(dct, *keys):
for key in keys:
try:
dct = dct[key]
except KeyError:
return None
return dct
So the rest of your code can stay relatively readable:
safeget(example_dict, 'key1', 'key2')
Don't waste your time trying to resolve this issue, this was made clear by the makers themselves. Instead of cv2.imshow()
use this:
img = cv2.imread('path_to_image')
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
Yes the second syntax is fine.
Have you tried using the SPF wizard? https://www.spfwizard.net/
It can quickly generate basic and complex SPF records.
Just for the sake of completeness, I invite you to think about it like this:
<p>
is a paragraph, an <li>
is a list item, etc., and we're supposed to use the right tag for the right purpose -- not like in the old days when we indented using <blockquote>
whether the content was a quote or not.<div>
and <span>
, because otherwise, people would go back to abusing the elements which do have meanings.Bitwise operators are operators that work on multi-bit values, but conceptually one bit at a time.
AND
is 1 only if both of its inputs are 1, otherwise it's 0.OR
is 1 if one or both of its inputs are 1, otherwise it's 0.XOR
is 1 only if exactly one of its inputs are 1, otherwise it's 0.NOT
is 1 only if its input is 0, otherwise it's 0.These can often be best shown as truth tables. Input possibilities are on the top and left, the resultant bit is one of the four (two in the case of NOT since it only has one input) values shown at the intersection of the inputs.
AND | 0 1 OR | 0 1 XOR | 0 1 NOT | 0 1
----+----- ---+---- ----+---- ----+----
0 | 0 0 0 | 0 1 0 | 0 1 | 1 0
1 | 0 1 1 | 1 1 1 | 1 0
One example is if you only want the lower 4 bits of an integer, you AND it with 15 (binary 1111) so:
201: 1100 1001
AND 15: 0000 1111
------------------
IS 9 0000 1001
The zero bits in 15 in that case effectively act as a filter, forcing the bits in the result to be zero as well.
In addition, >>
and <<
are often included as bitwise operators, and they "shift" a value respectively right and left by a certain number of bits, throwing away bits that roll of the end you're shifting towards, and feeding in zero bits at the other end.
So, for example:
1001 0101 >> 2 gives 0010 0101
1111 1111 << 4 gives 1111 0000
Note that the left shift in Python is unusual in that it's not using a fixed width where bits are discarded - while many languages use a fixed width based on the data type, Python simply expands the width to cater for extra bits. In order to get the discarding behaviour in Python, you can follow a left shift with a bitwise and
such as in an 8-bit value shifting left four bits:
bits8 = (bits8 << 4) & 255
With that in mind, another example of bitwise operators is if you have two 4-bit values that you want to pack into an 8-bit one, you can use all three of your operators (left-shift
, and
and or
):
packed_val = ((val1 & 15) << 4) | (val2 & 15)
& 15
operation will make sure that both values only have the lower 4 bits.<< 4
is a 4-bit shift left to move val1
into the top 4 bits of an 8-bit value.|
simply combines these two together.If val1
is 7 and val2
is 4:
val1 val2
==== ====
& 15 (and) xxxx-0111 xxxx-0100 & 15
<< 4 (left) 0111-0000 |
| |
+-------+-------+
|
| (or) 0111-0100
With ES6 supported also duplicate string
var allLongestStrings = arrayOfStrings => {
let maxLng = Math.max(...arrayOfStrings.map( elem => elem.length))
return arrayOfStrings.filter(elem => elem.length === maxLng)
}
let arrayOfStrings = ["aba", "aa", "ad", "vcd","aba"]
console.log(allLongestStrings(arrayOfStrings))
Without the update-and-join notation (not all DBMS support that), use:
UPDATE QuestionTrackings
SET QuestionID = (SELECT QuestionID
FROM AnswerTrackings
WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)
WHERE QuestionID IS NULL
AND EXISTS(SELECT QuestionID
FROM AnswerTrackings
WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)
Often in a query like this, you need to qualify the WHERE clause with an EXISTS clause that contains the sub-query. This prevents the UPDATE from trampling over rows where there is no match (usually nulling all the values). In this case, since a missing question ID would change the NULL to NULL, it arguably doesn't matter.
Adding external Jar is not smart in case you want to change the project location in filesystem.
The best way is to add the jar to build path so your project will compile if exported:
Create a folder called lib in your project folder.
copy to this folder all the jar files you need.
Refresh your project in eclipse.
Select all the jar files, then right click on one of them and select Build Path -> Add to Build Path
As Paul Tomblin mentioned you have to use ctags. You could also consider using plugins to select appropriate one or to preview the definition of the function under cursor. Without plugins you will have a headache trying to select one of the hundreds overloaded 'doAction' methods as built in ctags support doesn't take in account the context - just a name.
Also you can use cscope and its 'find global symbol' function. But your vim have to be compiled with +cscope support which isn't default one option of build.
If you know that the function is defined in the current file, you can use 'gD' keystrokes in a normal mode to jump to definition of the symbol under cursor.
Here is the most downloaded plugin for navigation
http://www.vim.org/scripts/script.php?script_id=273
Here is one I've written to select context while jump to tag
http://www.vim.org/scripts/script.php?script_id=2507
Using Ref forwarding you can pass the ref from parent to further down to a child.
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Note The second ref argument only exists when you define a component with React.forwardRef call. Regular functional or class components don’t receive the ref argument, and ref is not available in props either.
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
Reference: React Documentation.
A lot of these solutions build on instantiating real Array objects, which can get the job done for a lot of cases but can't support cases like range(Infinity)
. You could use a simple generator to avoid these problems and support infinite sequences:
function* range( start, end, step = 1 ){
if( end === undefined ) [end, start] = [start, 0];
for( let n = start; n < end; n += step ) yield n;
}
Examples:
Array.from(range(10)); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Array.from(range(10, 20)); // [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
i = range(10, Infinity);
i.next(); // { value: 10, done: false }
i.next(); // { value: 11, done: false }
i.next(); // { value: 12, done: false }
i.next(); // { value: 13, done: false }
i.next(); // { value: 14, done: false }
This will solve your problem
interface
TArrayStr = Array Of string;
implementation
function SplitString(Text: String): TArrayStr;
var
intIdx: Integer;
intIdxOutput: Integer;
const
Delimiter = ';';
begin
intIdxOutput := 0;
SetLength(Result, 1);
Result[0] := '';
for intIdx := 1 to Length(Text) do
begin
if Text[intIdx] = Delimiter then
begin
intIdxOutput := intIdxOutput + 1;
SetLength(Result, Length(Result) + 1);
end
else
Result[intIdxOutput] := Result[intIdxOutput] + Text[intIdx];
end;
end;
You can try the following code:
background-image:url('url of your image') 10px 10px no-repeat
This answer is all about authorization and it is a complement of my previous answer about authentication
Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.
@Secured
annotationBesides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.
Create an enumeration and define the roles according to your needs:
public enum Role {
ROLE_1,
ROLE_2,
ROLE_3
}
Change the @Secured
name binding annotation created before to support roles:
@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
Role[] value() default {};
}
And then annotate the resource classes and methods with @Secured
to perform the authorization. The method annotations will override the class annotations:
@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id) {
// This method is not annotated with @Secured
// But it's declared within a class annotated with @Secured({Role.ROLE_1})
// So it only can be executed by the users who have the ROLE_1 role
...
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
@Secured({Role.ROLE_1, Role.ROLE_2})
public Response myOtherMethod(@PathParam("id") Long id) {
// This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
// The method annotation overrides the class annotation
// So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
...
}
}
Create a filter with the AUTHORIZATION
priority, which is executed after the AUTHENTICATION
priority filter defined previously.
The ResourceInfo
can be used to get the resource Method
and resource Class
that will handle the request and then extract the @Secured
annotations from them:
@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the resource class which matches with the requested URL
// Extract the roles declared by it
Class<?> resourceClass = resourceInfo.getResourceClass();
List<Role> classRoles = extractRoles(resourceClass);
// Get the resource method which matches with the requested URL
// Extract the roles declared by it
Method resourceMethod = resourceInfo.getResourceMethod();
List<Role> methodRoles = extractRoles(resourceMethod);
try {
// Check if the user is allowed to execute the method
// The method annotations override the class annotations
if (methodRoles.isEmpty()) {
checkPermissions(classRoles);
} else {
checkPermissions(methodRoles);
}
} catch (Exception e) {
requestContext.abortWith(
Response.status(Response.Status.FORBIDDEN).build());
}
}
// Extract the roles from the annotated element
private List<Role> extractRoles(AnnotatedElement annotatedElement) {
if (annotatedElement == null) {
return new ArrayList<Role>();
} else {
Secured secured = annotatedElement.getAnnotation(Secured.class);
if (secured == null) {
return new ArrayList<Role>();
} else {
Role[] allowedRoles = secured.value();
return Arrays.asList(allowedRoles);
}
}
}
private void checkPermissions(List<Role> allowedRoles) throws Exception {
// Check if the user contains one of the allowed roles
// Throw an Exception if the user has not permission to execute the method
}
}
If the user has no permission to execute the operation, the request is aborted with a 403
(Forbidden).
To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext
(which should be already set in the ContainerRequestContext
) or inject it using CDI, depending on the approach you go for.
If a @Secured
annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.
Alternatively to defining the roles in the @Secured
annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed
, @PermitAll
and @DenyAll
.
JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:
@DenyAll
on the method takes precedence over @RolesAllowed
and @PermitAll
on the class.@RolesAllowed
on the method takes precedence over @PermitAll
on the class.@PermitAll
on the method takes precedence over @RolesAllowed
on the class.@DenyAll
can't be attached to classes.@RolesAllowed
on the class takes precedence over @PermitAll
on the class.So an authorization filter that checks JSR-250 annotations could be like:
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Method method = resourceInfo.getResourceMethod();
// @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
if (method.isAnnotationPresent(DenyAll.class)) {
refuseRequest();
}
// @RolesAllowed on the method takes precedence over @PermitAll
RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
return;
}
// @PermitAll on the method takes precedence over @RolesAllowed on the class
if (method.isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// @DenyAll can't be attached to classes
// @RolesAllowed on the class takes precedence over @PermitAll on the class
rolesAllowed =
resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
}
// @PermitAll on the class
if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// Authentication is required for non-annotated methods
if (!isAuthenticated(requestContext)) {
refuseRequest();
}
}
/**
* Perform authorization based on roles.
*
* @param rolesAllowed
* @param requestContext
*/
private void performAuthorization(String[] rolesAllowed,
ContainerRequestContext requestContext) {
if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
refuseRequest();
}
for (final String role : rolesAllowed) {
if (requestContext.getSecurityContext().isUserInRole(role)) {
return;
}
}
refuseRequest();
}
/**
* Check if the user is authenticated.
*
* @param requestContext
* @return
*/
private boolean isAuthenticated(final ContainerRequestContext requestContext) {
// Return true if the user is authenticated or false otherwise
// An implementation could be like:
// return requestContext.getSecurityContext().getUserPrincipal() != null;
}
/**
* Refuse the request.
*/
private void refuseRequest() {
throw new AccessDeniedException(
"You don't have permissions to perform this action.");
}
}
Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature
. If you use Jersey, you don't need to write your own filter, just use the existing implementation.
'parent.relativePath' points at wrong local POM @ myGroup:myParentArtifactId:1.0, C:\myProjectDir\parent\pom.xml
This indicates that maven did search locally for the parent pom, but found that it was not the correct pom.
pom.xml
of parentpom
correctly define the parent
pom as the pom.xml
of rootpom
?rootpom
folder contain pom.xml
as well as the paretpom
folder?Setting setOnClickListener(null)
is a good idea to remove click listener at runtime.
And also someone commented that calling View.hasOnClickListeners()
after this will return true
, NO my friend.
Here is the implementation of hasOnClickListeners()
taken from android.view.View
class
public boolean hasOnClickListeners() {
ListenerInfo li = mListenerInfo;
return (li != null && li.mOnClickListener != null);
}
Thank GOD. It checks for null
.
So everything is safe. Enjoy :-)
On CYGwin, you can install this as a typical package in the first screen. Look for
libssl-devel
You just have to put this code into cellForRowAtIndexPath
To disable the cell's selection property: (while tapping the cell)
cell.selectionStyle = UITableViewCellSelectionStyleNone;
To enable being able to select (tap) the cell: (tapping the cell)
// Default style
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
// Gray style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
Note that a cell with selectionStyle = UITableViewCellSelectionStyleNone;
will still cause the UI to call didSelectRowAtIndexPath
when touched by the user. To avoid this, do as suggested below and set.
cell.userInteractionEnabled = NO;
instead. Also note you may want to set cell.textLabel.enabled = NO;
to gray out the item.
Late to the party: Try this>
base_filename = 'Values.txt'
with open(os.path.join(WorkingFolder, base_filename),'w') as outfile:
df.to_string(outfile)
#Neatly allocate all columns and rows to a .txt file
I have build such kind of application using approximatively the same approach except :
UIImage
but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.Whenever the user start zooming, I acquire the CGPDFPage
and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context
is like :
CGAffineTransform currentCTM = CGContextGetCTM(context);
if (currentCTM.a == 1.0 && baseImage) {
//Calculate ideal scale
CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height;
CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);
CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
@synchronized(issue) {
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
CGContextConcatCTM(context, pdfToPageTransform);
CGContextDrawPDFPage(context, pdfPage);
}
}
issue is the object containg the CGPDFDocumentRef
. I synchronize the part where I access the pdfDoc
property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef
object do some internal caching that I did not find how to get rid of.
Suppose we want to find the string variable needle
in the string variable haystack
. There are three gotchas:
string.toUpperCase
and string.toLowerCase
. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i");
followed by needleRegExp.test(haystack)
.needle
. Be careful that needle
does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
.needle
and haystack
, just ignoring case, make sure to add "^"
at the start and "$"
at the end of your regular expression constructor.Taking points (1) and (2) into consideration, an example would be:
var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
alert(result);
I'm not an expert, but I did a lot of looking to implement this for myself. I found something different, but modified it to accomplish this. It's really quite simple:
The function takes two arguments, a div containing only the words "show more" [or whatever] and a div containing the originally hidden text and the words "show less." The function displays the one div and hides the other.
NOTE: If more than one show/hide on page, assign different ids to divs Colors can be changed
<p>Here is text that is originally displayed</p>
<div id="div1">
<p style="color:red;" onclick="showFunction('div2','div1')">show more</p></div>
<div id="div2" style="display:none">
<p>Put expanded text here</p>
<p style="color:red;" onclick="showFunction('div1','div2')">show less</p></div>
<p>more text</p>
Here is the Script:
<script>
function showFunction(diva, divb) {
var x = document.getElementById(diva);
var y = document.getElementById(divb);
x.style.display = 'block';
y.style.display = 'none';
}
</script>
try this, for Programmatically to set a background with radius to LinearLayout or any View.
private Drawable getDrawableWithRadius() {
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setCornerRadii(new float[]{20, 20, 20, 20, 20, 20, 20, 20});
gradientDrawable.setColor(Color.RED);
return gradientDrawable;
}
LinearLayout layout = new LinearLayout(this);
layout.setBackground(getDrawableWithRadius());
pip install easy-tictoc
In the code:
from tictoc import tic, toc
tic()
#Some code
toc()
Disclaimer: I'm the author of this library.
When using a relative layout, you can make a view stretch by anchoring it to both of the views it's supposed to stretch toward. Although the specified height will be disregarded, Android still requires a height attribute, which is why I wrote "0dp". Example:
<View
android:id="@+id/topView"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:layout_marginTop="8dp"/>
<View
android:id="@+id/stretchableView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="@id/topView"
android:layout_above="@+id/bottomView"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:adjustViewBounds="true"/>
<View
android:id="@id/bottomView"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp"/>
Just to clarify what moonlightcheese stated: To trigger a button click event through code in Android provide the following:
buttonName.performClick();
This should work:
import java.util.Scanner;
public class Test {
public static void main(String... args) throws Throwable {
Scanner kb = new Scanner(System.in);
int num1;
System.out.print("Enter number 1: ");
while (true)
try {
num1 = Integer.parseInt(kb.nextLine());
break;
} catch (NumberFormatException nfe) {
System.out.print("Try again: ");
}
int num2;
do {
System.out.print("Enter number 2: ");
while (true)
try {
num2 = Integer.parseInt(kb.nextLine());
break;
} catch (NumberFormatException nfe) {
System.out.print("Try again: ");
}
} while (num2 < num1);
}
}
The Header
field of the Request is public. You may do this :
req.Header.Set("name", "value")
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html Check this tutorial
If it's a UI based application , then " I also need to know what I need to add to my code so that my program waits about 700 milliseconds for a keyinput before moving on to another method" you can use GlassPane or Timer class to fulfill the requirement.
For key Event:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}
check this game example http://zetcode.com/tutorials/javagamestutorial/movingsprites/
Thanks to @jarno I know about the -z option and I found out that when using GNU grep with the -P option, matching against \n
is possible. :)
Example:
grep -zoP 'foo\n\K.*'<<<$'foo\nbar'
Prints bar
You could send yourself an email an look in the email header (In Outlook: Open the mail, View->Options, there is 'Internet headers)
Some js files come from the web or library, they are not written by yourself. The code they get variable like this:
var queryString = document.location.search.substring(1);
var params = PDFViewerApplication.parseQueryString(queryString);
var file = 'file' in params ? params.file : DEFAULT_URL;
This method makes js files unchanged(keep independence), and pass variable correctly!
'b' should be in capital letter in document.getElementById
modified code jsfiddle
function test()
{
var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
//document.body.appendChild(element);
}
One other difference lies in the performance.
As the DLL is loaded at runtime by the .exe(s), the .exe(s) and the DLL work with shared memory concept and hence the performance is low relatively to static linking.
On the other hand, a .lib is code that is linked statically at compile time into every process that requests. Hence the .exe(s) will have single memory, thus increasing the performance of the process.
As far as I can tell what you could do is "retire" your previous app and redirect all users to your new app. This procedure is not supported by Google (tsk... tsk...), but it could be implemented in four steps:
Change the current application to show a message to the users about the upgrade and redirect them to the new app listing. Probably a full screen message would do with some friendly text. This message could be triggered remotely ideally, but a cut-off date can be used too. (But then that will be a hard deadline for you, so be careful... ;))
Release the modified old app as an upgrade, maybe with some feature upgrades/bug fixes too, to "sweeten the deal" to the users. Still there is no guarantee that all users will upgrade, but probably the majority will do.
Prepare your new app with the updated package name and upload it to the store, then trigger the message in the old app (or just wait until it expires, if that was your choice).
Unpublish the old app in Play Store to avoid any new installs. Unpublishing an app doesn't mean the users who already installed it won't have access to it anymore, but at least the potential new users won't find it on the market.
Not ideal and can be annoying to the users, sometimes even impossible to implement due to the status/possibilities of the app. But since Google left us no choice this is the only way to migrate the users of the old apps to a "new" one (even if it is not really new). Not to mention that if you don't have access to the sources and code signing details for the old app then all you could do is hoping that he users will notice the new app...
If anybody figured out a better way by all means: please do tell.
Use filter
, or if the number of dictionaries in exampleSet
is too high, use ifilter
of the itertools
module. It would return an iterator, instead of filling up your system's memory with the entire list at once:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
As per the PHP manual - parse_url should not be used to validate a URL.
Unfortunately, it seems that filter_var('example.com', FILTER_VALIDATE_URL)
does not perform any better.
Both parse_url()
and filter_var()
will pass malformed URLs such as http://...
Therefore in this case - regex is the better method.
Your second version is less efficient because it creates an extra string object when there is simply no need to do so.
Immutability means that your first version behaves the way you expect and is thus the approach to be preferred.
You can use Process.GetProcesses()
to get the currently running processes, then Process.Kill()
to kill a process.
When calling a promise defined in a service or in a factory make sure to use service as I could not get response from a promise defined in a factory. This is how I call a promise defined in a service.
myApp.service('serverOperations', function($http) {
this.get_data = function(user) {
return $http.post('http://localhost/serverOperations.php?action=get_data', user);
};
})
myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {
serverOperations.get_data(user)
.then( function(response) {
console.log(response.data);
}
);
})
There are actually two place where where mac os x serves website by default:
/Library/WebServer/Documents --> http://localhost
~/Sites --> http://localhost/~user/
Listing the entries in the current directory (for directories in os.listdir(os.getcwd()):
) and then interpreting those entries as subdirectories of an entirely different directory (dir = os.path.join('/home/user/workspace', directories)
) is one thing that looks fishy.
Bug is in Jquery Validation Validation Plugin Only validates with @ to change this
change the code to this
email: function( value, element ) {
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
// Retrieved 2014-01-14
// If you have a problem with this implementation, report a bug against the above spec
// Or use custom methods to implement your own email validation
return this.optional( element ) || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test( value );
}
Instead of ng-options="product as product.label for product in products">
in the select element, you can even use this:
<option ng-repeat="product in products" value="{{product.label}}">{{product.label}}
which works just fine as well.
I think the good practice may be something like this;
import subprocess
cmd = 'python script.py'
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()
result = out.split('\n')
for lin in result:
if not lin.startswith('#'):
print(lin)
according to documentation The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. Read Here
From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":
The following works for me:
python -m http.server [<portNo>]
Because I am using Python 3 the module SimpleHTTPServer
has been replaced by http.server
, at least in Windows.
You can use the %
operator to find the remainder of a division, and compare the result with 0
.
Example:
if (number % divisor == 0)
{
//code for perfect divisor
}
else
{
//the number doesn't divide perfectly by divisor
}
Sounds like a job for sed
:
sed -n '8,12p' yourfile
...will send lines 8 through 12 of yourfile
to standard out.
If you want to prepend the line number, you may wish to use cat -n
first:
cat -n yourfile | sed -n '8,12p'
This is extension of answer provided by Ranjith
I would suggest, you to choose a choice-parameter build, and specify the branches that you would like to build. Active Choice Parameter
And after that, you can specify branches to build. Branch to Build
Now, when you would build your project, you would be provided with "Build with Parameters, where you can choose the branch to build"
You can also write a groovy script to fetch all your branches to in active choice parameter.
I just wanted to add to the William Smash solution as I couldn't get to his blog so answers which may have been in there to my simple questions could not be found.
Took me a while to realise, but maybe I was just having a moment...
If you haven't had to do so already you'll need to add a reference to System.Windows.Forms in the project properties.
Also you'll need to add
Imports System.Windows.Forms
to the file where you're adding the override class.
For OnPaintBackground you'll need to add a reference for System.Drawing then
Imports System.Drawing.Printing.PrintEventArgs
If you launch your program with -enableassertions
(or -ea
for short) then this statement
assert cond;
is equivalent to
if (!cond)
throw new AssertionError();
If you launch your program without this option, the assert statement will have no effect.
For example, assert d >= 0 && d <= s.length();
, as posted in your question, is equivalent to
if (!(d >= 0 && d <= s.length()))
throw new AssertionError();
(If you launched with -enableassertions
that is.)
Formally, the Java Language Specification: 14.10. The assert
Statement says the following:
14.10. The
assert
Statement
An assertion is anassert
statement containing a boolean expression. An assertion is either enabled or disabled. If the assertion is enabled, execution of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates tofalse
. If the assertion is disabled, execution of the assertion has no effect whatsoever.
Where "enabled or disabled" is controlled with the -ea
switch and "An error is reported" means that an AssertionError
is thrown.
assert
:You can append : "Error message"
like this:
assert d != null : "d is null";
to specify what the error message of the thrown AssertionError should be.
This post has been rewritten as an article here.
In order to detect mouseleave without taking in account the scroll bar and the autcomplete field or inspect :
document.addEventListener("mouseleave", function(event){
if(event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight))
{
console.log("I'm out");
}
});
Conditions explanations:
event.clientY <= 0 is when the mouse leave from the top
event.clientX <= 0 is when the mouse leave from the left
event.clientX >= window.innerWidth is when the mouse leave from the right
event.clientY >= window.innerHeight is when the mouse leave from the bottom
======================== EDIT ===============================
document.addEventListener("mouseleave") seems to be not fired on new firefox version, mouseleave need to be attached to an element like body, or a child element.
I suggest to use instead
document.body.addEventListener("mouseleave")
Or
window.addEventListener("mouseout")
You should use the new available m2e plugin for Maven integration in Eclipse. With help of that plugin, you should create a new project and move your sources into that project. These are the steps:
File > New > Project...
Maven
and select Maven Project
and click Next
.Create a simple project
(to skip the archetype selection).jar
, and a Name.Run as > Maven install
.If you don't want to use html/dom, you could use regex. I haven't tested this; but something along the lines of:
function parseHtmlEntities(str) {
return str.replace(/&#([0-9]{1,3});/gi, function(match, numStr) {
var num = parseInt(numStr, 10); // read num as normal number
return String.fromCharCode(num);
});
}
Note: this would only work for numeric html-entities, and not stuff like &oring;.
Fixed the function (some typos), test here: http://jsfiddle.net/Be2Bd/1/
You cannot "erase" from a file in-place unless you need to erase the end. Either be content with an overwrite of an "empty" value, or read the parts of the file you care about and write it to another file.
I've spent some time working on this and came up with this to calculate someone's age in years, months and days. I've tested against the Feb 29th problem and leap years and it seems to work, I'd appreciate any feedback:
public void LoopAge(DateTime myDOB, DateTime FutureDate)
{
int years = 0;
int months = 0;
int days = 0;
DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);
DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);
while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)
{
months++;
if (months > 12)
{
years++;
months = months - 12;
}
}
if (FutureDate.Day >= myDOB.Day)
{
days = days + FutureDate.Day - myDOB.Day;
}
else
{
months--;
if (months < 0)
{
years--;
months = months + 12;
}
days +=
DateTime.DaysInMonth(
FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month
) + FutureDate.Day - myDOB.Day;
}
//add an extra day if the dob is a leap day
if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)
{
//but only if the future date is less than 1st March
if (FutureDate >= new DateTime(FutureDate.Year, 3, 1))
days++;
}
}
By using below method you can convert java.math.BigDecimal to String.
BigDecimal bigDecimal = new BigDecimal("10.0001");
String bigDecimalString = String.valueOf(bigDecimal.doubleValue());
System.out.println("bigDecimal value in String: "+bigDecimalString);
Output:
bigDecimal value in String: 10.0001
You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.
The formula would look like this:
=SUBTOTAL(9,B1:B20)
The function number 9, tells it to use the SUM function on the data range B1:B20.
If you are 'filtering' by hiding rows, the function number should be updated to 109.
=SUBTOTAL(109,B1:B20)
The function number 109 is for the SUM function as well, but hidden rows are ignored.
for windows :
Ctrl + q and c for exit the running situation .
With a class & AudioToolbox:
import AudioToolbox
class Sound {
var soundEffect: SystemSoundID = 0
init(name: String, type: String) {
let path = NSBundle.mainBundle().pathForResource(name, ofType: type)!
let pathURL = NSURL(fileURLWithPath: path)
AudioServicesCreateSystemSoundID(pathURL as CFURLRef, &soundEffect)
}
func play() {
AudioServicesPlaySystemSound(soundEffect)
}
}
Usage:
testSound = Sound(name: "test", type: "caf")
testSound.play()
the equivalent to the batch program would be
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
std::cin.get();
return 0;
}
The additional line does exactly what PAUSE
does, waits for a single character input
I have the same problem with importing WinSCard.dll in my project. I deal with that importing directly from dll like this:
[DllImport("winscard.dll")]
public static extern int SCardEstablishContext(int dwScope, int pvReserved1, int pvReserved2, ref int phContext);
[DllImport("winscard.dll")]
public static extern int SCardReleaseContext(int phContext);
You could add this to separate project and then add a reference from your main project.
For anyone interested: if you are using Intellj, just simply put hibernate.cfg.xml
under src/main/resources
.
First up you need to download Selenium jar files from http://www.seleniumhq.org/download/. Then you'd need an IDE, something like IntelliJ or Eclipse. Then you'll have to map your jar files to those IDEs. Then depending on which language/framework you choose, you'll have to download the relevant library files, for example, if you're using JUnit you'll have to download Junit 4.11 jar file. Finally don't forget to download the drivers for Chrome and Safari (firefox driver comes standard with selenium). Once done, you can start coding and testing your code with the browser of your choice.
The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):
import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')
plt.show()
print(fpath)
will show you where you should put the .ttf.
You can see the output here: https://matplotlib.org/gallery/api/font_file.html
Found a SOLUTION which works for me! Add one more rule in the file proguard-android.txt
:
-keepclassmembers class * extends android.webkit.WebChromeClient {
public void openFileChooser(...);
}
With Bootstrap 3.2 you can wrap each iframe in the responsive-embed wrapper of your choice:
http://getbootstrap.com/components/#responsive-embed
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="…"></iframe>
</div>
<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
<iframe class="embed-responsive-item" src="…"></iframe>
</div>
If you don't want to wrap your iframes, you can use FluidVids https://github.com/toddmotto/fluidvids. See demo here: http://toddmotto.com/labs/fluidvids/
<!-- fluidvids.js -->
<script src="js/fluidvids.js"></script>
<script>
fluidvids.init({
selector: ['iframe'],
players: ['www.youtube.com', 'player.vimeo.com']
});
</script>
When I converted my project with default pacage and a class named addition, to testng.xml. It got converted as:
<classes>
<class name=".addition"/>
</classes>
and was throwing error that class cannot be loaded. If I remove . before addition, the code works fine. So be careful with default package.
As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )
The querystring (get) parameters included in your url probably will not do anything.
Try this:
string url = "http://myserver/method";
string content = "param1=1¶m2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);
HTH,
bovako
try this:
<a id="send-thoughts" href="">Click</a>
<textarea id="message"></textarea>
<!--<textarea id="#message"></textarea>-->
jQuery("a#send-thoughts").click(function() {
//var thought = jQuery("textarea#message").val();
var thought = $("#message").val();
alert(thought);
});
Make sure your escaping the HTML characters
E.g.
// Always check an input variable is set before you use it
if (isset($_POST['contact_list'])) {
// Escape any html characters
echo htmlentities($_POST['contact_list']);
}
This would occur because of the angle brackets and the browser thinking they are tags.
other.component.ts
So final correct solution is :
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
/* 'router' it must be in small case */
@Component({
selector: 'app-other',
templateUrl: './other.component.html',
styleUrls: ['./other.component.css']
})
export class OtherComponent implements OnInit {
public href: string = "";
url: string = "asdf";
constructor(private router : Router) {} // make variable private so that it would be accessible through out the component
ngOnInit() {
this.href = this.router.url;
console.log(this.router.url);
}
}
Complile a Java file to generate a class:
javac filename.java
Execute the generated class:
java filename
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
});
});</script>
</body>
</html>
The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here
For those whom this did not work, here is how I hid the labels on the X-axis-
options: {
maintainAspectRatio: false,
layout: {
padding: {
left: 1,
right: 2,
top: 2,
bottom: 0,
},
},
scales: {
xAxes: [
{
time: {
unit: 'Areas',
},
gridLines: {
display: false,
drawBorder: false,
},
ticks: {
maxTicksLimit: 7,
display: false, //this removed the labels on the x-axis
},
'dataset.maxBarThickness': 5,
},
],
With the assumption that there's only one element:
$("#grid_GridHeader")[0]
$("#grid_GridHeader").get(0)
$("#grid_GridHeader").get()
...are all equivalent, returning the single underlying element.
From the jQuery source code, you can see that get(0)
, under the covers, essentially does the same thing as the [0]
approach:
// Return just the object
( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
I had the same problem.Please Follow below steps :
1- Open applicationhost file in Documents\IISExpress\config and add below code if it's not exist
<site name="solutionname" id="2">
<application path="/" applicationPool="solutionname">
<virtualDirectory path="/" physicalPath="physicaladdressofproject" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:xxxx:localhost" />
</bindings>
</site>
2- Then go to the root file of your project and delete all of updates are done on the project by using different version of Visual Stdio
3- Next go to [root].vs\config and delete applicationhost it will be created automatically
4-Run the project
It worked for me.
If you haven't yet figured out a way, use the associative property of JavaScript objects to add an extend function to the Object.prototype
as shown below.
Object.prototype.extend = function(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
this[i] = obj[i];
}
}
};
You can then use this function as shown below.
var o = { member: "some member" };
var x = { extension: "some extension" };
o.extend(x);
You can actually index directly into the Attributes collection (if you are using C# not VB):
foreach (XmlNode xNode in nodeListName)
{
XmlNode parent = xNode.ParentNode;
if (parent.Attributes != null
&& parent.Attributes["split"] != null)
{
parentSplit = parent.Attributes["split"].Value;
}
}
while it might not matter now here is a function which generate a float between 2 values.
#include <math.h>
float func_Uniform(float left, float right) {
float randomNumber = sin(rand() * rand());
return left + (right - left) * fabs(randomNumber);
}
If
side_effect_func
is a function then whatever that function returns is what calls to the mock return. Theside_effect_func
function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:>>> def side_effect_func(value): ... return value + 1 ... >>> m = MagicMock(side_effect=side_effect_func) >>> m(1) 2 >>> m(2) 3 >>> m.mock_calls [call(1), call(2)]
The problem was the table width. I had used width: 100%
for the table. The table columns are adjusted automatically after removing the width tag.
Didn't find any solution that would work with UTF-8 characters. String.fromCharCode
is good until you meet 2 byte character.
For example Hüser will come as [0x44,0x61,0x6e,0x69,0x65,0x6c,0x61,0x20,0x48,0xc3,0xbc,0x73,0x65,0x72]
But if you go through it with String.fromCharCode
you will have Hüser as each byte will be converted to a char separately.
Currently I'm using following solution:
function pad(n) { return (n.length < 2 ? '0' + n : n); }
function decodeUtf8(data) {
return decodeURIComponent(
data.map(byte => ('%' + pad(byte.toString(16)))).join('')
);
}
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
Actually if you need to test background fetch you need to enable one option in scheme:
Another way how you can test it:
Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html
Another option is doing the following:
public class UserList extends List<User>{
}
public <T> T magicalListGetter(Class<T> clazz) {
List<?> list = doMagicalVooDooHere();
return (T)list;
}
List<User> users = magicalListGetter(UserList.class);
`
If you are still not getting device token, try putting following code so to register your device for push notification.
It will also work on ios8 or more.
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([UIApplication respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
}
#else
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
#endif
Your first requirement, how to clear or redraw whole canvas - Answer - use canvas.drawColor(color.Black) method for clearing the screen with a color of black or whatever you specify .
Your second requirement, how to update part of the screen - Answer - for example if you want to keep all other things unchanged on the screen but in a small area of screen to show an integer(say counter) which increases after every five seconds. then use canvas.drawrect method to draw that small area by specifying left top right bottom and paint. then compute your counter value(using postdalayed for 5 seconds etc., llike Handler.postDelayed(Runnable_Object, 5000);) , convert it to text string, compute the x and y coordinate in this small rect and use text view to display the changing counter value.
Based on the answer of Stephen Cagle I added support for nested test modules.
import fnmatch
import os
import unittest
def all_test_modules(root_dir, pattern):
test_file_names = all_files_in(root_dir, pattern)
return [path_to_module(str) for str in test_file_names]
def all_files_in(root_dir, pattern):
matches = []
for root, dirnames, filenames in os.walk(root_dir):
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
return matches
def path_to_module(py_file):
return strip_leading_dots( \
replace_slash_by_dot( \
strip_extension(py_file)))
def strip_extension(py_file):
return py_file[0:len(py_file) - len('.py')]
def replace_slash_by_dot(str):
return str.replace('\\', '.').replace('/', '.')
def strip_leading_dots(str):
while str.startswith('.'):
str = str[1:len(str)]
return str
module_names = all_test_modules('.', '*Tests.py')
suites = [unittest.defaultTestLoader.loadTestsFromName(mname) for mname
in module_names]
testSuite = unittest.TestSuite(suites)
runner = unittest.TextTestRunner(verbosity=1)
runner.run(testSuite)
The code searches all subdirectories of .
for *Tests.py
files which are then loaded. It expects each *Tests.py
to contain a single class *Tests(unittest.TestCase)
which is loaded in turn and executed one after another.
This works with arbitrary deep nesting of directories/modules, but each directory in between needs to contain an empty __init__.py
file at least. This allows the test to load the nested modules by replacing slashes (or backslashes) by dots (see replace_slash_by_dot
).
For future friendliness, I second the recommendation for classList with polyfill/shim: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#wrapper
var elem = document.getElementById( 'some-id' );
elem.classList.add('some-class'); // Add class
elem.classList.remove('some-other-class'); // Remove class
elem.classList.toggle('some-other-class'); // Add or remove class
if ( elem.classList.contains('some-third-class') ) { // Check for class
console.log('yep!');
}
The basic difference is next() is used for gettting the input till the delimiter is encountered(By default it is whitespace,but you can also change it) and return the token which you have entered.The cursor then remains on the Same line.Whereas in nextLine() it scans the input till we hit enter button and return the whole thing and places the cursor in the next line. **
Scanner sc=new Scanner(System.in);
String s[]=new String[2];
for(int i=0;i<2;i++){
s[i]=sc.next();
}
for(int j=0;j<2;j++)
{
System.out.println("The string at position "+j+ " is "+s[j]);
}
**
Try running this code by giving Input as "Hello World".The scanner reads the input till 'o' and then a delimiter occurs.so s[0] will be "Hello" and cursor will be pointing to the next position after delimiter(that is 'W' in our case),and when s[1] is read it scans the "World" and return it to s[1] as the next complete token(by definition of Scanner).If we use nextLine() instead,it will read the "Hello World" fully and also more till we hit the enter button and store it in s[0]. We may give another string also by using nextLine(). I recommend you to try using this example and more and ask for any clarification.
If you are inheriting UITableViewController, you can just init tableView again.
Objective C:
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
Swift:
self.tableView = UITableView(frame: CGRect.zero, style: .grouped)