As of 2017 I post to a rest service and getting the results from it like that:
var loginModel = new LoginModel();
loginModel.DatabaseName = "TestDB";
loginModel.UserGroupCode = "G1";
loginModel.UserName = "test1";
loginModel.Password = "123";
var client = new RestClient(BaseUrl);
var request = new RestRequest("/Connect?", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(loginModel);
var response = client.Execute(request);
var obj = JObject.Parse(response.Content);
LoginResult result = new LoginResult
{
Status = obj["Status"].ToString(),
Authority = response.ResponseUri.Authority,
SessionID = obj["SessionID"].ToString()
};
You want to use a Set
or List
implementation (e.g. HashSet
, TreeSet
, etc, or ArrayList
, LinkedList
, etc..), since Java does not have dynamically sized arrays.
List<String> zoom = new ArrayList<>();
zoom.add("String 1");
zoom.add("String 2");
for (String z : zoom) {
System.err.println(z);
}
Edit: Here is a more succinct way to initialize your List with an arbitrary number of values using varargs:
List<String> zoom = Arrays.asList("String 1", "String 2", "String n");
Copy the .war file (E.g.: prj.war) to %CATALINA_HOME%\webapps
( E.g.: C:\tomcat\webapps )
Run %CATALINA_HOME%\bin\startup.bat
Your .war file will be extracted automatically to a folder that has the same name (without extension) (E.g.: prj)
Go to %CATALINA_HOME%\conf\server.xml
and take the port for the HTTP protocol. <Connector port="8080" ... />
. The default value is 8080.
Access the following URL:
[<protocol>://]localhost:<port>/folder/resourceName
(E.g.: localhost:8080/folder/resourceName
)
Don't try to access the URL without the resourceName
because it won't work if there is no file like index.html
, or if there is no url pattern like "/
" or "/*
" in web.xml.
The available main paths are here: [<protocol>://]localhost:<port>/manager/html
(E.g.: http://localhost:8080/manager/html
) and they have true
on the "Running" column.
Go to [<protocol>://]localhost:<port>/manager/html/
(usually localhost:8080/manager/html/
)
This is also achievable from [<protocol>://]localhost:<port>
> Manager App)
If you get:
403 Access Denied
go to %CATALINA_HOME%\conf\tomcat-users.xml
and check that you have enabled a line like this:
<user username="tomcat" password="tomcat" roles="tomcat,role1,manager-gui"/>
In the Deploy section, WAR file to deploy subsection, click on Browse....
Select the .war file (E.g.: prj.war) > click on Deploy.
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
You will need to melt
your dataframe to get it into the so-called long format:
require(reshape2)
sample.data.M <- melt(sample.data)
Now your field values are represented by their own rows and identified through the variable column. This can now be leveraged within the ggplot aesthetics:
require(ggplot2)
c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
c + geom_bar(stat = "identity")
Instead of stacking you may also be interested in showing multiple plots using facets:
c <- ggplot(sample.data.M, aes(x = Rank, y = value))
c + facet_wrap(~ variable) + geom_bar(stat = "identity")
imageView.setImageResource(R.drawable.picname);
You have to add a CSP meta tag in the head section of your app's index.html
As per https://github.com/apache/cordova-plugin-whitelist#content-security-policy
Content Security Policy
Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly).
On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g.
<video>
& WebSockets are not blocked). So, in addition to the whitelist, you should use a Content Security Policy<meta>
tag on all of your pages.On Android, support for CSP within the system webview starts with KitKat (but is available on all versions using Crosswalk WebView).
Here are some example CSP declarations for your
.html
pages:<!-- Good default declaration: * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: * Enable inline JS: add 'unsafe-inline' to default-src * Enable eval(): add 'unsafe-eval' to default-src --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *"> <!-- Allow requests to foo.com --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com"> <!-- Enable all requests, inline styles, and eval() --> <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"> <!-- Allow XHRs via https only --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' https:"> <!-- Allow iframe to https://cordova.apache.org/ --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org">
int number = -1;
int holdingDigits = 7;
System.out.println(String.format("%0"+ holdingDigits +"d", number));
Just asked this in an interview........
My answer below but this (mentioned above) is much nicer->
String.format("%05d", num);
My answer is:
static String leadingZeros(int num, int digitSize) {
//test for capacity being too small.
if (digitSize < String.valueOf(num).length()) {
return "Error : you number " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";
//test for capacity will exactly hold the number.
} else if (digitSize == String.valueOf(num).length()) {
return String.valueOf(num);
//else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError
//else calculate and return string
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < digitSize; i++) {
sb.append("0");
}
sb.append(String.valueOf(num));
return sb.substring(sb.length() - digitSize, sb.length());
}
}
The data.table
package has its IDate
class and functionalities similar to lubridate
or the zoo
package. You could do:
dt = data.table(
Name = c('Joe', 'Amy', 'John'),
JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
AmtPaid = c(1000, 100, 200)
)
require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]
Use enumerate:
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
Its also possible to just create a matplotlib figure
object and then use plt.savefig(...)
:
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure
For array of multiple arrays and ES6, use
Array.prototype.concat(...arr);
For example:
const arr = [[1, 2, 3], [4, 5, 6], [7, 8 ,9]];
const newArr = Array.prototype.concat(...arr);
// output: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
u could try this it produces randomly generated array of true and false :
a=[bool(i) for i in np.array(np.random.randint(0,2,10))]
out: [True, True, True, True, True, False, True, False, True, False]
Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.
For example, using GridBagLayout:
import java.awt.*;
import javax.swing.*;
public class LayoutEg1 extends JPanel{
private static final int ROWS = 10;
public LayoutEg1() {
setLayout(new GridBagLayout());
for (int i = 0; i < ROWS; i++) {
GridBagConstraints gbc = makeGbc(0, i);
JLabel label = new JLabel("Row Label " + (i + 1));
add(label, gbc);
JPanel panel = new JPanel();
panel.add(new JCheckBox("check box"));
panel.add(new JTextField(10));
panel.add(new JButton("Button"));
panel.setBorder(BorderFactory.createEtchedBorder());
gbc = makeGbc(1, i);
add(panel, gbc);
}
}
private GridBagConstraints makeGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = x;
gbc.weighty = 1.0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
return gbc;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Layout Eg1");
frame.getContentPane().add(new LayoutEg1());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
I see permutation has been suggested. In fact it can be made into one line:
>>> A = np.random.randint(5, size=(10,3))
>>> np.random.permutation(A)[:2]
array([[0, 3, 0],
[3, 1, 2]])
This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:
git co master
git pull
Which fetched those changes. Then,
git co develop
git pull
Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.
In your 'head' section, add this code:
<style>
input[type='text'] { font-size: 24px; }
</style>
Or you can only add the:
input[type='text'] { font-size: 24px; }
to a CSS file which can later be included.
You can also change the font face by using the CSS property: font-family
font-family: monospace;
So you can have a CSS code like this:
input[type='text'] { font-size: 24px; font-family: monospace; }
You can find further help at the W3Schools website.
I suggest you to have a look at the CSS3 specification. With CSS3 you can also load a font from the web instead of having the limitation to use only the most common fonts or tell the user to download the font you're using.
No, there is no way to do this yet. I wish they add a future like this in browsers.
EDIT:
Now there is a Full Screen API for the web You can requestFullscreen
on an Video or Canvas element to ask user to give you permisions and make it full screen.
Let's consider this element:
<video controls id="myvideo">
<source src="somevideo.webm"></source>
<source src="somevideo.mp4"></source>
</video>
We can put that video into fullscreen mode with script like this:
var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
}
I've tried to answer this question in a more complete way, and I ended up creating a complete script with options to help you understand the find
command.
The script oldfiles
is in this repository
To "create" a new find command you run it with the option -n
(dry-run), and it will print to you the correct find
command you need to use.
Of course, if you omit the -n
it will just run, no need to retype the find
command.
$ oldfiles [-v...] ([-h|-V|-n] | {[(-a|-u) | (-m|-t) | -c] (-i | -d | -o| -y | -g) N (-\> | -\< | -\=) [-p "pat"]})
-h, --help : Show this help.
-V, --version : Show version.
-v, --verbose : Turn verbose mode on (cumulative).
-n, --dry-run : Do not run, just explain how to create a "find" command
-a or -u : access (use) time
-m or -t : modification time (default)
-c : inode status change
-i N : minutes (default, with N equal 1 min)
-d N : days
-o N : months
-y N : years
-g N : N is a DATE (example: "2017-07-06 22:17:15")
-p "pat" : optional pattern to match (example: -p "*.c" to find c files) (default -p "*")
-\> : file is newer than given range, ie, time modified after it.
-\< : file is older than given range, ie, time is from before it. (default)
-\= : file that is exactly N (min, day, month, year) old.
$ oldfiles -a -i 10 -p"*.c" -\> -nvvv
Starting oldfiles script, by beco, version 20170706.202054...
$ oldfiles -vvv -a -i 10 -p "*.c" -\> -n
Looking for "*.c" files with (a)ccess time newer than 10 minute(s)
find . -name "*.c" -type f -amin -10 -exec ls -ltu --time-style=long-iso {} +
Dry-run
$ oldfiles -m -o 1 -p"*.h" -\< -nvv
Starting oldfiles script, by beco, version 20170706.202054...
$ oldfiles -vv -m -o 1 -p "*.h" -\< -n
find . -name "*.h" -type f -mtime +30 -exec ls -lt --time-style=long-iso {} +
Dry-run
$ oldfiles -mng "2016-12-01" -\=
find . -name "*" -type f -newermt "2016-11-30 23:59:59" ! -newermt "2016-12-01 23:59:59" -exec ls -lt --time-style=long-iso {} +
Of course, removing the -n
the program will run the find
command itself and save you the trouble.
I hope this helps everyone finally learn this {a,c,t}{time,min}
options.
You will also notice that the "ls" option ls OPT
changes to match the type of time you choose.
oldfiles
script:I just want to add something here: changing the title via JavaScript is actually useful if you're updating a database via AJAX, so then the title changes without you having to refresh the page. The title actually changes via your server side scripting language, but having it change via JavaScript is just a usability and UI thing that makes the user experience more enjoyable and fluid.
Now, if you're changing the title via JavaScript just for the hell of it, then you should not be doing that.
First of all, you need not do var r = this;
as this in if statement
refers to the context of the callback itself which since you are using arrow function refers to the React component context.
history objects typically have the following properties and methods:
- length - (number) The number of entries in the history stack
- action - (string) The current action (PUSH, REPLACE, or POP)
location - (object) The current location. May have the following properties:
- pathname - (string) The path of the URL
- search - (string) The URL query string
- hash - (string) The URL hash fragment
- state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
- push(path, [state]) - (function) Pushes a new entry onto the history stack
- replace(path, [state]) - (function) Replaces the current entry on the history stack
- go(n) - (function) Moves the pointer in the history stack by n entries
- goBack() - (function) Equivalent to go(-1)
- goForward() - (function) Equivalent to go(1)
- block(prompt) - (function) Prevents navigation
So while navigating you can pass props to the history object like
this.props.history.push({
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
})
or similarly for the Link
component or the Redirect
component
<Link to={{
pathname: '/template',
search: '?query=abc',
state: { detail: response.data }
}}> My Link </Link>
and then in the component which is rendered with /template
route, you can access the props passed like
this.props.location.state.detail
Also keep in mind that, when using history or location objects from props you need to connect the component with withRouter
.
withRouter
You can get access to the history object’s properties and the closest
<Route>'s
match via thewithRouter
higher-order component.withRouter
will re-render its component every time the route changes with the same props as<Route>
renderprops: { match, location, history }
.
I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8;
I used System.nanoTime()
for measurements.
I got the same time on both cases - around 1.564 seconds.
So, it looks like Netbeans has bad performance on print to console.
After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println
command), demonstrated by this code:
for (int i = 0; i < 1000; i++) {
long t1 = System.nanoTime();
System.out.print("BBB......BBB"); \\<-contain 1000 "B"
long t2 = System.nanoTime();
System.out.println(t2-t1);
System.out.println("");
}
The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.
And so on..
You should provide the second database information in `application/config/database.php´
Normally, you would set the default
database group, like so:
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
Notice that the login information and settings are provided in the array named $db['default']
.
You can then add another database in a new array - let's call it 'otherdb'.
$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = TRUE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;
Now, to actually use the second database, you have to send the connection to another variabel that you can use in your model:
function my_model_method()
{
$otherdb = $this->load->database('otherdb', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.
$query = $otherdb->select('first_name, last_name')->get('person');
var_dump($query);
}
That should do it. The documentation for connecting to multiple databases can be found here: http://codeigniter.com/user_guide/database/connecting.html
In Swift 4
let array:[String] = ["Apple", "Pear ","Orange"]
array.joined(separator: " ")
The --no-ff
option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff
.
If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.
For example, the author of this article thinks that --no-ff
option should be default and his reasoning is close to that I outlined above:
Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff
, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff
is not used], whereas it is easily done if the --no-ff
flag was used [because it's just one commit]."
Use the FIND_IN_SET function:
SELECT t.*
FROM YOUR_TABLE t
WHERE FIND_IN_SET(3, t.ids) > 0
trick string to boolean conversion in javascript. e.g.
var bool= "true";
console.log(bool==true) //false
var bool_con = JSON.parse(bool);
console.log(bool_con==true) //true
If you actually create the buffer as per dirks suggestion, then:
int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE);
may completely fill the buffer, possibly overwriting the terminating zero character which you depend on when extracting to a stringstream. You need:
int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE - 1 );
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
The key is to use the reset_index() method.
Use:
import pandas
df1 = pandas.DataFrame( {
"Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] ,
"City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } )
g1 = df1.groupby( [ "Name", "City"] ).count().reset_index()
Now you have your new dataframe in g1:
This is an old post but regardless, you can also get boldface and italic characters by leveraging utf-32. There are even greek and math symbols that can be used as well as the roman alphabet.
sklearn.cross_validation
is now changed to sklearn.model_selection
Just change
sklearn.cross_validation
to
sklearn.model_selection
You need to use the reserve function to set an initial allocated size or do it in the initial constructor.
vector<CustomClass *> content(20000);
or
vector<CustomClass *> content;
...
content.reserve(20000);
When you reserve()
elements, the vector
will allocate enough space for (at least?) that many elements. The elements do not exist in the vector
, but the memory is ready to be used. This will then possibly speed up push_back()
because the memory is already allocated.
This is what worked for me:
.pdf::before {
content: url('path/to/image.png');
display: flex;
align-items: center;
justify-content: center;
height: inherit;
}
you should give permission on your db
grant execute on (packageName or tableName) to user;
If you do not use the transaction logs for restores (i.e. You only ever do full backups), you can set Recovery Mode to "Simple", and the transaction log will very shortly shrink and never fill up again.
If you are using SQL 7 or 2000, you can enable "truncate log on checkpoint" in the database options tab. This has the same effect.
This is not recomended in production environments obviously, since you will not be able to restore to a point in time.
The problem with your query is that in CASE
expressions, the THEN
and ELSE
parts have to have an expression that evaluates to a number or a varchar or any other datatype but not to a boolean value.
You just need to use boolean logic (or rather the ternary logic that SQL uses) and rewrite it:
WHERE
DateDropped = 0
AND ( @JobsOnHold = 1 AND DateAppr >= 0
OR (@JobsOnHold <> 1 OR @JobsOnHold IS NULL) AND DateAppr <> 0
)
http://en.wikipedia.org/wiki/Uname
All the info you'll ever need. Google is your friend.
Use uname -s
to query the system name.
Darwin
CYGWIN_...
LINUX
for mostThe usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:
Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.
There are many variants to versioning. It all boils down to personal preference.
For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.
If you create a new repository from the Github web GUI, you sometimes get the name 'main' instead of 'master'. By using the command git status
from your terminal you'd see which location you are. In some cases, you'd see origin/main
.
If you are trying to push your app to a cloud service via CLI then use 'main', not 'master'.
example:
git push heroku main
If you add an abbr
instead of an alias
you'll get better auto-complete. In fish abbr
more closely matches the behavior of a bash alias.
abbr -a gco git checkout
Will -a
dd a new abbr
eviation gco
that expands to git checkout
.
Casting int to char is done simply by assigning with the type in parenthesis:
int i = 65535;
char c = (char)i;
Note: I thought that you might be losing data (as in the example), because the type sizes are different.
Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h>
functions like strcat
or sprintf
.
I run pre-startup stuff like migrations in a separate ephemeral container, like so (note, compose file has to be of version '2' type):
db:
image: postgres
web:
image: app
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
links:
- db
depends_on:
- migration
migration:
build: .
image: app
command: python manage.py migrate
volumes:
- .:/code
links:
- db
depends_on:
- db
This helps things keeping clean and separate. Two things to consider:
You have to ensure the correct startup sequence (using depends_on).
You want to avoid multiple builds which is achieved by tagging it the first time round using build and image; you can refer to image in other containers then.
You can use :
var MSIE = jQuery.support.leadingWhitespace; // This property is not supported by ie 6-8
$(document).ready(function(){
if (MSIE){
if (navigator.vendor == 'Apple Computer, Inc.'){
// some code for this navigator
} else {
// some code for others browsers
}
} else {
// default code
}});
Axivion Bauhaus Suite is a static analysis tool that works with C# (as well as C, C++ and Java).
It provides the following capabilities:
These features can be run on a one-off basis or as part of a Continuous Integration process. Issues can be highlighted on a per project basis or per developer basis when the system is integrated with a source code control system.
sudo find / -Bmin 60
From the man
page:
-Bmin n
True if the difference between the time of a file's inode creation and the time
find
was started, rounded up to the next full minute, is n minutes.
Obviously, you may want to set up a bit differently, but this primary seems the best solution for searching for any file created in the last N minutes.
Looking at your example, I think this is what you want:
var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);
$('#new_user_form').find('input').each(function(){
//your code here
});
You can use "Date.parse()" to properly compare the dates, but since in most of the comments people are trying to split the string and then trying to add up the digits and compare with obviously wrong logic -not completely.
Here's the trick. If you are breaking the string then compare the parts in nested format.
Compare year with year, month with month and day with day.
<pre><code>
var parts1 = "26/07/2020".split('/');
var parts2 = "26/07/2020".split('/');
var latest = false;
if (parseInt(parts1[2]) > parseInt(parts2[2])) {
latest = true;
} else if (parseInt(parts1[2]) == parseInt(parts2[2])) {
if (parseInt(parts1[1]) > parseInt(parts2[1])) {
latest = true;
} else if (parseInt(parts1[1]) == parseInt(parts2[1])) {
if (parseInt(parts1[0]) >= parseInt(parts2[0])) {
latest = true;
}
}
}
return latest;
</code></pre>
Every minor version of Python, that is any 3.x and 2.x version, will install side-by-side with other versions on your computer. Only patch versions will upgrade existing installations.
So if you want to keep your installed Python 2.7 around, then just let it and install a new version using the installer. If you want to get rid of Python 2.7, you can uninstall it before or after installing a newer version—there is no difference to this.
Current Python 3 installations come with the py.exe
launcher, which by default is installed into the system directory. This makes it available from the PATH, so you can automatically run it from any shell just by using py
instead of python
as the command. This avoids you having to put the current Python installation into PATH yourself. That way, you can easily have multiple Python installations side-by-side without them interfering with each other. When running, just use py script.py
instead of python script.py
to use the launcher. You can also specify a version using for example py -3
or py -3.6
to launch a specific version, otherwise the launcher will use the current default (which will usually be the latest 3.x).
Using the launcher, you can also run Python 2 scripts (which are often syntax incompatible to Python 3), if you decide to keep your Python 2.7 installation. Just use py -2 script.py
to launch a script.
As for PyPI packages, every Python installation comes with its own folder where modules are installed into. So if you install a new version and you want to use modules you installed for a previous version, you will have to install them first for the new version. Current versions of the installer also offer you to install pip
; it’s enabled by default, so you already have pip
for every installation. Unless you explicitly add a Python installation to the PATH, you cannot just use pip
though. Luckily, you can also simply use the py.exe
launcher for this: py -m pip
runs pip
. So for example to install Beautiful Soup for Python 3.6, you could run py -3.6 -m pip install beautifulsoup4
.
import java.util.Scanner;
class Array {
public static void main(String a[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
System.out.println("Enter the Element "+num+" of an Array");
double[] numbers = new double[num];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
for (int i = 0; i < numbers.length; i++)
{
if ( (i%3) !=0){
System.out.print("");
System.out.print(numbers[i]+"\t");
} else {
System.out.println("");
System.out.print(numbers[i]+"\t");
}
}
}
If you are willing to use std::array
instead of built-in arrays, you may use:
std::array<int, 5> iar1 = {1,2,3,4,5};
std::array<int, 5> iar2 = {1,2,3,4,5};
if (iar1 == iar2)
You could use cursor.lastrowid (see "Optional DB API Extensions"):
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
username varchar(50),
password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('test','test'))
print(cursor.lastrowid)
# 1
If two people are inserting at the same time, as long as they are using different cursor
s, cursor.lastrowid
will return the id
for the last row that cursor
inserted:
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('blah','blah'))
cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('blah','blah'))
print(cursor2.lastrowid)
# 3
print(cursor.lastrowid)
# 2
cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
(100,'blah','blah'))
print(cursor.lastrowid)
# 100
Note that lastrowid
returns None
when you insert more than one row at a time with executemany
:
cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
(('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None
I had the same error message from spring's @RestController
. My rest controller class was using spring's JpaRepository
class and by replacing repository.getOne(id)
method call with repository.findOne(id)
problem was gone.
fmt.SprintF function returns a string and you can format the string the very same way you would have with fmt.PrintF
If you using Bootstrap:
The current version of Bootstrap (3.0.2) (with jQuery 1.10.2 & Chrome) seems to generate this warning as well.
(It does so on Twitter too, BTW.)
The current version of Bootstrap (3.1.0) no longer seems to generate this warning.
You can do both in code and XML. Only 4 basic things to be set.
e.g.
android:shadowColor="@color/text_shadow_color"
android:shadowDx="-2"
android:shadowDy="2"
android:shadowRadius="0.01"
This draws a prominent shadow on left-lower side of text. In code, you can add something like this;
TextView item = new TextView(getApplicationContext());
item.setText(R.string.text);
item.setTextColor(getResources().getColor(R.color.general_text_color));
item.setShadowLayer(0.01f, -2, 2, getResources().getColor(R.color.text_shadow_color));
I like the idea of telling the user to put his phone back into portrait mode. Like it's mentioned here: http://tech.sarathdr.com/featured/prevent-landscape-orientation-of-iphone-web-apps/ ...but utilising CSS instead of JavaScript.
Open libraries/Input.php
(system/core/Input.php
in CI version 2.0+
) and locate function _clean_input_keys($str){
,
Modify if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
to if ( ! preg_match("/^[a-z0-9:_\-|]+$/i", $str))
Set the define character to something other than &
SET DEFINE ~ create table blah (x varchar(20)); insert into blah (x) values ('blah&'); select * from blah; X -------------------- blah&
You could use the "FindString.." functions:
Public Class Form1
Public Enum Test
pete
jack
fran
bill
End Enum
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = [Enum].GetValues(GetType(Test))
ComboBox1.SelectedIndex = ComboBox1.FindStringExact("jack")
ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Test.jack.ToString())
ComboBox1.SelectedIndex = ComboBox1.FindStringExact([Enum].GetName(GetType(Test), Test.jack))
ComboBox1.SelectedItem = Test.bill
End Sub
End Class
Here is a very simple way:
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True"
CommandArgument='<%# Container.DataItemIndex %>' />
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
-> Add a permission to read contacts data to your application manifest.
<uses-permission android:name="android.permission.READ_CONTACTS"/>
-> Use Intent.Action_Pick in your Activity like below
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
-> Then Override the onActivityResult()
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
Cursor cursor = null;
try {
String phoneNo = null ;
String name = null;
Uri uri = data.getData();
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
phoneNo = cursor.getString(phoneIndex);
textView2.setText(phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
This will work check it out
You can do that with a single line of code nowadays. Create the arrayList and the Path object representing the file where you want to write into:
Path out = Paths.get("output.txt");
List<String> arrayList = new ArrayList<> ( Arrays.asList ( "a" , "b" , "c" ) );
Create the actual file, and fill it with the text in the ArrayList:
Files.write(out,arrayList,Charset.defaultCharset());
It should be CascadeType.Merge, in that case it will update if the record already exists.
private void Log(string s , Color? c = null)
{
richTextBox.SelectionStart = richTextBox.TextLength;
richTextBox.SelectionLength = 0;
richTextBox.SelectionColor = c ?? Color.Black;
richTextBox.AppendText((richTextBox.Lines.Count() == 0 ? "" : Environment.NewLine) + DateTime.Now + "\t" + s);
richTextBox.SelectionColor = Color.Black;
}
Just to continue to all the answers that were given here, especially @James Lanes
the size of the integer type can be expressed by this formula:
total range = (2 ^ bit system)
lower limit = -(2 ^ bit system)*0.5 upper limit = ((2 ^ bit system)*0.5) - 1
This is about recent additions to AngularJS, to serve as future answer (also for another question).
Angular newer versions (now in 1.3 beta), AngularJS natively supports this option, using ngModelOptions
, like
ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"
Example:
<input type="text" name="username"
ng-model="user.name"
ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0} }" />
This works for me. Has a nice delayed action going on.
var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;
$(document).mousemove(function(e){
$mouseX = e.pageX;
$mouseY = e.pageY;
});
var $loop = setInterval(function(){
// change 12 to alter damping higher is slower
$xp += (($mouseX - $xp)/12);
$yp += (($mouseY - $yp)/12);
$("#moving_div").css({left:$xp +'px', top:$yp +'px'});
}, 30);
Nice and simples
This fiddle shows how
ul, li {
display:inline
}
Great references on lists and css here:
Add two datasets containing datatables, now it will merge as required
DataSet ds1 = new DataSet();
DataSet ds2 = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add(new DataColumn("Column1", typeof(System.String)));
DataRow newSelRow1 = dt1.NewRow();
newSelRow1["Column1"] = "Select";
dt1.Rows.Add(newSelRow1);
DataTable dt2 = new DataTable();
dt2.Columns.Add(new DataColumn("Column1", typeof(System.String)));
DataRow newSelRow2 = dt1.NewRow();
newSelRow2["Column1"] = "DataRow1Data"; // Data
dt2.Rows.Add(newSelRow2);
ds1.Tables.Add(dt1);
ds2.Tables.Add(dt2);
ds1.Tables[0].Merge(ds2.Tables[0]);
Now ds1 will have the merged data
You can use lambda to bind a method to an instance:
def run(self):
print self._instanceString
class A(object):
def __init__(self):
self._instanceString = "This is instance string"
a = A()
a.run = lambda: run(a)
a.run()
Output:
This is instance string
Since SHA-1 maps several byte sequences to one, you can't "decrypt" a hash, but in theory you can find collisions: strings that have the same hash.
It seems that breaking a single hash would cost about 2.7 million dollars worth of computer time currently, so your efforts are probably better spent somewhere else.
LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");
list.sort(String::compareToIgnoreCase);
Another option would be using lambda expressions:
list.sort((o1, o2) -> o1.compareToIgnoreCase(o2));
use typescript for your coding, because it's object oriented, strictly typed and easy to maintain the code ...
for more info about typescipt click here
Here one simple example I have created to share data between two controller using Typescript...
module Demo {
//create only one module for single Applicaiton
angular.module('app', []);
//Create a searvie to share the data
export class CommonService {
sharedData: any;
constructor() {
this.sharedData = "send this data to Controller";
}
}
//add Service to module app
angular.module('app').service('CommonService', CommonService);
//Create One controller for one purpose
export class FirstController {
dataInCtrl1: any;
//Don't forget to inject service to access data from service
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl1 = this.commonService.sharedData;
}
}
//add controller to module app
angular.module('app').controller('FirstController', FirstController);
export class SecondController {
dataInCtrl2: any;
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl2 = this.commonService.sharedData;
}
}
angular.module('app').controller('SecondController', SecondController);
}
Default constructors -- public constructors with out arguments (either declared or implied) -- are inherited by default. You can try the following code for an example of this:
public class CtorTest {
public static void main(String[] args) {
final Sub sub = new Sub();
System.err.println("Finished.");
}
private static class Base {
public Base() {
System.err.println("In Base ctor");
}
}
private static class Sub extends Base {
public Sub() {
System.err.println("In Sub ctor");
}
}
}
If you want to explicitly call a constructor from a super class, you need to do something like this:
public class Ctor2Test {
public static void main(String[] args) {
final Sub sub = new Sub();
System.err.println("Finished.");
}
private static class Base {
public Base() {
System.err.println("In Base ctor");
}
public Base(final String toPrint) {
System.err.println("In Base ctor. To Print: " + toPrint);
}
}
private static class Sub extends Base {
public Sub() {
super("Hello World!");
System.err.println("In Sub ctor");
}
}
}
The only caveat is that the super() call must come as the first line of your constructor, else the compiler will get mad at you.
The easiest way I've found to do this is to write in markdown right from the start of the line. Press Ctrl+D
(shortcut for opening the markup input dialog) and type markdown. The normal wiki editor doesn't seem to be very good for precise formatting. It doesn't seem to know much about character styles and only knows paragraph styles.
How to make the char in the recursion at the end:
public static String removeChar(String word, char charToRemove)
{
String char_toremove=Character.toString(charToRemove);
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == charToRemove)
{
String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord,charToRemove);
}
}
System.out.println(word);
return word;
}
for exemple:
removeChar ("hello world, let's go!",'l') ? "heo word, et's go!llll"
removeChar("you should not go",'o') ? "yu shuld nt goooo"
I'm not sure why your current code is failing (what is the Exception you get?), but I would like to point out this approach performs O(N-squared). Consider pre-sorting your input arrays (if they are not defined to be pre-sorted) and merging the sorted arrays:
http://www.algolist.net/Algorithms/Merge/Sorted_arrays
Sorting is generally O(N logN) and the merge is O(m+n).
One way to do this by updating the app.locals
variable for that app in app.js
Set via following
var app = express();
app.locals.appName = "DRC on FHIR";
Get / Access
app.listen(3000, function () {
console.log('[' + app.locals.appName + '] => app listening on port 3001!');
});
Elaborating with a screenshot from @RamRovi example with slight enhancement.
You have to indent the docstring after the function definition there (line 3, 4):
def print_lol(the_list):
"""this doesn't works"""
print 'Ain't happening'
Indented:
def print_lol(the_list):
"""this works!"""
print 'Aaaand it's happening'
Or you can use #
to comment instead:
def print_lol(the_list):
#this works, too!
print 'Hohoho'
Also, you can see PEP 257 about docstrings.
Hope this helps!
Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.
Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.
ssh kev@server1 './test/foo.sh'
Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).
When calling java use the -Xmx Flag for example -Xmx512m for 512 megs for the heap size. You may also want to consider the -xms flag to start the heap larger if you are going to have it grow right from the start. The default size is 128megs.
This does it in text.
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>_x000D_
_x000D_
<script type="text/javascript">_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
timeleft--;_x000D_
document.getElementById("countdowntimer").textContent = timeleft;_x000D_
if(timeleft <= 0)_x000D_
clearInterval(downloadTimer);_x000D_
},1000);_x000D_
</script>
_x000D_
The knitr::include_graphics solution worked well for resizing the figures, but I was unable to figure out how to use it to produce side-by-side resized figures. I found this post useful for doing so.
If you use SonarScanner CLI with Docker, you may have this error because the SonarScanner container can not access to the Sonar UI container.
Note that you will have the same error with a simple curl from another container:
docker run --rm byrnedo/alpine-curl 127.0.0.1:9000
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused
The solution is to connect the SonarScanner container to the same docker network of your sonar instance, for instance with --network=host
:
docker run --network=host -e SONAR_HOST_URL='http://127.0.0.1:9000' --user="$(id -u):$(id -g)" -v "$PWD:/usr/src" sonarsource/sonar-scanner-cli
(other parameters of this command comes from the SonarScanner CLI documentation)
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
The answer above is now obsolete with Unity 5 or newer. Use this instead!
GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);
I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...
public float playerSpeed; //allows us to be able to change speed in Unity
public Vector2 jumpHeight;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f); //makes player run
if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) //makes player jump
{
GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);
This makes it to where you can edit the jump height in Unity itself without having to go back to the script.
Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)
To do something after certain div load from function .load()
.
I think this exactly what you need:
$('#divIDer').load(document.URL + ' #divIDer',function() {
// call here what you want .....
//example
$('#mydata').show();
});
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
With the latest version of phpmyadmin 5.0.2+ at least
Check that the actual installation was completed correctly,
Mine had been copied over into a sub folder on a linux machine rather that being at the
/usr/share/phpmyadmin/
Replace this:
var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
$(this).select(); // This is where my problem is
});
With this:
$('#cbCategory').val(cat);
Calling val()
on a select list will automatically select the option with that value, if any.
A While
/Wend
loop can only be exited prematurely with a GOTO
or by exiting from an outer block (Exit sub
/function
or another exitable loop)
Change to a Do
loop instead:
Do While True
count = count + 1
If count = 10 Then
Exit Do
End If
Loop
Or for looping a set number of times:
for count = 1 to 10
msgbox count
next
(Exit For
can be used above to exit prematurely)
We also had to develop a solution which would even work with APIs requiring authentication (see this article)
Using AngularJS in a nutshell here is how we did it:
Step 1: Create a dedicated directive
// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
restrict: 'E',
templateUrl: '/path/to/pdfDownload.tpl.html',
scope: true,
link: function(scope, element, attr) {
var anchor = element.children()[0];
// When the download starts, disable the link
scope.$on('download-start', function() {
$(anchor).attr('disabled', 'disabled');
});
// When the download finishes, attach the data to the link. Enable the link and change its appearance.
scope.$on('downloaded', function(event, data) {
$(anchor).attr({
href: 'data:application/pdf;base64,' + data,
download: attr.filename
})
.removeAttr('disabled')
.text('Save')
.removeClass('btn-primary')
.addClass('btn-success');
// Also overwrite the download pdf function to do nothing.
scope.downloadPdf = function() {
};
});
},
controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
$scope.downloadPdf = function() {
$scope.$emit('download-start');
$http.get($attrs.url).then(function(response) {
$scope.$emit('downloaded', response.data);
});
};
}]
});
Step 2: Create a template
<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>
Step 3: Use it
<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>
This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.
Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.
Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml
to read your $_POST. You can use file_get_contents('php://input')
to get the raw post data as plain XML.
You might want to look at Quick-R, which has a lot of nice little tutorials on how you can do basic statistics in R. For example on correlations:
It is sad that something so simple and well defined became "opinion based" in this thread.
A HTTP server only knows of "entities", which is an abstraction for any content, be it a static web page, a list of search results, a list of other entities, a json description of something, a media file, etc etc.
Each such entity is expected to be identifiable by a unique URL, e.g.
If a server finds a resource by the given URL, it does not matter what its contents are -- 2G of data, null, {}, [] -- as long as it exists, it will be 200. But if such entity is not known to the server, it is EXPECTED to return 404 "Not Found".
One confusion seems to be from developers who think if the application has a handler for a certain path shape, it should not be an error. In the eyes of the HTTP protocol it does not matter what happened in the internals of the server (ie. whether the default router responded or a handler for a specific path shape), as long as there is no matching entity on the server to the requested URL (that requested MP3 file, webpage, user object etc), which would return valid contents (empty or otherwise), it must be 404 (or 410 etc).
Another point of confusion seems to be around "no data" and "no entity". The former is about content of an entity, and the latter about its existence.
Example 1:
Example 2:
Example 3:
This is a slightly improvised answer to ajsp answer using XML-RPC.
On the server-side when you convert the data, convert the numpy data to a string using the '.tostring()' method. This encodes the numpy ndarray as bytes string. On the client-side when you receive the data decode it using '.fromstring()' method. I wrote two simple functions for this. Hope this is helpful.
def ndarray2str(a):
# Convert the numpy array to string
a = a.tostring()
return a
On the receiver side, the data is received as a 'xmlrpc.client.Binary' object. You need to access the data using '.data'.
def str2ndarray(a):
# Specify your data type, mine is numpy float64 type, so I am specifying it as np.float64
a = np.fromstring(a.data, dtype=np.float64)
a = np.reshape(a, new_shape)
return a
Note: Only problem with this approach is that XML-RPC is very slow while sending large numpy arrays. It took me around 4 secs to send and receive a (10, 500, 500, 3) size numpy array for me.
I am using python 3.7.4.
To achieve it, you have to modify the background-color
of the element.
Ways to create a (semi-) transparent color:
The CSS color name transparent
creates a completely transparent color.
Usage:
.transparent{
background-color: transparent;
}
Using rgba
or hsla
color functions, that allow you to add the alpha channel (opacity) to the rgb
and hsl
functions. Their alpha values range from 0 - 1.
Usage:
.semi-transparent-yellow{
background-color: rgba(255, 255, 0, 0.5);
}
.transparent{
background-color: hsla(0, 0%, 0%, 0);
}
Besides the already mentioned solutions, you can also use the HEX format with alpha value (#RRGGBBAA
or #RGBA
notation).
That's pretty new (contained by CSS Color Module Level 4), but already implemented in larger browsers (sorry, no IE).
This differs from the other solutions, as this treats the alpha channel (opacity) as a hexadecimal value as well, making it range from 0 - 255 (FF
).
Usage:
.semi-transparent-yellow{
background-color: #FFFF0080;
}
.transparent{
background-color: #0000;
}
You can try them out as well:
transparent
:div {
position: absolute;
top: 50px;
left: 100px;
height: 100px;
width: 200px;
text-align: center;
line-height: 100px;
border: 1px dashed grey;
background-color: transparent;
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
Using `transparent`
</div>
_x000D_
rgba()
:div {
position: absolute;
top: 50px;
left: 100px;
height: 100px;
width: 200px;
text-align: center;
line-height: 100px;
border: 1px dashed grey;
background-color: rgba(0, 255, 0, 0.3);
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
Using `rgba()`
</div>
_x000D_
#RRGGBBAA
:div {
position: absolute;
top: 50px;
left: 100px;
height: 100px;
width: 200px;
text-align: center;
line-height: 100px;
border: 1px dashed grey;
background-color: #FF000060
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
Using `#RRGGBBAA`
</div>
_x000D_
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
this solution from this link helped me a lot. you can check it out.
The curl.php file with those line of instruction can work.
<?php
// Server key from Firebase Console define( 'API_ACCESS_KEY', 'AAAA----FE6F' );
$data = array("to" => "cNf2---6Vs9", "notification" => array( "title" => "Shareurcodes.com", "body" => "A Code Sharing Blog!","icon" => "icon.png", "click_action" => "http://shareurcodes.com"));
$data_string = json_encode($data);
echo "The Json Data : ".$data_string;
$headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' );
$ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close ($ch);
echo "<p> </p>";
echo "The Result : ".$result;
Remember you need to execute curl.php file using another browser ie not from the browser that is used to get the user token. You can see notification only if you are browsing another website.
I think it would be better to actually bind your listBoxes to a datasource, since it looks like you are adding the same elements to each listbox. A simple example would be something like this:
private List<String> _weight = new List<string>() { "kilogram", "pound" };
private List<String> _height = new List<string>() { "foot", "inch", "meter" };
public Window1()
{
InitializeComponent();
}
private void Weight_Click(object sender, RoutedEventArgs e)
{
listBox1.ItemsSource = _weight;
listBox2.ItemsSource = _weight;
}
private void Height_Click(object sender, RoutedEventArgs e)
{
listBox1.ItemsSource = _height;
listBox2.ItemsSource = _height;
}
In my case, locking and unlocking login-keychain from Keychain Access did the trick
#include <sstream>
and use the fully qualified name i.e. std::stringstream ss;
convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.
if(!number.split(".")[1]){
//do stuff
}
This way you can also know what the integer and decimal actually are. a more advanced example would be.
number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1];
if(!dece){
//do stuff
}
Why not take a collection, likely a Map such as a HashMap, and use it as the nucleus of your own combo box model class that implements the ComboBoxModel interface? Then you could access your combo box's items easily via their key Strings rather than ints.
For instance...
import java.util.HashMap;
import java.util.Map;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;
public class MyComboModel<K, V> implements ComboBoxModel {
private Map<K, V> nucleus = new HashMap<K, V>();
// ... any constructors that you want would go here
public void put(K key, V value) {
nucleus.put(key, value);
}
public V get(K key) {
return nucleus.get(key);
}
@Override
public void addListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}
// ... plus all the other methods required by the interface
}
Amazing there is no '$0' type structure in R! You can do it with a system() call to a bash script written in R:
write.table(c("readlink -e $0"), file="scriptpath.sh",col=F, row=F, quote=F)
thisscript <- system("sh scriptpath.sh", intern = TRUE)
Then just split out the scriptpath.sh name for other.R
splitstr <- rev(strsplit(thisscript, "\\/")[[1]])
otherscript <- paste0(paste(rev(splitstr[2:length(splitstr)]),collapse="/"),"/other.R")
You can attach the form to some object which is defined in a parent controller. Then you can reach your form even from a child scope.
Parent controller
$scope.forms = {};
Some template in a child scope
<form name="forms.form1">
</form>
Problem is that the form doesn't have to be defined in the moment when to code in the controller is executed. So you have to do something like this
$scope.$watch('forms.form1', function(form) {
if(form) {
// your code...
}
});
There is no such operator in Python, but it is trivial to implement on your own. In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one.
I just timed some functions out of curiosity. In these tests I'm removing non-alphanumeric characters from the string string.printable
(part of the built-in string
module). The use of compiled '[\W_]+'
and pattern.sub('', str)
was found to be fastest.
$ python -m timeit -s \
"import string" \
"''.join(ch for ch in string.printable if ch.isalnum())"
10000 loops, best of 3: 57.6 usec per loop
$ python -m timeit -s \
"import string" \
"filter(str.isalnum, string.printable)"
10000 loops, best of 3: 37.9 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]', '', string.printable)"
10000 loops, best of 3: 27.5 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]+', '', string.printable)"
100000 loops, best of 3: 15 usec per loop
$ python -m timeit -s \
"import re, string; pattern = re.compile('[\W_]+')" \
"pattern.sub('', string.printable)"
100000 loops, best of 3: 11.2 usec per loop
The problem is with percentage sizing. You are not defining the size of the parent div (the new one), so the browser can not report the size to the Google Maps API. Giving the wrapper div a specific size, or a percentage size if the size of its parent can be determined, will work.
See this explanation from Mike Williams' Google Maps API v2 tutorial:
If you try to use style="width:100%;height:100%" on your map div, you get a map div that has zero height. That's because the div tries to be a percentage of the size of the
<body>
, but by default the<body>
has an indeterminate height.There are ways to determine the height of the screen and use that number of pixels as the height of the map div, but a simple alternative is to change the
<body>
so that its height is 100% of the page. We can do this by applying style="height:100%" to both the<body>
and the<html>
. (We have to do it to both, otherwise the<body>
tries to be 100% of the height of the document, and the default for that is an indeterminate height.)
Add the 100% size to html and body in your css
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
Add it inline to any divs that don't have an id:
<body>
<div style="height:100%; width: 100%;">
<div id="map-canvas"></div>
</div>
</body>
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale);
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
it returns how many days between given two dates, where DateTime
is from joda library
Follow these steps:
Right click on designing part > Constraint Layout > Infer Constraints
encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Just uninstall the previous Apk and install the updated APK
Don't know if anyone is still looking here, but you can do this by going to Window menu > Preferences, then open the General list, choose keys. Scroll down the list of keys until you see "Shift Left". Click that. Below that you'll see some boxes, one of which lets you bind a key. It won't accept Shift-Tab, so I bound it to Shift-`. Apply-and-close and you're all set.
You must specify :
Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
return new FileStreamResult(stream, "application/pdf")
For the file to be opened directly in the browser instead of being downloaded
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
Here is a small example for Action and Func without using Linq:
class Program
{
static void Main(string[] args)
{
Action<int> myAction = new Action<int>(DoSomething);
myAction(123); // Prints out "123"
// can be also called as myAction.Invoke(123);
Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
Console.WriteLine(myFunc(5)); // Prints out "2.5"
}
static void DoSomething(int i)
{
Console.WriteLine(i);
}
static double CalculateSomething(int i)
{
return (double)i/2;
}
}
Like this?
In LINQ:
var sortedList = originalList.OrderBy(foo => !foo.AVC)
.ToList();
Or in-place:
originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));
As Jon Skeet says, the trick here is knowing that false
is considered to be 'smaller' than true.
If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo
to implement the IComparable<Foo>
and IComparable
interfaces.
Slight modification to @Mosche answer, for handling if there exist no filter element.
TS:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filterFromList'
})
export class FilterPipe implements PipeTransform {
public transform(value, keys: string, term: string) {
if (!term) {
return value
}
let res = (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));
return res.length ? res : [-1];
}
}
Now, in your HTML you can check via '-1' value, for no results.
HTML:
<div *ngFor="let item of list | filterFromList: 'attribute': inputVariableModel">
<mat-list-item *ngIf="item !== -1">
<h4 mat-line class="inline-block">
{{item}}
</h4>
</mat-list-item>
<mat-list-item *ngIf="item === -1">
No Matches
</mat-list-item>
</div>
HTML/JSP Markup:
<form:option
data-libelle="${compte.libelleCompte}"
data-raison="${compte.libelleSociale}" data-rib="${compte.numeroCompte}" <c:out value="${compte.libelleCompte} *MAD*"/>
</form:option>
JQUERY CODE: Event: change
var $this = $(this);
var $selectedOption = $this.find('option:selected');
var libelle = $selectedOption.data('libelle');
To have a element libelle.val() or libelle.text()
Here's what I do:
Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.
Possibly not cross browser but I managed get this: http://jsfiddle.net/QexkH/
basically it requires a fixed height header and footer. and it absolute positions the table.
table {
width: 50%;
height: 50%;
border-spacing: 0;
position:absolute;
}
td {
border: 1px solid black;
}
#content {
position:absolute;
width:100%;
left:0px;
top:20px;
bottom:20px;
overflow: hidden;
}
You can use The Oracle Enterprise Manager to monitor the active sessions, with the query that is being executed, its execution plan, locks, some statistics and even a progress bar for the longer tasks.
See: http://download.oracle.com/docs/cd/B10501_01/em.920/a96674/db_admin.htm#1013955
Go to Instance -> sessions and watch the SQL Tab of each session.
There are other ways. Enterprise manager just puts with pretty colors what is already available in specials views like those documented here: http://www.oracle.com/pls/db92/db92.catalog_views?remark=homepage
And, of course you can also use Explain PLAN FOR, TRACE tool and tons of other ways of instrumentalization. There are some reports in the enterprise manager for the top most expensive SQL Queries. You can also search recent queries kept on the cache.
Trace.WriteLine
should work provided you select the correct output (the dropdown labeled with "Show output from" found in the Output window).
Here is how to convert nested for loop to nested list comprehension:
Here is how nested list comprehension works:
l a b c d e f
? ? ? ? ? ? ?
In [1]: l = [ [ [ [ [ [ 1 ] ] ] ] ] ]
In [2]: for a in l:
...: for b in a:
...: for c in b:
...: for d in c:
...: for e in d:
...: for f in e:
...: print(float(f))
...:
1.0
In [3]: [float(f)
for a in l
...: for b in a
...: for c in b
...: for d in c
...: for e in d
...: for f in e]
Out[3]: [1.0]
For your case, it will be something like this.
In [4]: new_list = [float(y) for x in l for y in x]
VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.
There is currently no way to disable this behaviour.
For Python-3 try removing virtual environment files. And resetting it up.
rm -rf venv
virtualenv -p /usr/bin/python3 venv/
source venv/bin/activate
pip install -r requirements.txt
https://wiki.ubuntu.com/XenialXerus/ReleaseNotes#Python_3 edit fo
just replace 'myselect' with your id
to disable->
document.getElementById("mySelect").disabled = true;
to enable->
document.getElementById("mySelect").disabled = false;
I prefer using Symfony for this. Their libraries are pretty nice.
Use the The DomCrawler Component
Example:
$browser = new HttpBrowser(HttpClient::create());
$crawler = $browser->request('GET', 'example.com');
$class = $crawler->filter('.class')->first();
you can use the following command line:
java -jar -Dspring.profiles.active=[yourProfileName] target/[yourJar].jar
To do this efficiently using jQuery, you can chain it like so:
$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');
For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')
):
var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');
Also (since there is a js tag), if you wanted to do it in vanilla js:
For modern browsers (See this to see which browsers I'm calling modern)
(assuming one element with class theClassThatsThereNow
)
var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');
Or older browsers:
var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');
R-squared is a statistic that only applies to linear regression.
Essentially, it measures how much variation in your data can be explained by the linear regression.
So, you calculate the "Total Sum of Squares", which is the total squared deviation of each of your outcome variables from their mean. . .
where y_bar is the mean of the y's.
Then, you calculate the "regression sum of squares", which is how much your FITTED values differ from the mean
and find the ratio of those two.
Now, all you would have to do for a polynomial fit is plug in the y_hat's from that model, but it's not accurate to call that r-squared.
Here is a link I found that speaks to it a little.
For passing both a function, and any arguments to the function:
from typing import Callable
def looper(fn: Callable, n:int, *args, **kwargs):
"""
Call a function `n` times
Parameters
----------
fn: Callable
Function to be called.
n: int
Number of times to call `func`.
*args
Positional arguments to be passed to `func`.
**kwargs
Keyword arguments to be passed to `func`.
Example
-------
>>> def foo(a:Union[float, int], b:Union[float, int]):
... '''The function to pass'''
... print(a+b)
>>> looper(foo, 3, 2, b=4)
6
6
6
"""
for i in range(n):
fn(*args, **kwargs)
Depending on what you are doing, it could make sense to define a decorator
, or perhaps use functools.partial
.
For two digit minutes use:
new Date().toLocaleFormat("%M")
Swift version:
override func viewDidLoad() {
super.viewDidLoad()
// Assign your color to this property, for example here we assign the red color.
tableView.separatorColor = UIColor.redColor()
}
I had the same problem, and the way I ended up fixing it was like this:
ul, li{
list-style:none;
list-style-type:none;
}
Maybe it's a little extreme, but when I did that, it worked for me.
EDIT: I've added one more option for bootstrap sidebars.
There are actually three manners in which you can make a bootstrap 3 sidebar. I tried to keep the code as simple as possible.
Here you can see a demo of a simple fixed sidebar I've developed with the same height as the page
I've also developed a rather simple column sidebar that works in a two or three column page inside a container. It takes the length of the longest column. Here you can see a demo
If you google bootstrap dashboard, you can find multiple suitable dashboard, such as this one. However, most of them require a lot of coding. I've developed a dashboard that works without additional javascript (next to the bootstrap javascript). Here is a demo
For all three examples you off course have to include the jquery, bootstrap css, js and theme.css files.
If you want the sidebar to hide on pressing a button this is also possible with only a little javascript.Here is a demo
a bit of a cheat, but it works:
HTML:
<ol type="A" style="font-weight: bold;">
<li><span>Text</span></li>
<li><span>More text</span></li>
</ol>
CSS:
li span { font-weight: normal; }
I always add the following statement to a console application.(Create a code snippet for this if you wish)
Console.WriteLine("Press any key to quit!");
Console.ReadKey();
Doing this helps when you want to experiment different concepts through console application.
Ctr + F5 will make the Console stay but you cant debug! All the console applications that I have written in realworld is always non-interactive and triggered by a Scheduler such as TWS or CA Work station and did not require something like this.
Without using Regex
or substring()
function on String
which will be inefficient -
public static String removeZero(String str){
StringBuffer sb = new StringBuffer(str);
while (sb.length()>1 && sb.charAt(0) == '0')
sb.deleteCharAt(0);
return sb.toString(); // return in String
}
CodeIgniter way:
$this->load->helper('text');
$string = convert_accented_characters($string);
This function uses a companion config file application/config/foreign_chars.php
to define the to and from array for transliteration.
https://www.codeigniter.com/user_guide/helpers/text_helper.html#ascii_to_entities
try this:
function isUrl(s) {
if (!isUrl.rx_url) {
// taken from https://gist.github.com/dperini/729294
isUrl.rx_url=/^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
// valid prefixes
isUrl.prefixes=['http:\/\/', 'https:\/\/', 'ftp:\/\/', 'www.'];
// taken from https://w3techs.com/technologies/overview/top_level_domain/all
isUrl.domains=['com','ru','net','org','de','jp','uk','br','pl','in','it','fr','au','info','nl','ir','cn','es','cz','kr','ua','ca','eu','biz','za','gr','co','ro','se','tw','mx','vn','tr','ch','hu','at','be','dk','tv','me','ar','no','us','sk','xyz','fi','id','cl','by','nz','il','ie','pt','kz','io','my','lt','hk','cc','sg','edu','pk','su','bg','th','top','lv','hr','pe','club','rs','ae','az','si','ph','pro','ng','tk','ee','asia','mobi'];
}
if (!isUrl.rx_url.test(s)) return false;
for (let i=0; i<isUrl.prefixes.length; i++) if (s.startsWith(isUrl.prefixes[i])) return true;
for (let i=0; i<isUrl.domains.length; i++) if (s.endsWith('.'+isUrl.domains[i]) || s.includes('.'+isUrl.domains[i]+'\/') ||s.includes('.'+isUrl.domains[i]+'?')) return true;
return false;
}
function isEmail(s) {
if (!isEmail.rx_email) {
// taken from http://stackoverflow.com/a/16016476/460084
var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
var sQuotedPair = '\\x5c[\\x00-\\x7f]';
var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
var sDomain_ref = sAtom;
var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
var sWord = '(' + sAtom + '|' + sQuotedString + ')';
var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
isEmail.rx_email = new RegExp(sValidEmail);
}
return isEmail.rx_email.test(s);
}
will also recognize urls such as google.com
, http://www.google.bla
, http://google.bla
, www.google.bla
but not google.bla
If you want a copy of the HashMap you need to construct a new one with.
myobjectListB = new HashMap<Integer,myObject>(myobjectListA);
This will create a (shallow) copy of the map.
You can do it with an UPDATE statement setting the value with a REPLACE
UPDATE
Table
SET
Column = Replace(Column, 'find value', 'replacement value')
WHERE
xxx
You will want to be extremely careful when doing this! I highly recommend doing a backup first.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
which means that cacerts keystore isn't password protected
That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:
In order to verify its integrity, you must provide your keystore password.
Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.
gets()
dangerousThe first internet worm (the Morris Internet Worm) escaped about 30 years ago (1988-11-02), and it used gets()
and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.
You should forget you ever heard that gets()
existed.
The C11 standard ISO/IEC 9899:2011 eliminated gets()
as a standard function, which is A Good Thing™ (it was formally marked as 'obsolescent' and 'deprecated' in ISO/IEC 9899:1999/Cor.3:2007 — Technical Corrigendum 3 for C99, and then removed in C11). Sadly, it will remain in libraries for many years (meaning 'decades') for reasons of backwards compatibility. If it were up to me, the implementation of gets()
would become:
char *gets(char *buffer)
{
assert(buffer != 0);
abort();
return 0;
}
Given that your code will crash anyway, sooner or later, it is better to head the trouble off sooner rather than later. I'd be prepared to add an error message:
fputs("obsolete and dangerous function gets() called\n", stderr);
Modern versions of the Linux compilation system generates warnings if you link gets()
— and also for some other functions that also have security problems (mktemp()
, …).
gets()
As everyone else said, the canonical alternative to gets()
is fgets()
specifying stdin
as the file stream.
char buffer[BUFSIZ];
while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
...process line of data...
}
What no-one else yet mentioned is that gets()
does not include the newline but fgets()
does. So, you might need to use a wrapper around fgets()
that deletes the newline:
char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
if (fgets(buffer, buflen, fp) != 0)
{
size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n')
buffer[len-1] = '\0';
return buffer;
}
return 0;
}
Or, better:
char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
if (fgets(buffer, buflen, fp) != 0)
{
buffer[strcspn(buffer, "\n")] = '\0';
return buffer;
}
return 0;
}
Also, as caf points out in a comment and paxdiablo shows in his answer, with fgets()
you might have data left over on a line. My wrapper code leaves that data to be read next time; you can readily modify it to gobble the rest of the line of data if you prefer:
if (len > 0 && buffer[len-1] == '\n')
buffer[len-1] = '\0';
else
{
int ch;
while ((ch = getc(fp)) != EOF && ch != '\n')
;
}
The residual problem is how to report the three different result states — EOF or error, line read and not truncated, and partial line read but data was truncated.
This problem doesn't arise with gets()
because it doesn't know where your buffer ends and merrily tramples beyond the end, wreaking havoc on your beautifully tended memory layout, often messing up the return stack (a Stack Overflow) if the buffer is allocated on the stack, or trampling over the control information if the buffer is dynamically allocated, or copying data over other precious global (or module) variables if the buffer is statically allocated. None of these is a good idea — they epitomize the phrase 'undefined behaviour`.
There is also the TR 24731-1 (Technical Report from the C Standard Committee) which provides safer alternatives to a variety of functions, including gets()
:
§6.5.4.1 The
gets_s
functionSynopsis
#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h> char *gets_s(char *s, rsize_t n);
Runtime-constraints
s
shall not be a null pointer.n
shall neither be equal to zero nor be greater than RSIZE_MAX. A new-line character, end-of-file, or read error shall occur within readingn-1
characters fromstdin
.25)3 If there is a runtime-constraint violation,
s[0]
is set to the null character, and characters are read and discarded fromstdin
until a new-line character is read, or end-of-file or a read error occurs.Description
4 The
gets_s
function reads at most one less than the number of characters specified byn
from the stream pointed to bystdin
, into the array pointed to bys
. No additional characters are read after a new-line character (which is discarded) or after end-of-file. The discarded new-line character does not count towards number of characters read. A null character is written immediately after the last character read into the array.5 If end-of-file is encountered and no characters have been read into the array, or if a read error occurs during the operation, then
s[0]
is set to the null character, and the other elements ofs
take unspecified values.Recommended practice
6 The
fgets
function allows properly-written programs to safely process input lines too long to store in the result array. In general this requires that callers offgets
pay attention to the presence or absence of a new-line character in the result array. Consider usingfgets
(along with any needed processing based on new-line characters) instead ofgets_s
.25) The
gets_s
function, unlikegets
, makes it a runtime-constraint violation for a line of input to overflow the buffer to store it. Unlikefgets
,gets_s
maintains a one-to-one relationship between input lines and successful calls togets_s
. Programs that usegets
expect such a relationship.
The Microsoft Visual Studio compilers implement an approximation to the TR 24731-1 standard, but there are differences between the signatures implemented by Microsoft and those in the TR.
The C11 standard, ISO/IEC 9899-2011, includes TR24731 in Annex K as an optional part of the library. Unfortunately, it is seldom implemented on Unix-like systems.
getline()
— POSIXPOSIX 2008 also provides a safe alternative to gets()
called getline()
. It allocates space for the line dynamically, so you end up needing to free it. It removes the limitation on line length, therefore. It also returns the length of the data that was read, or -1
(and not EOF
!), which means that null bytes in the input can be handled reliably. There is also a 'choose your own single-character delimiter' variation called getdelim()
; this can be useful if you are dealing with the output from find -print0
where the ends of the file names are marked with an ASCII NUL '\0'
character, for example.
one time i found this script, this copy folder and files and keep the same structure of the source in the destination, you can make some tries with this.
# Find the source files
$sourceDir="X:\sourceFolder"
# Set the target file
$targetDir="Y:\Destfolder\"
Get-ChildItem $sourceDir -Include *.* -Recurse | foreach {
# Remove the original root folder
$split = $_.Fullname -split '\\'
$DestFile = $split[1..($split.Length - 1)] -join '\'
# Build the new destination file path
$DestFile = $targetDir+$DestFile
# Move-Item won't create the folder structure so we have to
# create a blank file and then overwrite it
$null = New-Item -Path $DestFile -Type File -Force
Move-Item -Path $_.FullName -Destination $DestFile -Force
}
Make sure you have following configuration in your pom.xml
file.
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
Set Current State first ...this.state
Its because when you are going to assign a new state it may be undefined. so it will be fixed by setting state extracting current state also
this.setState({...this.state, field})
If there is an object in your state, you should set state as follows, suppose you have to set username inside the user object.
this.setState({user:{...this.state.user, ['username']: username}})
The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.
This is working for me.
SizedBox(
width: double.maxFinite,
child: RaisedButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
child: new Text("Button 2"),
color: Colors.lightBlueAccent,
onPressed: () => debugPrint("Button 2"),
),
),
In iOS 13 you can use .darkContent
UIStatusBarStyle
property to display dark status bar
You can create a batch by PreparedStatement#addBatch()
and execute it by PreparedStatement#executeBatch()
.
Here's a kickoff example:
public void save(List<Entity> entities) throws SQLException {
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
) {
int i = 0;
for (Entity entity : entities) {
statement.setString(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.
See also:
If someone still having this problem.Try to use instead of ovverriding
public void OnActionExecuting(ActionExecutingContext context)
{
try
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
if (!HttpContext.Current.Response.IsRequestBeingRedirected)
{
context.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "controller", "Login" }, { "action", "Index" } });
}
}
}
catch (Exception ex)
{
new RouteValueDictionary { { "controller", "Login" }, { "action", "Index" } });
}
}
First you have to ensure that there is a SMTP server listening on port 25.
To look whether you have the service, you can try using TELNET client, such as:
C:\> telnet localhost 25
(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.
$ telnet localhost 25
If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.
If you don't have the service, you can use these:
If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.
For your question :
SELECT id,
IF(qty_1 <= '23', price,
IF(('23' > qty_1 && qty_2 <= '23'), price_2,
IF(('23' > qty_2 && qty_3 <= '23'), price_3,
IF(('23' > qty_2 && qty_3<='23'), price_3,
IF('23' > qty_3, price_4, 1))))) as total
FROM product;
You can use the if - else
control structure or the IF
function in MySQL.
Reference:
http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/
a combination of answers gave me a very fast running time. using the shift method to create new column of next row values, then using the row_iterator function as @alisdt did, but here i changed it from iterrows to itertuples which is 100 times faster.
my script is for iterating dataframe of duplications in different length and add one second for each duplication so they all be unique.
# create new column with shifted values from the departure time column
df['next_column_value'] = df['column_value'].shift(1)
# create row iterator that can 'save' the next row without running for loop
row_iterator = df.itertuples()
# jump to the next row using the row iterator
last = next(row_iterator)
# because pandas does not support items alteration i need to save it as an object
t = last[your_column_num]
# run and update the time duplications with one more second each
for row in row_iterator:
if row.column_value == row.next_column_value:
t = t + add_sec
df_result.at[row.Index, 'column_name'] = t
else:
# here i resetting the 'last' and 't' values
last = row
t = last[your_column_num]
Hope it will help.
The entire new
expression is an object reference, so methods can be invoked on it:
public class A {
public static void main(String[] arg)
{
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
}
}
In windows you should use %WORKSPACE%
.
Try my simple trick:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("classRegister:")) {
Intent MnRegister = new Intent(getApplicationContext(), register.class); startActivity(MnRegister);
}
view.loadUrl(url);
return true;
}
and my html link:
<a href="classRegister:true">Go to register.java</a>
or you can make < a href="classRegister:true" > <- "true" value for class filename
however this script work for mailto link :)
if (url.startsWith("mailto:")) {
String[] blah_email = url.split(":");
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{blah_email[1]});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, what_ever_you_want_the_subject_to_be)");
Log.v("NOTICE", "Sending Email to: " + blah_email[1] + " with subject: " + what_ever_you_want_the_subject_to_be);
startActivity(emailIntent);
}
In your case IF you want to go with foreach loop than
$sum = 0;
foreach($group as $key => $value) {
$sum += $value;
}
echo $sum;
But if you want to go with direct sum of array than look on below for your solution :
$total = array_sum($group);
for only sum of array looping is time wasting.
http://php.net/manual/en/function.array-sum.php
array_sum — Calculate the sum of values in an array
<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>
The above example will output:
sum(a) = 20
sum(b) = 6.9
import os
source = ['test_sound.flac','ts.mp3']
for files in source:
fileName,fileExtension = os.path.splitext(files)
print fileExtension # Print File Extensions
print fileName # It print file name
This works with Firefox Quantum 60+ and Chrome v72 (2019)
//set a header to instruct the browser to call the page every 30 sec
header("Refresh: 30;");
It does not seem to be NECESSARY to pass the page url as well as the refresh period in order to (re)call the same page. I haven't tried this with Safari/Opera or IE/Edge.
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
This has been answered and accepted, but if someone is still wondering why are things a bit messed up today, you'll have to read this:
http://webaim.org/blog/user-agent-string-history/
It gives a good idea of how gecko, webkit and other major rendering engines evolved and what led to the current state of messed up user-agent strings.
Quoting the last paragraph for TL;DR purposes:
And then Google built Chrome, and Chrome used Webkit, and it was like Safari, and wanted pages built for Safari, and so pretended to be Safari. And thus Chrome used WebKit, and pretended to be Safari, and WebKit pretended to be KHTML, and KHTML pretended to be Gecko, and all browsers pretended to be Mozilla, and Chrome called itself
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13
, and the user agent string was a complete mess, and near useless, and everyone pretended to be everyone else, and confusion abounded.
Bear in mind that using WaitForSingleObject
can get you into trouble in this scenario. The following is snipped from a tip on my website:
The problem arises because your application has a window but isn't pumping messages. If the spawned application invokes SendMessage with one of the broadcast targets (HWND_BROADCAST or HWND_TOPMOST), then the SendMessage won't return to the new application until all applications have handled the message - but your app can't handle the message because it isn't pumping messages.... so the new app locks up, so your wait never succeeds.... DEADLOCK.
If you have absolute control over the spawned application, then there are measures you can take, such as using SendMessageTimeout rather than SendMessage (e.g. for DDE initiations, if anybody is still using that). But there are situations which cause implicit SendMessage broadcasts over which you have no control, such as using the SetSysColors API for instance.
The only safe ways round this are:
MsgWaitForMultipleObjects
API.In Order to implement Line Break in SSRS, there are 2 ways
<br/>
tag to introduce line break within the expression ="first line of text. Param1 value: " & Parameters!Param1.Value & "<br/>" & Parameters!Param1.Value
="first line of text. Param1 value: " & Parameters!Param1.Value & Environment.NewLine()
& Parameters!Param1.Value
Note:- Always remember to leave a space after every "&" (ampersand) in order to evaluate the expression properly
IF you want to derive usg Boolean true False need to add "[]" around value
<form [formGroup]="form">
<input type="radio" [value]=true formControlName="gender" >Male
<input type="radio" [value]=false formControlName="gender">Female
</form>
instanceof
will not work for primitives eg "foo" instanceof String
will return false
whereas typeof "foo" == "string"
will return true
.
On the other hand typeof
will probably not do what you want when it comes to custom objects (or classes, whatever you want to call them). For example:
function Dog() {}
var obj = new Dog;
typeof obj == 'Dog' // false, typeof obj is actually "object"
obj instanceof Dog // true, what we want in this case
It just so happens that functions are both 'function' primitives and instances of 'Function', which is a bit of an oddity given that it doesn't work like that for other primitive types eg.
(typeof function(){} == 'function') == (function(){} instanceof Function)
but
(typeof 'foo' == 'string') != ('foo' instanceof String)
I think this working CodePen example that I created will show you exactly how to do what you want.
The template:
<section ng-app="app" ng-controller="MainCtrl">
<span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
<table class="table table-bordered">
<thead>
<tr>
<th>
<a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">
<td>{{emp.firstName}}</td>
<td>{{emp.lastName}}</td>
<td>{{emp.age}}</td>
</tr>
</tbody>
</table>
</section>
The JavaScript code:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.orderByField = 'firstName';
$scope.reverseSort = false;
$scope.data = {
employees: [{
firstName: 'John',
lastName: 'Doe',
age: 30
},{
firstName: 'Frank',
lastName: 'Burns',
age: 54
},{
firstName: 'Sue',
lastName: 'Banter',
age: 21
}]
};
});
I use Universal Image loader library to download and round the corners of image, and it worked for me.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(thisContext)
// You can pass your own memory cache implementation
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.build();
DisplayImageOptions options = new DisplayImageOptions.Builder()
.displayer(new RoundedBitmapDisplayer(10)) //rounded corner bitmap
.cacheInMemory(true)
.cacheOnDisc(true)
.build();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
imageLoader.displayImage(image_url,image_view, options );
The browser might not be able to detect that your form is a login form. According to some of the discussion in this previous question, a browser looks for form fields that look like <input type="password">
. Is your password form field implemented similar to that?
Edit: To answer your questions below, I think Firefox detects passwords by form.elements[n].type == "password"
(iterating through all form elements) and then detects the username field by searching backwards through form elements for the text field immediately before the password field (more info here). From what I can tell, your login form needs to be part of a <form>
or Firefox won't detect it.
Since version 5, Qt uses a platform abstraction system (QPA) to abstract from the underlying platform.
The implementation for each platform is provided by plugins. For X11 it is the XCB plugin. See Qt for X11 requirements for more information about the dependencies.
.third-level-menu_x000D_
{_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: -150px;_x000D_
width: 150px;_x000D_
list-style: none;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.third-level-menu > li_x000D_
{_x000D_
height: 30px;_x000D_
background: #999999;_x000D_
}_x000D_
.third-level-menu > li:hover { background: #CCCCCC; }_x000D_
_x000D_
.second-level-menu_x000D_
{_x000D_
position: absolute;_x000D_
top: 30px;_x000D_
left: 0;_x000D_
width: 150px;_x000D_
list-style: none;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.second-level-menu > li_x000D_
{_x000D_
position: relative;_x000D_
height: 30px;_x000D_
background: #999999;_x000D_
}_x000D_
.second-level-menu > li:hover { background: #CCCCCC; }_x000D_
_x000D_
.top-level-menu_x000D_
{_x000D_
list-style: none;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.top-level-menu > li_x000D_
{_x000D_
position: relative;_x000D_
float: left;_x000D_
height: 30px;_x000D_
width: 150px;_x000D_
background: #999999;_x000D_
}_x000D_
.top-level-menu > li:hover { background: #CCCCCC; }_x000D_
_x000D_
.top-level-menu li:hover > ul_x000D_
{_x000D_
/* On hover, display the next level's menu */_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
_x000D_
/* Menu Link Styles */_x000D_
_x000D_
.top-level-menu a /* Apply to all links inside the multi-level menu */_x000D_
{_x000D_
font: bold 14px Arial, Helvetica, sans-serif;_x000D_
color: #FFFFFF;_x000D_
text-decoration: none;_x000D_
padding: 0 0 0 10px;_x000D_
_x000D_
/* Make the link cover the entire list item-container */_x000D_
display: block;_x000D_
line-height: 30px;_x000D_
}_x000D_
.top-level-menu a:hover { color: #000000; }
_x000D_
<ul class="top-level-menu">_x000D_
<li><a href="#">About</a></li>_x000D_
<li><a href="#">Services</a></li>_x000D_
<li>_x000D_
<a href="#">Offices</a>_x000D_
<ul class="second-level-menu">_x000D_
<li><a href="#">Chicago</a></li>_x000D_
<li><a href="#">Los Angeles</a></li>_x000D_
<li>_x000D_
<a href="#">New York</a>_x000D_
<ul class="third-level-menu">_x000D_
<li><a href="#">Information</a></li>_x000D_
<li><a href="#">Book a Meeting</a></li>_x000D_
<li><a href="#">Testimonials</a></li>_x000D_
<li><a href="#">Jobs</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Seattle</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Contact</a></li>_x000D_
</ul>
_x000D_
I have also put together a live demo that's available to play with HERE
Luckily, Python has this built-in :)
import re
re.split('; |, ',str)
Update:
Following your comment:
>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
I have a solution for this but not sure on the reason why this would be different from one environment to the other - although one big difference between the two environments is WSS svc pack 1 was installed on the environment where the error was occurring.
To fix this issue I got a good clue from this link - http://silverlight.net/forums/t/22787.aspx ie to "please check the Xml Schema of your service" and "the sequence in the schema is sorted alphabetically"
Looking at the wsdl generated I noticed that for the serialized class that was causing the error, the properties of this class were not visible in the wsdl.
The Definition of the class had private setters for most of the properties, but not for CustomFields property ie..
[Serializable]
public class FileMetaDataDto
{
.
. a constructor... etc and several other properties edited for brevity
.
public int Id { get; private set; }
public string Version { get; private set; }
public List<MetaDataValueDto> CustomFields { get; set; }
}
On removing private from the setter and redeploying the service then looking at the wsdl again, these properties were now visible, and the original error was fixed.
So the wsdl before update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
</s:sequence>
</s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
</s:sequence>
</s:complexType>
The wsdl after update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
</s:sequence>
</s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="Id" type="s:int" />
<s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Title" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="ContentType" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Icon" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="ModifiedBy" type="s:string" />
<s:element minOccurs="1" maxOccurs="1" name="ModifiedDateTime" type="s:dateTime" />
<s:element minOccurs="1" maxOccurs="1" name="FileSizeBytes" type="s:int" />
<s:element minOccurs="0" maxOccurs="1" name="Url" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="RelativeFolderPath" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="DisplayVersion" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Version" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
<s:element minOccurs="0" maxOccurs="1" name="CheckoutBy" type="s:string" />
</s:sequence>
</s:complexType>
Something like this will do it:
Rows("12:12").Select
Selection.Delete
So in your code it would look like something like this:
Rows(CStr(rand) & ":" & CStr(rand)).Select
Selection.Delete
custom-border
class is what worked for me.Mods:
border
instead of backaground-color
since background-color
is not consistent.height
& top
of the properties of :after
in such a way that the total comes up to 100%
where bottom
's value is implicit.ul {_x000D_
list-style-type: none;_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
}_x000D_
_x000D_
li {_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
.custom-border {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.custom-border:after {_x000D_
content: " ";_x000D_
position: absolute;_x000D_
border-left: 1px #6c757d solid;_x000D_
top: 35%;_x000D_
right: 0;_x000D_
height: 30%;_x000D_
margin-top: auto;_x000D_
margin-bottom: auto;_x000D_
}
_x000D_
<ul>_x000D_
<li class="custom-border">_x000D_
Hello_x000D_
</li>_x000D_
<li class="custom-border">_x000D_
World_x000D_
</li>_x000D_
<li class="custom-border">_x000D_
Foo_x000D_
</li>_x000D_
<li class="custom-border">Bar</li>_x000D_
<li class="custom-border">Baz</li>_x000D_
</ul>
_x000D_
Good Luck...
This will work from anywhere, inside Form(), Form_Load(), or any event handler. I posted before, but I don't see it now?!?
public void exit(int exitCode)
{
if (System.Windows.Forms.Application.MessageLoop)
{
// Use this since we are in a running Form
System.Windows.Forms.Application.Exit();
System.Environment.Exit(exitCode);
}
else
{
// Form ended or never .Run
System.Environment.Exit(exitCode);
}
} //* end exit()
Double importing jquery can cause Error
<script src="static/public/js/jquery/jquery.min.js"></script>
OR
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="" crossorigin="anonymous"></script>
If you've recently updated, a reboot might solve this problem.
In it's simplest form, you are saying "for this cell, if it's value is X, then apply format foo". However, if you use the "formula" method, you can select the whole row, enter the formula and associated format, then use copy and paste (formats only) for the rest of the table.
You're limited to only 3 rules in Excel 2003 or older so you might want to define a pattern for the colours rather than using raw values. Something like this should work though:
Here is an elegant method using quaternions that are blazingly fast; I can calculate 10 million rotations per second with appropriately vectorised numpy arrays. It relies on the quaternion extension to numpy found here.
Quaternion Theory:
A quaternion is a number with one real and 3 imaginary dimensions usually written as q = w + xi + yj + zk
where 'i', 'j', 'k' are imaginary dimensions. Just as a unit complex number 'c' can represent all 2d rotations by c=exp(i * theta)
, a unit quaternion 'q' can represent all 3d rotations by q=exp(p)
, where 'p' is a pure imaginary quaternion set by your axis and angle.
We start by converting your axis and angle to a quaternion whose imaginary dimensions are given by your axis of rotation, and whose magnitude is given by half the angle of rotation in radians. The 4 element vectors (w, x, y, z)
are constructed as follows:
import numpy as np
import quaternion as quat
v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian
vector = np.array([0.] + v)
rot_axis = np.array([0.] + axis)
axis_angle = (theta*0.5) * rot_axis/np.linalg.norm(rot_axis)
First, a numpy array of 4 elements is constructed with the real component w=0 for both the vector to be rotated vector
and the rotation axis rot_axis
. The axis angle representation is then constructed by normalizing then multiplying by half the desired angle theta
. See here for why half the angle is required.
Now create the quaternions v
and qlog
using the library, and get the unit rotation quaternion q
by taking the exponential.
vec = quat.quaternion(*v)
qlog = quat.quaternion(*axis_angle)
q = np.exp(qlog)
Finally, the rotation of the vector is calculated by the following operation.
v_prime = q * vec * np.conjugate(q)
print(v_prime) # quaternion(0.0, 2.7491163, 4.7718093, 1.9162971)
Now just discard the real element and you have your rotated vector!
v_prime_vec = v_prime.imag # [2.74911638 4.77180932 1.91629719] as a numpy array
Note that this method is particularly efficient if you have to rotate a vector through many sequential rotations, as the quaternion product can just be calculated as q = q1 * q2 * q3 * q4 * ... * qn and then the vector is only rotated by 'q' at the very end using v' = q * v * conj(q).
This method gives you a seamless transformation between axis angle <---> 3d rotation operator simply by exp
and log
functions (yes log(q)
just returns the axis-angle representation!). For further clarification of how quaternion multiplication etc. work, see here
Another simple way using JOIN
and INSTR
Sub Sample()
Dim Mainfram(4) As String, strg As String
Dim cel As Range
Dim Delim As String
Delim = "#"
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
strg = Join(Mainfram, Delim)
strg = Delim & strg
For Each cel In Selection
If InStr(1, strg, Delim & cel.Value & Delim, vbTextCompare) Then _
Rows(cel.Row).Style = "Accent1"
Next cel
End Sub
One approach is to combine the search strings into a regex pattern as in this answer.
Make sure you:
1) Have a registered provisioning profile for your device.
2) Device must be added to the Development profile and updated.
If you still run into issues check your target's build settings.
Make sure you:
1) CODE_SIGNING_REQUIRED
in User-Defined
is set to YES
.
2) Check Signing
options are correct. If the problem persists switch to Manual settings instead of automatically.
I'm trying to implement this but it's not working right. The page is posting back, but my code isn't getting executed. When i debug the page, the RaisePostBackEvent never gets fired. One thing i did differently is I'm doing this in a user control instead of an aspx page.
If anyone else is like Merk, and having trouble over coming this, I have a solution:
When you have a user control, it seems you must also create the PostBackEventHandler in the parent page. And then you can invoke the user control's PostBackEventHandler by calling it directly. See below:
public void RaisePostBackEvent(string _arg)
{
UserControlID.RaisePostBackEvent(_arg);
}
Where UserControlID is the ID you gave the user control on the parent page when you nested it in the mark up.
Note: You can also simply just call methods belonging to that user control directly (in which case, you would only need the RaisePostBackEvent handler in the parent page):
public void RaisePostBackEvent(string _arg)
{
UserControlID.method1();
UserControlID.method2();
}
If you just want the unix timestamp, create an extension:
extension Date {
func currentTimeMillis() -> Int64 {
return Int64(self.timeIntervalSince1970 * 1000)
}
}
Then you can use it just like in other programming languages:
let timestamp = Date().currentTimeMillis()
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
Using moment.js example:
var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)
You actually can use an inet function. Observe.
main.c:
#include <arpa/inet.h>
main() {
uint32_t ip = 2110443574;
struct in_addr ip_addr;
ip_addr.s_addr = ip;
printf("The IP address is %s\n", inet_ntoa(ip_addr));
}
The results of gcc main.c -ansi; ./a.out
is
The IP address is 54.208.202.125
Note that a commenter said this does not work on Windows.
System.setProperty("gate.home", "/some/directory");
After that you can retrieve its value later by calling
String value = System.getProperty("gate.home");
The following line of code will swap the first two characters in str
:
return str.charAt(1) + str.charAt(0) + str.substring(2);
If you have to iterate over the first len(a)
items of an object b
(that is larger than a
), you should probably use range(len(a))
:
for i in range(len(a)):
do_something_with(b[i])
I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows
data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
print('{} {}'.format(item["gravatar_id"], item["position"]))
note that you need to handle the index in the dataset that is also returned by the function.