No, IIRC there is no getopt() on Windows.
Boost, however, has the program_options library... which works okay. It will seem like overkill at first, but it isn't terrible, especially considering it can handle setting program options in configuration files and environment variables in addition to command line options.
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
execl("/home/vlc",
"/home/vlc", "/home/my movies/the movie i want to see.mkv",
(char*) NULL);
You need to specify all arguments, included argv[0]
which isn't taken from the executable.
Also make sure the final NULL
gets cast to char*
.
Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html
In your code you are assigning a native method to a property of custom object.
When you call support.animationFrame(function () {})
, it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window
.
So the correct usage here is support.animationFrame.call(window, function() {});
.
The same happens with alert too:
var myObj = {
myAlert : alert //copying native alert to an object
};
myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window
Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame: _raf ? _raf.bind(window) : null
};
For this, you need to declare the variable as global. However, a global variable is also accessible from outside the module by using module_name.var_name
. Add this as the first line of your module:
global __DBNAME__
You can add jar doing:
For gradle just put following code in build.gradle
:
dependencies {
...
compile fileTree(dir: 'lib', includes: ['suitetalk-*0.jar'])
...
}
and for maven just follow steps:
For Intellij: File->project structure->modules->dependency tab-> click on + sign-> jar and dependency->select jars you want to import-> ok-> apply(if visible)->ok
Remember that if you got any java.lang.NoClassDefFoundError: Could not initialize class
exception at runtime this means that dependencies in jar not installed for that you have to add all dependecies in parent project.
Another request for sample data.
As has been mentioned I would work backwards from the zip.
Once you have a zip I would query a zip database, store the results, and remove them & the zip from the string.
That will leave you with the address mess. MOST (All?) addresses will start with a number so find the first occurrence of a number in the remaining string and grab everything from it to the (new) end of the string. That will be your address. Anything to the left of that number is likely an addressee.
You should now have the City, State, & Zip stored in a table and possibly two strings, addressee and address. For the address, check for the existence of "Suite" or "Apt." etc. and split that into two values (address lines 1 & 2).
For the addressee I would punt and grab the last word of that string as the last name and put the rest into the first name field. If you don't want to do that, you'll need to check for salutation (Mr., Ms., Dr., etc.) at the start and make some assumptions based on the number of spaces as to how the name is made up.
I don't think there's any way you can parse with 100% accuracy.
If you just want to remove one of a group of variables, then you can create a list and keep just the variable you need. The rm function can be used to remove all the variables apart from "data". Here is the script:
0->data
1->data_1
2->data_2
3->data_3
#check variables in workspace
ls()
rm(list=setdiff(ls(), "data"))
#check remaining variables in workspace after deletion
ls()
#note: if you just use rm(list) then R will attempt to remove the "list" variable.
list=setdiff(ls(), "data")
rm(list)
ls()
The problem is that your class contains a managed RAW pointer but does not implement the rule of three (five in C++11). As a result you are getting (expectedly) a double delete because of copying.
If you are learning you should learn how to implement the rule of three (five). But that is not the correct solution to this problem. You should be using standard container objects rather than try to manage your own internal container. The exact container will depend on what you are trying to do but std::vector is a good default (and you can change afterwords if it is not opimal).
#include <queue>
#include <vector>
class Test{
std::vector<int> myArray;
public:
Test(): myArray(10){
}
};
int main(){
queue<Test> q
Test t;
q.push(t);
}
The reason you should use a standard container is the separation of concerns
. Your class should be concerned with either business logic or resource management (not both). Assuming Test
is some class you are using to maintain some state about your program then it is business logic and it should not be doing resource management. If on the other hand Test
is supposed to manage an array then you probably need to learn more about what is available inside the standard library.
The easiest way is to create a DtaTable as of now
DataTable table = new DataTable
{
Columns = {
"Name", // typeof(string) is implied
{"Marks", typeof(int)}
},
TableName = "MarksTable" //optional
};
table.Rows.Add("ravi", 500);
If you want a smaller table (e.g. if your table extends beyond the area that can be displayed) you can simply change:
\usepackage[paper=a4paper]{geometry}
to \usepackage[paper=a3paper]{geometry}
.
Note that this only helps if you don't plan on printing your table out, as it will appear way too small, then.
find
supports -delete
operation, so:
find /base/dir/* -ctime +10 -delete;
I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.
The most voted solution here is missing -maxdepth 0
so it will call rm -rf
for every subdirectory, after deleting it. That doesn't make sense, so I suggest:
find /base/dir/* -maxdepth 0 -type d -ctime +10 -exec rm -rf {} \;
The -delete
solution above doesn't use -maxdepth 0
because find
would complain the dir is not empty. Instead, it implies -depth
and deletes from the bottom up.
You could try turning off the main Activity's ability to save its state (thus making it forget what control had text and what had focus). You will need to have some other way of remembering what your EditText's have and repopulating them onResume(). Launch your sub-Activities with startActivityForResult() and create an onActivityResult() handler in your main Activity that will update the EditText's correctly. This way you can set the proper button you want focused onResume() at the same time you repopulate the EditText's by using a myButton.post(new Runnable(){ run() { myButton.requestFocus(); } });
The View.post() method is useful for setting focus initially because that runnable will be executed after the window is created and things settle down, allowing the focus mechanism to function properly by that time. Trying to set focus during onCreate/Start/Resume() usually has issues, I've found.
Please note this is pseudo-code and non-tested, but it's a possible direction you could try.
If searching for a value, you will have to loop through all the data. But to minimize code involved, you can use LINQ
.
Given Dictionary defined as following:
Dictionary<Int32, String> dict;
You can use following code :
// Search for all keys with given value
Int32[] keys = dict.Where(kvp => kvp.Value.Equals("SomeValue")).Select(kvp => kvp.Key).ToArray();
// Search for first key with given value
Int32 key = dict.First(kvp => kvp.Value.Equals("SomeValue")).Key;
Similarly to Jakob's answer, you can use HTML tags. Just a note that the color
attribute of font
(<font color=...>
) is deprecated in HTML5. The following syntax would be HTML5-compliant:
This <span style="color:red">word</span> is not black.
Same caution that Jakob made probably still applies:
Be aware that this will not survive a conversion of the notebook to latex.
They are the same. Boolean helps simplify conversion back and forth between C# and VB.Net. Most C# programmers tend to prefer 'bool', but if you are in a shop where there's a lot of both VB.Net and C# then you may prefer Boolean because it works in both places.
$('input, select').attr('disabled', 'disabled');
Here is representation of screen eclipse to make hierarachical.
Both these work for me. Maybe post a complete example?
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PaneBackgroundTest extends Application {
@Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
VBox vbox = new VBox();
root.setCenter(vbox);
ToggleButton toggle = new ToggleButton("Toggle color");
HBox controls = new HBox(5, toggle);
controls.setAlignment(Pos.CENTER);
root.setBottom(controls);
// vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
// .then("-fx-background-color: cornflowerblue;")
// .otherwise("-fx-background-color: white;"));
vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
.then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
.otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Little bit more complex data, mix of @Laran's and @Nisal Gunawardana's answers
[
{
"foodItemsList":[
{
"id":7,
"price":240,
"quantity":1
},
{
"id":8,
"quantity":1
}],
"price":340,
"customer_id":1
},
{
"foodItemsList":[
{
"id":7,
"quantity":1
},
{
"id":8,
"quantity":1
}],
"customer_id":2
}
]
The validation rule will be
return [
'*.customer_id' => 'required|numeric|exists:customers,id',
'*.foodItemsList.*.id' => 'required|exists:food_items,id',
'*.foodItemsList.*.quantity' => 'required|numeric',
];
It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:
Array.prototype.some(fn)
offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it's not hard to apply some trickery, such as the solution offered by Bergi's answer.
Array.prototype.filter(fn)[0]
makes for a great one-liner but is the least efficient, because you throw away N - 1
elements just to get what you need.
Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.
Both solutions above don't support offset searching either, so I've decided to write this:
(function(ns) {
ns.search = function(array, callback, offset) {
var size = array.length;
offset = offset || 0;
if (offset >= size || offset <= -size) {
return -1;
} else if (offset < 0) {
offset = size - offset;
}
while (offset < size) {
if (callback(array[offset], offset, array)) {
return offset;
}
++offset;
}
return -1;
};
}(this));
search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3
You can include the branch to track when setting up remotes, to keep things working as you might expect:
git remote add --track master origin [email protected]:group/project.git # git
git remote add --track master origin [email protected]:group/project.git # git w/IP
git remote add --track master origin http://github.com/group/project.git # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/ # local
git remote add --track master origin G:/group/project/ # local, Win
This keeps you from having to manually edit your git config or specify branch tracking manually.
We do a lot of joins and composite primary keys have just become a performance hog. A simple int or long takes care of many problems even though you are introducing a second candidate key, but it's a lot easier and more understandable to join on one field versus three.
SELECT GETDATE() + (hours / 24.00000000000000000)
Adding to GETDATE() defaults to additional days, but it will also convert down to hours/seconds/milliseconds using decimal.
Updated for Swift :
Used below code for Email, Name, Mobile and Password Validation;
// Name validation
func isValidName(_ nameString: String) -> Bool {
var returnValue = true
let mobileRegEx = "[A-Za-z]{2}" // "^[A-Z0-9a-z.-_]{5}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = nameString as NSString
let results = regex.matches(in: nameString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// password validation
func isValidPassword(_ PasswordString: String) -> Bool {
var returnValue = true
let mobileRegEx = "[A-Za-z0-9.-_@#$!%&*]{5,15}$" // "^[A-Z0-9a-z.-_]{5}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = PasswordString as NSString
let results = regex.matches(in: PasswordString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// email validaton
func isValidEmailAddress(_ emailAddressString: String) -> Bool {
var returnValue = true
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"
do {
let regex = try NSRegularExpression(pattern: emailRegEx)
let nsString = emailAddressString as NSString
let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// mobile no. validation
func isValidPhoneNumber(_ phoneNumberString: String) -> Bool {
var returnValue = true
// let mobileRegEx = "^[789][0-9]{9,11}$"
let mobileRegEx = "^[0-9]{10}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = phoneNumberString as NSString
let results = regex.matches(in: phoneNumberString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
//How to use?
let isFullNameValid = isValidName("ray")
if isFullNameValid{
print("Valid name...")
}else{
print("Invalid name...")
}
Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:
foo[ c( rep(FALSE, 5), TRUE ) ]
AngularJS — Superheroic JavaScript MVW Framework
You can use this in a header file.
// setup session enviroment
ini_set('session.cookie_httponly',1);
ini_set('session.use_only_cookies',1);
This way all future session cookies will use httponly.
No, such method does not exist, but is trivial to write:
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
You can use a map if that lookup is an important part of your code, but maps have cost too.
Go to any page you want to see it in browser right click--> view in browser. this way working with me.
I simply do this:
UIWebView *webView = [[[UIWebView alloc] init] autorelease];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
Where "index.html" relatively references images, CSS, javascript, etc.
Create /etc/docker/daemon.json
file where you want to pull docker images and add the following content to that file
{
"insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}
Refer to my blog article for an in-depth explanation of creating a private docker registry: https://geekdosage.com/how-to-create-a-private-docker-registry-in-ubuntu-20-04/
Nobody likes the "refer to this answer" answers, but in this case it may help: Change an HTML5 input's placeholder color with CSS
Since it's only supported by a couple of browsers, you can try the jQuery placeholder plugin (assuming you can\are using jQuery). It allows you to style the placeholder text via CSS since it's really only a swap trick it does with focus events.
The plugin does not activate on browsers that support it, though, so you can have CSS that targets chrome\firefox and the jQuery plugin's CSS to catch the rest.
The plugin can be found here: https://github.com/mathiasbynens/jquery-placeholder
Given right answer is one way to go, however it is an overkill when you can fix it by one config settings.
Better to use it in the dbcontext constructor
public DbContext() // dbcontext constructor
: base("name=ConnectionStringNameFromWebConfig")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
I'm using the J.S. to fix a sidebar menu. I've tried a lot of solutions with CSS but it's the simplest way to solve it, just add J.S. adding and removing a native BootStrap class: "position-fixed".
The J.S.:
var lateral = false;
function fixar() {
var element, name, arr;
element = document.getElementById("minhasidebar");
if (lateral) {
element.className = element.className.replace(
/\bposition-fixed\b/g, "");
lateral = false;
} else {
name = "position-fixed";
arr = element.className.split(" ");
if (arr.indexOf(name) == -1) {
element.className += " " + name;
}
lateral = true;
}
}
The HTML:
Sidebar:
<aside>
<nav class="sidebar ">
<div id="minhasidebar">
<ul class="nav nav-pills">
<li class="nav-item"><a class="nav-link active"
th:href="@{/hoje/inicial}"> <i class="oi oi-clipboard"></i>
<span>Hoje</span>
</a></li>
</ul>
</div>
</nav>
</aside>
Change the auto_prepend_file property on php.ini
; Automatically add files before PHP document.
;http://php.net/auto-prepend-file
auto_prepend_file =
although it is invalid html but you can use selector context to limit your selector in your case it would be like :
$("input[name='name']" , "#form2").val("Hello World! ");
Example:
iptables -A INPUT -j LOG --log-prefix "INPUT:DROP:" --log-level 6
iptables -A INPUT -j DROP
Log Exampe:
Feb 19 14:18:06 servername kernel: INPUT:DROP:IN=eth1 OUT= MAC=aa:bb:cc:dd:ee:ff:11:22:33:44:55:66:77:88 SRC=x.x.x.x DST=x.x.x.x LEN=48 TOS=0x00 PREC=0x00 TTL=117 ID=x PROTO=TCP SPT=x DPT=x WINDOW=x RES=0x00 SYN URGP=0
Other options:
LOG
Turn on kernel logging of matching packets. When this option
is set for a rule, the Linux kernel will print some
information on all matching packets
(like most IP header fields) via the kernel log (where it can
be read with dmesg or syslogd(8)). This is a "non-terminating
target", i.e. rule traversal
continues at the next rule. So if you want to LOG the packets
you refuse, use two separate rules with the same matching
criteria, first using target LOG
then DROP (or REJECT).
--log-level level
Level of logging (numeric or see syslog.conf(5)).
--log-prefix prefix
Prefix log messages with the specified prefix; up to 29
letters long, and useful for distinguishing messages in
the logs.
--log-tcp-sequence
Log TCP sequence numbers. This is a security risk if the
log is readable by users.
--log-tcp-options
Log options from the TCP packet header.
--log-ip-options
Log options from the IP packet header.
--log-uid
Log the userid of the process which generated the packet.
I don't have enough reputation to comment on the previous answers which are great. :) Here are some of the ways how I am debugging when developing react-native app.
Live reloading
react-native makes it super easy to see your changes with the ? + R keys or even just enable live reload and watchman will "refresh" the simulator with the latest changes. If you get an error, you can get a clue from the line number from that red screen. A couple of undo will get you back to working state and start again.
console.log('yeah, seriously.')
I find myself prefer letting the program run and logging some informations than adding a debugger
break point. (tough debugger is useful when trying to work with external packages/libraries and it comes with autocompletion, so you know what other methods you can utilise.)
Enable Chrome Debugging
with debugger;
break point in your program.
Well it depends on the type of errors you encountered and your preferences of how to debug. For most of the undefined is not an object (evaluating 'something.something')
, method 1 and 2 will be good enough for me.
Whereas dealing with external libraries or packages written by other developers will require more effort to debug hence a good tool like Chrome Debugging
Sometimes it is coming from the react-native platform itself so googling for react-native issues will definitely helps.
hope this helps someone out there.
This worked for me with a string-array named shoes
loaded from the projects resources:
Spinner spinnerCountShoes = (Spinner)findViewById(R.id.spinner_countshoes);
ArrayAdapter<String> spinnerCountShoesArrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.shoes));
spinnerCountShoes.setAdapter(spinnerCountShoesArrayAdapter);
This is my resource file (res/values/arrays.xml
) with the string-array named shoes
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="shoes">
<item>0</item>
<item>5</item>
<item>10</item>
<item>100</item>
<item>1000</item>
<item>10000</item>
</string-array>
</resources>
With this method it's easier to make it multilingual (if necessary).
Not purely Java8 but if you use guava's Lists.reverse() method in conjunction, you can easily achieve this:
List<Integer> list = Arrays.asList(1,2,3,4);
Lists.reverse(list).stream().forEach(System.out::println);
<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>
Instructions
First, insert these lines wherever you want within your newsletter code. Then:
If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.
I know this is quite an old question -
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Let's say, you want to extract the first 2 rows and first 3 columns
A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
[4, 5, 6]]
Understanding the syntax
A_NEW = A[start_index_row : stop_index_row,
start_index_column : stop_index_column)]
If one wants row 2 and column 2 and 3
A_NEW = A[1:2, 1:3]
Reference the numpy indexing and slicing article - Indexing & Slicing
As rcar says, you can't without losing some quality, the best you can do in c# is:
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}
The first line of a paragraph is indented by default, thus whether or not you have \indent
there won't make a difference. \indent
and \noindent
can be used to override default behavior. You can see this by replacing your line with the following:
Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented
\noindent override default indentation (not indented)\\
asdf
With Spring 3.1 and Tomcat 7 I got next error:
org.springframework.web.servlet.DispatcherServlet noHandlerFound No mapping found for HTTP request with URI [/baremvc/] in DispatcherServlet with name 'appServlet'
And I needed to add to web.xml next configuration:
<welcome-file-list>
<welcome-file/>
</welcome-file-list>
And the application worked!
For me, I'm using Windows 10, @andrew-marshall's instructions worked (Thanks!) except that git.exe
was within a cmd
directory within PortableGit...
, not bin
, so I had to put \cmd
on the end of the path I added to PATH
. Thought I would post this here in case anyone else hits the same issue. You can tell it works once git
in a new Command Prompt window returns command usage info and not an error.
This is a very old question - but still for reference if others are looking at it - requestAnimationFrame()
is the right way to handle animation in modern browsers:
UPDATE: The mozilla link shows how to do this - I didn't feel like repeating the text behind the link ;)
Suppose we have a generator:
def gen():
for i in range(10):
yield i
We can wrap the generator, along with the known length, in an object:
import itertools
class LenGen(object):
def __init__(self,gen,length):
self.gen=gen
self.length=length
def __call__(self):
return itertools.islice(self.gen(),self.length)
def __len__(self):
return self.length
lgen=LenGen(gen,10)
Instances of LenGen
are generators themselves, since calling them returns an iterator.
Now we can use the lgen
generator in place of gen
, and access len(lgen)
as well:
def new_gen():
for i in lgen():
yield float(i)/len(lgen)
for i in new_gen():
print(i)
I had the same need & quickly patched an existing code to be able to do something like this:
if( $('.scroll').hasHandlers('mouseout') ) // could be click, or '*'...
{
... code ..
}
It works for event delegation too:
if ( $('#main').hasHandlers('click','.simple-search') ) ...
It is available here : jquery-handler-toolkit.js
You'll need to create an instance of the class and invoke the method on it.
public class Foo
{
public void Data1()
{
}
public static void Data2()
{
Foo foo = new Foo();
foo.Data1();
}
}
I'm using Chrome and print() literally prints the text on paper. This is what works for me:
document.write("My message");
The usual way to do it is as outlined by Guffa, nested elements. It's a bit sad having to add extra markup to get the hooks you need for this, but in practice a wrapper div here or there isn't going to hurt anyone.
If you must do it without extra elements (eg. when you don't have control of the page markup), you can use box-sizing, which has pretty decent but not complete or simple browser support. Likely more fun than having to rely on scripting though.
You can use my utility function created for shadow and corner radius as below:
- (void)addShadowWithRadius:(CGFloat)shadowRadius withShadowOpacity:(CGFloat)shadowOpacity withShadowOffset:(CGSize)shadowOffset withShadowColor:(UIColor *)shadowColor withCornerRadius:(CGFloat)cornerRadius withBorderColor:(UIColor *)borderColor withBorderWidth:(CGFloat)borderWidth forView:(UIView *)view{
// drop shadow
[view.layer setShadowRadius:shadowRadius];
[view.layer setShadowOpacity:shadowOpacity];
[view.layer setShadowOffset:shadowOffset];
[view.layer setShadowColor:shadowColor.CGColor];
// border radius
[view.layer setCornerRadius:cornerRadius];
// border
[view.layer setBorderColor:borderColor.CGColor];
[view.layer setBorderWidth:borderWidth];
}
Hope it will help you!!!
better use timer:
Sub wait (sec)
dim temp
temp=timer
do while timer-temp<sec
loop
end Sub
Just to add on Jukka K. Korpela answer above, font awesome already defined a css selector "fa". You can simply do <i class="fa"></i>
. The catch here is, fa defines the font-style:normal, if you need italic, you can override like <i class="fa" style="font-style:italic"></i>
Section 6.16 Frame target names in the HTML 4.01 spec defines the meanings, but it is partly outdated. It refers to “windows”, whereas HTML5 drafts more realistically speak about “browsing contexts”, since modern browsers often use tabs instead of windows in this context.
Briefly, _self
is the default (current browsing context, i.e. current window or tab), so it is useful only to override a <base target=...>
setting. The value _parent
refers to the frameset that is the parent of the current frame, whereas _top
“breaks out of all frames” and opens the linked document in the entire browser window.
There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/
You can always add the "!" into your float-options. This way, latex tries really hard to place the figure where you want it (I mostly use [h!tb]), stretching the normal rules of type-setting.
I have found another solution:
Use the float-package. This way you can place the figures where you want them to be.
Simply add []
to those names like
<input type="text" class="form-control" placeholder="Titel" name="levels[level][]">
<input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">
Take that template and then you can add those even using a loop.
Then you can add those dynamically as much as you want, without having to provide an index. PHP will pick them up just like your expected scenario example.
Edit
Sorry I had braces in the wrong place, which would make every new value as a new array element. Use the updated code now and this will give you the following array structure
levels > level (Array)
levels > build_time (Array)
Same index on both sub arrays will give you your pair. For example
echo $levels["level"][5];
echo $levels["build_time"][5];
I got this to work by calling this function in document ready:
$(document).ready(function () {
$.fancybox({
'width': '40%',
'height': '40%',
'autoScale': true,
'transitionIn': 'fade',
'transitionOut': 'fade',
'type': 'iframe',
'href': 'http://www.example.com'
});
});
Try this,
Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText();
Shadowbox is your best choice. Check it out.
Try to make the bounds
's size integer.
#include <math.h>
....
if (ratio > 1) {
bounds.size.width = resolution;
bounds.size.height = round(bounds.size.width / ratio);
} else {
bounds.size.height = resolution;
bounds.size.width = round(bounds.size.height * ratio);
}
How about something like this ...
var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };
var g = l1.GroupBy( i => i );
foreach( var grp in g )
{
Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}
Edit per comment: I will try and do this justice. :)
In my example, it's a Func<int, TKey>
because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int>
(a grouping of ints keyed by an int). If I changed it to (i => i.ToString()
) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...
private string SampleMethod( int i )
{
// magically return "One" if i == 1, "Two" if i == 2, etc.
}
So, that's a Func that would take an int and return a string, just like ...
i => // magically return "One" if i == 1, "Two" if i == 2, etc.
But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.
In theory the 4 digit option is right. But in practice it might be better to have 1900-2099 range.
Additionally it need to be non-capturing group. Many comments and answers propose capturing grouping which is not proper IMHO. Because for matching it might work, but for extracting matches using regex it will extract 4 digit numbers and two digit (19 and 20) numbers also because of paranthesis.
This will work for exact matching using non-capturing groups:
(?:19|20)\d{2}
Check all 'C' characters. There are may be some cyrillic 'C's in english-looking word.
Reason for this is that in both english and russian keyboards 'C' occupies same physical button.
In your component -
Make sure to initialize the formControl name country with a value.
For instance: Assuming that your form group name is myForm and _fb is FormBuilder instance then,
....
this.myForm = this._fb.group({
country:[this.default]
})
and also try replacing [value] with [ngValue].
EDIT 1: If you are unable to initialize the value when declaring then set the value when you have the value like this.
this.myForm.controls.country.controls.setValue(this.country)
You might get even better results if you try:
console.log(JSON.stringify(obj, null, 4));
In a nutshell, you don't have the object as $this in the second case, as the static method is a function/method of the class not the object instance.
You can easily make SSH connections using SSHLibrary. Read this post :
https://workpython.blogspot.com/2020/04/creating-ssh-connections-with-python.html
In SQL Server Management Studio, go to Object Explorer > (your server) > Security > Logins
and right-click New Login
:
Then in the dialog box that pops up, pick the types of objects you want to see (Groups
is disabled by default - check it!) and pick the location where you want to look for your objects (e.g. use Entire Directory
) and then find your AD group.
You now have a regular SQL Server Login - just like when you create one for a single AD user. Give that new login the permissions on the databases it needs, and off you go!
Any member of that AD group can now login to SQL Server and use your database.
Using a loop -
public static boolean containsDigit(final String aString)
{
if (aString != null && !aString.isEmpty())
{
for (char c : aString.toCharArray())
{
if (Character.isDigit(c))
{
return true;
}
}
}
return false;
}
Using a stream -
public static boolean containsDigit(final String aString)
{
return aString != null && !aString.isEmpty() &&
aString.chars().anyMatch(Character::isDigit);
}
You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.
Here is the Basic Difference between Compiler vs Interpreter Language.
Compiler Language
Interpreter Language:
Setting CommandTimeout to 120 is not recommended. Try using pagination as mentioned above. Setting CommandTimeout to 30 is considered as normal. Anything more than that is consider bad approach and that usually concludes something wrong with the Implementation. Now the world is running on MiliSeconds Approach.
If you are using jQuery, use css to add CSS
$("#voltaic_holder").css({'position': 'absolute',
'top': '-75px'});
To remove CSS attributes
$("#voltaic_holder").css({'position': '',
'top': ''});
When you read in git tag
man page:
One important aspect of git is it is distributed, and being distributed largely means there is no inherent "upstream" or "downstream" in the system.
, that simply means there is no absolute upstream repo or downstream repo.
Those notions are always relative between two repos and depends on the way data flows:
If "yourRepo" has declared "otherRepo" as a remote one, then:
Note the "from" and "for": you are not just "downstream", you are "downstream from/for", hence the relative aspect.
The DVCS (Distributed Version Control System) twist is: you have no idea what downstream actually is, beside your own repo relative to the remote repos you have declared.
Basically:
In term of "flow of data", your repo is at the bottom ("downstream") of a flow coming from upstream repos ("pull from") and going back to (the same or other) upstream repos ("push to").
You can see an illustration in the git-rebase
man page with the paragraph "RECOVERING FROM UPSTREAM REBASE":
It means you are pulling from an "upstream" repo where a rebase took place, and you (the "downstream" repo) is stuck with the consequence (lots of duplicate commits, because the branch rebased upstream recreated the commits of the same branch you have locally).
That is bad because for one "upstream" repo, there can be many downstream repos (i.e. repos pulling from the upstream one, with the rebased branch), all of them having potentially to deal with the duplicate commits.
Again, with the "flow of data" analogy, in a DVCS, one bad command "upstream" can have a "ripple effect" downstream.
Note: this is not limited to data.
It also applies to parameters, as git commands (like the "porcelain" ones) often call internally other git commands (the "plumbing" ones). See rev-parse
man page:
Many git porcelainish commands take mixture of flags (i.e. parameters that begin with a dash '
-
') and parameters meant for the underlyinggit rev-list
command they use internally and flags and parameters for the other commands they use downstream ofgit rev-list
. This command is used to distinguish between them.
See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);
And my 15 cent. A one liner for the mac terminal etc just set the MIN= to whatever and a message
MIN=15 && for i in $(seq $(($MIN*60)) -1 1); do echo "$i, "; sleep 1; done; echo -e "\n\nMac Finder should show a popup" afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Look away. Rest your eyes"'
A bonus example for inspiration to combine more commands; this will put a mac put to standby sleep upon the message too :) the sudo login is needed then, a multiplication as the 60*2 for two hours goes aswell
sudo su
clear; echo "\n\nPreparing for a sleep when timers done \n"; MIN=60*2 && for i in $(seq $(($MIN*60)) -1 1); do printf "\r%02d:%02d:%02d" $((i/3600)) $(( (i/60)%60)) $((i%60)); sleep 1; done; echo "\n\n Time to sleep zzZZ"; afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Time to sleep zzZZ"'; shutdown -h +1 -s
In case anyone wanted more of a visual reference:
Decimal approximations reference table:
+----------------------------------------------------------------------------+
¦ aspect ratio ¦ decimal approx. ¦ decimal approx. ¦
¦ [long edge x short edge] ¦ [short edge/long edge] ¦ [long edge/short edge] ¦
¦--------------------------+------------------------+------------------------¦
¦ 19.5 x 9 ¦ 0.462... ¦ 2.167... ¦
¦--------------------------+------------------------+------------------------¦
¦ 19 x 9 ¦ 0.474... ¦ 2.11... ¦
¦--------------------------+------------------------+------------------------¦
¦ ~18.7 x 9 ¦ 0.482... ¦ 2.074... ¦
¦--------------------------+------------------------+------------------------¦
¦ 18.5 x 9 ¦ 0.486... ¦ 2.056... ¦
¦--------------------------+------------------------+------------------------¦
¦ 18 x 9 ¦ 0.5 ¦ 2 ¦
¦--------------------------+------------------------+------------------------¦
¦ 19 x 10 ¦ 0.526... ¦ 1.9 ¦
¦--------------------------+------------------------+------------------------¦
¦ 16 x 9 ¦ 0.5625 ¦ 1.778... ¦
¦--------------------------+------------------------+------------------------¦
¦ 5 x 3 ¦ 0.6 ¦ 1.667... ¦
¦--------------------------+------------------------+------------------------¦
¦ 16 x 10 ¦ 0.625 ¦ 1.6 ¦
¦--------------------------+------------------------+------------------------¦
¦ 3 x 2 ¦ 0.667... ¦ 1.5 ¦
¦--------------------------+------------------------+------------------------¦
¦ 4 x 3 ¦ 0.75 ¦ 1.333... ¦
+----------------------------------------------------------------------------+
Changelog:
56x27 === ~18.7x9
(Huawei P20), 19x9
(Nokia X6 2018) and 19.5x9
(LG G7 ThinQ)19x10
(Essential Phone)18.5x9
(Samsung Galaxy S8) and 18x9
(LG G6)I fixed this by changing EntityClient
back to SqlClient
, even though I was using Entity Framework.
So my complete connection string was in the format:
<add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx" providerName="System.Data.SqlClient" />
public static class Employee
{
public static string SomeSetting
{
get
{
return ConfigurationManager.AppSettings["SomeSetting"];
}
}
}
Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.
If you feel that you must store a reference to appsettings, try
public static class Employee
{
private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;
public static NameValueCollection AppSettings { get { return _appSettings; } }
}
It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.
In the many situations where the IMG can be made position:absolute, you can use clip to hide the blurred edges--and the outer DIV is unnecessary.
img {
filter: blur(5px);
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
position: absolute;
clip: rect(5px,295px,295px;5px);
}
Do something like this:
A <div>
with ID of #imageDIV
, another one with ID #download
and a hidden <div>
with ID #previewImage
.
Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN
Then add this script:
var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
$("#download").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#download").attr("download", "image.png").attr("href", newData);
});
The div will be saved as a PNG on clicking the #download
You can delete the service:
sc delete ServiceName
Then recreate the service.
Depending on the type of your variable, one of abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
, or fabsl(long double)
.
Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)
(Alas, there is no habs(short)
function. Or scabs(signed char)
for that matter...)
Apple's and GNU's Objective-C headers also include an ABS()
macro which is type-agnostic. I don't recommend using ABS()
however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++)
will have an undefined result.
If you're using C++ or Objective-C++, you can bring in the <cmath>
header and use std::abs()
, which is templated for all the standard integer and floating-point types.
<?php
$email = "someone@exa mple.com";
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
echo "E-mail is not valid";
else
echo "E-mail is valid";
?>
You can use trunc and to_date as follows:
select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.*
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;
Before you start, go to the directory "phpMyAdmin" preferably the one in your localhost, clear all of your cookies, and have your sql running by entering:
sudo /usr/local/mysql/support-files/mysql.server start
To fix the error , you will have to run the following commands in your terminal:
export PATH=$PATH:/usr/local/mysql/bin/
then:
mysql -u root
after which, you'll need to change your permissions inside the mySQL shell:
UPDATE user SET Password=PASSWORD('YOURNEWPASSWORD') WHERE User='root'; FLUSH PRIVILEGES; exit;
Refresh your phpMyAdmin window, re-enter the "root" username (or whichever is applicable), and your password and you should be good to go. Check http://machiine.com/2013/how-to-setup-phpmyadmin-on-a-mac-with-osx-10-8-mamp-part-3/ if you are willing to set up from scratch.
Rather than finding which version you are using you can rephrase your question to "which version of ECMA script does my browser's JavaScript/JSscript engine conform to".
For IE :
alert(@_jscript_version); //IE
Refer Squeegy's answer for non-IE versions :)
This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.
NSArray *data = @[@"The String Value"];
if you need to send more than just 1 string value, you could also use
NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];
then you can send it to the function like below
theFunction(data);
The important needs to be inside the ;
td.rule2 div { background-color: #ffff00 !important; }
in fact i believe this should override it
td.rule2 { background-color: #ffff00 !important; }
On older notebooks with integrated video Swing app starts and works much faster than JavaFX app. As for development, I'd recommend switch to Scala - comparable Scala Swing app contains 2..3 times less code than Java. As for Swing vs SWT: Netbeans GUI considerably faster than Eclipse...
Late to the party, but in case this happens with a WORDPRESS
installation :
#1273 - Unknown collation: 'utf8mb4_unicode_520_ci
In phpmyadmin, under export method
> Format-specific options
( custom export )
Set to : MYSQL40
If you will try to import now, you now might get another error message :
1064 - You have an error in your SQL syntax; .....
That is because The older TYPE
option that was synonymous with ENGINE
was removed in MySQL 5.5.
Open your .sql
file , search and replace all instances
from TYPE=
to ENGINE=
Now the import should go smoothly.
// this is a Jquery plugin function that fires an event when the size of an element is changed
// usage: $().sizeChanged(function(){})
(function ($) {
$.fn.sizeChanged = function (handleFunction) {
var element = this;
var lastWidth = element.width();
var lastHeight = element.height();
setInterval(function () {
if (lastWidth === element.width()&&lastHeight === element.height())
return;
if (typeof (handleFunction) == 'function') {
handleFunction({ width: lastWidth, height: lastHeight },
{ width: element.width(), height: element.height() });
lastWidth = element.width();
lastHeight = element.height();
}
}, 100);
return element;
};
}(jQuery));
Here is a good article on the matter - "Use references when you can, and pointers when you have to."
begin
var_number := 10;
if var_number > 100 then
dbms_output.put_line(var_number||' is greater than 100');
else if var_number < 100 then
dbms_output.put_line(var_number||' is less than 100');
else
dbms_output.put_line(var_number||' is equal to 100');
end if;
end if;
Things have changed quite a bit since this question was asked. There are now options to let Google index your AngularJS site. The easiest option I found was to use http://prerender.io free service that will generate the crwalable pages for you and serve that to the search engines. It is supported on almost all server side web platforms. I have recently started using them and the support is excellent too.
I do not have any affiliation with them, this is coming from a happy user.
Based on the method Bootstrap uses to set its Responsive breakpoints, the following function returns xs, sm, md, lg or xl based on the screen width:
console.log(breakpoint());
function breakpoint() {
let breakpoints = {
'(min-width: 1200px)': 'xl',
'(min-width: 992px) and (max-width: 1199.98px)': 'lg',
'(min-width: 768px) and (max-width: 991.98px)': 'md',
'(min-width: 576px) and (max-width: 767.98px)': 'sm',
'(max-width: 575.98px)': 'xs',
}
for (let media in breakpoints) {
if (window.matchMedia(media).matches) {
return breakpoints[media];
}
}
return null;
}
_x000D_
This question will give you good insights on how to delete a record from a DataTable:
DataTable, How to conditionally delete rows
It would look like this:
DataRow[] drr = dt.Select("Student=' " + id + " ' ");
foreach (var row in drr)
row.Delete();
Don't forget that if you want to update your database, you are going to need to call the Update command. For more information on that, see this link:
You can simple make use of lapply
or sapply
builtin functions.
lapply
will return you a list
-
lapply(dataframe,class)
while sapply
will take the best possible return type ex. Vector etc -
sapply(dataframe,class)
Both the commands will return you all the column names with their respective class.
RunOnUIThread didn't seem to work for me but the following ended up solving my issues.
_ = MainThread.InvokeOnMainThreadAsync(async () =>
{
this.LoadApplication(Startup.Init(this.ConfigureServices));
var authenticationService = App.ServiceProvider.GetService<AuthenticationService>();
if (authenticationService.AuthenticationResult == null)
{
await authenticationService.AuthenticateAsync(AuthenticationUserFlow.SignUpSignIn, CrossCurrentActivity.Current.Activity).ConfigureAwait(false);
}
});
Within the Startup.Init method there is ReactiveUI routing and this needs to be invoked on the main thread. This Invoke method also accepts async/await better than RunOnUIThread.
So anywhere I need to invoke methods on the mainthread I use this.
Please comment on this if anyone knows something I don't and can help me improve my application.
Why don't you use ACL's to distinguish traffic? on top of my head:
acl go_sslwebserver path bar
use_backend sslwebserver if go_sslwebserver
This goes on top of what Matthew Brown answered.
See the ha docs , search for things like hdr_dom and below to find more ACL options. There are plenty of choices.
System.setProperty("gate.home", "/some/directory");
For more information, see:
System.setProperty( String key , String value )
.I used the data from Shawn's answer but generalized and shortened the regex a little. The key difference with this one is that it won't test for a valid Youtube URL, it'll just look for a video ID. Meaning it will still return a video ID for www.facebook.com?wtv=youtube.com/v/vidid
. Works for all the test cases, but is a bit more lax. Consequently, it will output a false positive for something like https://www.twitter.com/watch?v=vidid
. Use this method if the data is super inconsistent, otherwise use a more specific regex or parse_url()
and parse_str()
.
preg_match("/([\?&\/]vi?|embed|\.be)[\/=]([\w-]+)/",$url,$matches);
print($matches[2]);
this error get if add decimal format. i just add
step="0.1"
You should be using a library to do URI manipulation as it is more complicated than it seems on the surface to do it yourself. Take a look at: http://medialize.github.io/URI.js/
Recommendation. Do not use user-added REM statements to block batch steps. Use conditional GOTO instead. That way you can predefine and test the steps and options. The users also get much simpler changes and better confidence.
@Echo on
rem Using flags to control command execution
SET ExecuteSection1=0
SET ExecuteSection2=1
@echo off
IF %ExecuteSection1%==0 GOTO EndSection1
ECHO Section 1 Here
:EndSection1
IF %ExecuteSection2%==0 GOTO EndSection2
ECHO Section 2 Here
:EndSection2
There is a new way to do this.
Android Studio 2.2 has APK Analyzer it will give lot of info about apk, checkout it here :- http://android-developers.blogspot.in/2016/05/android-studio-22-preview-new-ui.html
A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.
$array = some_json();
// Encode all string children in the array to html entities.
array_walk_recursive($array, function(&$item, $key) {
if(is_string($item)) {
$item = htmlentities($item);
}
});
$json = json_encode($array);
// Decode the html entities and end up with unicode again.
$json = html_entity_decode($rson);
If you want to grant to both tables and views try:
SELECT DISTINCT
|| OWNER
|| '.'
|| TABLE_NAME
|| ' to db_user;'
FROM
ALL_TAB_COLS
WHERE
TABLE_NAME LIKE 'TABLE_NAME_%';
For just views try:
SELECT
'grant select on '
|| OWNER
|| '.'
|| VIEW_NAME
|| ' to REPORT_DW;'
FROM
ALL_VIEWS
WHERE
VIEW_NAME LIKE 'VIEW_NAME_%';
Copy results and execute.
In order to find the location of a script, use Split-Path $MyInvocation.MyCommand.Path
(make sure you use this in the script context).
The reason you should use that and not anything else can be illustrated with this example script.
## ScriptTest.ps1
Write-Host "InvocationName:" $MyInvocation.InvocationName
Write-Host "Path:" $MyInvocation.MyCommand.Path
Here are some results.
PS C:\Users\JasonAr> .\ScriptTest.ps1 InvocationName: .\ScriptTest.ps1 Path: C:\Users\JasonAr\ScriptTest.ps1 PS C:\Users\JasonAr> . .\ScriptTest.ps1 InvocationName: . Path: C:\Users\JasonAr\ScriptTest.ps1 PS C:\Users\JasonAr> & ".\ScriptTest.ps1" InvocationName: & Path: C:\Users\JasonAr\ScriptTest.ps1
In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot
:
## ScriptTest.ps1
Write-Host "Script:" $PSCommandPath
Write-Host "Path:" $PSScriptRoot
PS C:\Users\jarcher> .\ScriptTest.ps1 Script: C:\Users\jarcher\ScriptTest.ps1 Path: C:\Users\jarcher
Put double exclamation mark i.e !! before the function name that you want to check. If it exists, it will return true.
function abc(){
}
!!window.abc; // return true
!!window.abcd; // return false
You can use df.plot.scatter, and pass an array to c= argument defining the color of each point:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
colors = np.where(df["key1"]==4,'r','-')
colors[df["key1"]==6] = 'g'
colors[df["key1"]==8] = 'b'
print(colors)
df.plot.scatter(x="one",y="two",c=colors)
plt.show()
The app will only exit if there are no activities in the back stack. SO add this line in your manifest android:noHistory="true" to all the activities that you dont want to be back stacked.And then to close the app call the finish() in the OnBackPressed
<activity android:name=".activities.DemoActivity"
android:screenOrientation="portrait"
**android:noHistory="true"**
/>
The profile choices need to be setup as a ManyToManyField for this to work correctly.
So... your model should be like this:
class Choices(models.Model):
description = models.CharField(max_length=300)
class Profile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True, verbose_name='user')
choices = models.ManyToManyField(Choices)
Then, sync the database and load up Choices with the various options you want available.
Now, the ModelForm will build itself...
class ProfileForm(forms.ModelForm):
Meta:
model = Profile
exclude = ['user']
And finally, the view:
if request.method=='POST':
form = ProfileForm(request.POST)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
else:
form = ProfileForm()
return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))
It should be mentioned that you could setup a profile in a couple different ways, including inheritance. That said, this should work for you as well.
Good luck.
Share Any File as below ( Kotlin ) :
first create a folder named xml
in the res
folder and create a new XML Resource File named provider_paths.xml
and put the below code inside it :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="files"
path="."/>
<external-path
name="external_files"
path="."/>
</paths>
now go to the manifests
folder and open the AndroidManifest.xml
and then put the below code inside the <application>
tag :
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>
now you put the below code in the setOnLongClickListener
:
share_btn.setOnClickListener {
try {
val file = File("pathOfFile")
if(file.exists()) {
val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setType("*/*")
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
toast("Error")
}
}
This pulls back client info as well.
var get = function(u){
var x = new XMLHttpRequest;
x.open('GET', u, false);
x.send();
return x.responseText;
}
JSON.parse(get('http://ifconfig.me/all.json'))
It's either through system property
-Dorg.slf4j.simpleLogger.defaultLogLevel=debug
or simplelogger.properties
file on the classpath
see http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html for details
//javascript
//teams.Table does not exist
function OnSuccessJSON(data, status) {
var teams = eval('(' + data.d + ')');
var listItems = "";
for (var i = 0; i < teams.length; i++) {
listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
}
$("#<%=ddlTeams.ClientID%>").html(listItems);
}
For me this solution worked well to center an input field in a TD:
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet" />_x000D_
<td style="background:#B3AEB5;">_x000D_
<div class="form-group text-center">_x000D_
<div class="input-group" style="margin:auto;">_x000D_
<input type="month" name="p2" value="test">_x000D_
</div>_x000D_
</div>_x000D_
</td>
_x000D_
If it is a standalone (Main method) java project then Not any specific path put all the jars inside the project not any specific path then right click on the project - > export - > Runnable jar --> Select the lunch configuration and Library handeling then choose the radio button option "Package required libraries into generated jar" -- > Finish.
Or
If you have a web project then put all the jars in web-inf/lib folder and do the same step.
In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference
use v5.13.7;
foreach my $key (keys $ad_grp_ref) {
...
}
A picture is worth a thousand words !
The concept of Angular is very simple. It propose to "build" an app with "bricks" -> modules.
This concept makes it possible to better structure the code and to facilitate reuse and sharing.
Be careful not to confuse the Angular modules with the ES2015 / TypeScript modules.
Regarding the Angular module, it is a mechanism for:
1- group components (but also services, directives, pipes etc ...)
2- define their dependencies
3- define their visibility.
An Angular module is simply defined with a class (usually empty) and the NgModule decorator.
Having a look at MySQL documentation for the string functions, we can also use CHAR_LENGTH()
and CHARACTER_LENGTH()
as well.
try this
<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>
Expose this iframe in the master page's codebehind:
public HtmlControl iframe
{
get
{
return this.myIframe;
}
}
Add the MasterType directive for the content page to strongly typed Master Page.
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>
In code behind
protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}
most simple way,
use set().difference(set())
list_a = [1,2,3]
list_b = [2,3]
print set(list_a).difference(set(list_b))
answer is set([1])
can print as a list,
print list(set(list_a).difference(set(list_b)))
There is no search and replace function or stream editing at the command line in XP or 2k3 (dont know about vista or beyond). So, you'll need to use a script like the one Ghostdog posted, or a search and replace capable tool like sed.
There is more than one way to do it, as this script shows:
@echo off
SETLOCAL=ENABLEDELAYEDEXPANSION
rename text.file text.tmp
for /f %%a in (text.tmp) do (
set foo=%%a
if !foo!==ex3 set foo=ex5
echo !foo! >> text.file)
del text.tmp
You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do
for (var i = myArray.length - 1; i >= 0; i--) { console.log(eval(myArray[i])); };
More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.
var result = {}; for (var i = myArray.length - 1; i >= 0; i--) { result[myArray[i]] = eval(myArray[i]); };
I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via
window['myVarName'] = 'namingCollisionsAreFun';
(per comment)
Some project might want to add *.manifest
to their visual studio gitignore.io
file.
That is because some Visual Studio project properties of new projects are set to generate a manifest file.
See "Manifest Generation in Visual Studio"
But if you have generated them and they are static (not changing over time), then it is a good idea to remove them from the .gitignore
file.
That is what a project like Git for Windows just did (for Git 2.24, Q4 2019)
See commit aac6ff7 (05 Sep 2019) by Johannes Schindelin (dscho
).
(Merged by Junio C Hamano -- gitster
-- in commit 59438be, 30 Sep 2019)
.gitignore
: stop ignoring.manifest
filesOn Windows, it is possible to embed additional metadata into an executable by linking in a "manifest", i.e. an XML document that describes capabilities and requirements (such as minimum or maximum Windows version).
These XML documents are expected to be stored in.manifest
files.At least some Visual Studio versions auto-generate
.manifest
files when none is specified explicitly, therefore we used to ask Git to ignore them.However, we do have a beautiful
.manifest
file now:compat/win32/git.manifest
, so neither does Visual Studio auto-generate a manifest for us, nor do we want Git to ignore the.manifest
files anymore.
Create a function like so:
CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE @result INT
EXEC master.dbo.xp_fileexist @path, @result OUTPUT
RETURN cast(@result as bit)
END;
GO
Edit your table and add a computed column (IsExists BIT). Set the expression to:
dbo.fn_FileExists(filepath)
Then just select:
SELECT * FROM dbo.MyTable where IsExists = 1
Update:
To use the function outside a computed column:
select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable
Update:
If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.
And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.
Here is how I solved the issue, might be useful to some:
Ajax modal doesn't seem to be available with boostrap 2.1.1
So I ended up coding it myself:
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
//var modal_id = $(this).attr('data-target');
$.get(url, function(data) {
$(data).modal();
});
});
Example of a link that calls a modal:
<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
I now send the whole modal markup through ajax.
Credits to drewjoh
If you have the managed = True
in yout model Meta, you need to remove it and do a migration. Then run the migrations again, it will detect the new updates.
You could also use the apache library and do this:
StringUtils.split(test, "|");
XmlWriter is the fastest way to write good XML. XDocument, XMLDocument and some others works good aswell, but are not optimized for writing XML. If you want to write the XML as fast as possible, you should definitely use XmlWriter.
If you are not using Math.round() function the solution suggested by Dr.Molle will not work in some cases when a browser window has a zoom.
For example $(this).scrollTop() + $(this).innerHeight() = 600
$(this)[0].scrollHeight yields = 599.99998
600 >= 599.99998 fails.
Here is the correct code:
jQuery(function($) {
$('#flux').on('scroll', function() {
if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10)) {
alert('end reached');
}
})
});
You may also add some extra margin pixels if you do not need a strict condition
var margin = 4
jQuery(function($) {
$('#flux').on('scroll', function() {
if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10) - margin) {
alert('end reached');
}
})
});
Was having an issue getting the "Run in Postman" links to work with the browsers until I added this to the .desktop file
MimeType=application/postman;x-scheme-handler/postman;
To Enter into crontab :
crontab -e
write this into the file:
0 */2 * * * python/php/java yourfilepath
Example :0 */2 * * * python ec2-user/home/demo.py
and make sure you have keep one blank line after the last cron job in your crontab file
You could try:
$rows = array();
while($row = mysql_fetch_array($result)){
array_push($rows, $row);
}
echo json_encode($rows);
this is my blog on git and its for beginners who want to get started on git. https://techxposers.com/git-for-beginners/
You could use AJAX to send a POST request if you don't want forms.
Using jquery $.post method it is pretty simple:
$.post('/foo.php', { key1: 'value1', key2: 'value2' }, function(result) {
alert('successfully posted key1=value1&key2=value2 to foo.php');
});
Change your clean
so rm
will not complain:
clean:
rm -f .lambda .lambda_t .activity .activity_t_lambda
This solution requires only the installation of dill and no other libraries as pathos
def apply_packed_function_for_map((dumped_function, item, args, kwargs),):
"""
Unpack dumped function as target function and call it with arguments.
:param (dumped_function, item, args, kwargs):
a tuple of dumped function and its arguments
:return:
result of target function
"""
target_function = dill.loads(dumped_function)
res = target_function(item, *args, **kwargs)
return res
def pack_function_for_map(target_function, items, *args, **kwargs):
"""
Pack function and arguments to object that can be sent from one
multiprocessing.Process to another. The main problem is:
«multiprocessing.Pool.map*» or «apply*»
cannot use class methods or closures.
It solves this problem with «dill».
It works with target function as argument, dumps it («with dill»)
and returns dumped function with arguments of target function.
For more performance we dump only target function itself
and don't dump its arguments.
How to use (pseudo-code):
~>>> import multiprocessing
~>>> images = [...]
~>>> pool = multiprocessing.Pool(100500)
~>>> features = pool.map(
~... *pack_function_for_map(
~... super(Extractor, self).extract_features,
~... images,
~... type='png'
~... **options,
~... )
~... )
~>>>
:param target_function:
function, that you want to execute like target_function(item, *args, **kwargs).
:param items:
list of items for map
:param args:
positional arguments for target_function(item, *args, **kwargs)
:param kwargs:
named arguments for target_function(item, *args, **kwargs)
:return: tuple(function_wrapper, dumped_items)
It returs a tuple with
* function wrapper, that unpack and call target function;
* list of packed target function and its' arguments.
"""
dumped_function = dill.dumps(target_function)
dumped_items = [(dumped_function, item, args, kwargs) for item in items]
return apply_packed_function_for_map, dumped_items
It also works for numpy arrays.
I fixed this (using Java / Spring backend) by adding a handler that matches everything defined in my Angular routes, that sends back index.html instead of a 404. This then effectively (re)bootstraps the application and loads the correct page. I also have a 404 handler for anything that isn't caught by this.
@Controller ////don't use RestController or it will just send back the string "index.html"
public class Redirect {
private static final Logger logger = LoggerFactory.getLogger(Redirect.class);
@RequestMapping(value = {"comma", "sep", "list", "of", "routes"})
public String redirectToIndex(HttpServletRequest request) {
logger.warn("Redirect api called for URL {}. Sending index.html back instead. This will happen on a page refresh or reload when the page is on an Angular route", request.getRequestURL());
return "/index.html";
}
}
I got same problem lot of time. Check your request url, if you are requesting on local server like 127.1.1/api or 192.168...., try to change it, make sure you are hitting cloud.
how about trying this?
void CheckKey(void) {
int key;
if (kbhit()) {
key=getch();
if (key == 224) {
do {
key=getch();
} while(key==224);
switch (key) {
case 72:
printf("up");
break;
case 75:
printf("left");
break;
case 77:
printf("right");
break;
case 80:
printf("down");
break;
}
}
printf("%d\n",key);
}
int main() {
while (1) {
if (kbhit()) {
CheckKey();
}
}
}
(if you can't understand why there is 224, then try running this code: )
#include <stdio.h>
#include <conio.h>
int main() {
while (1) {
if (kbhit()) {
printf("%d\n",getch());
}
}
}
but I don't know why it's 224. can you write down a comment if you know why?
You can easily create timed redirections with JavaScript. But I suggest you to use location.replace('url') instead of location.href. It prevents to browser to push the site into the history. I found this JavaScript redirect tool. I think you could use this.
Example code (with 5 secs delay):
<!-- Pleace this snippet right after opening the head tag to make it work properly -->
<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->
<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.com/"/>
<noscript>
<meta http-equiv="refresh" content="5;URL=https://yourdomain.com/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
var url = "https://yourdomain.com/";
var delay = "5000";
window.onload = function ()
{
setTimeout(GoToURL, delay);
}
function GoToURL()
{
if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
{
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else { window.location.replace(url); } // All other browsers
}
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->
The simplest solution:
I made a reactive version that accepts callbacks for stdOut and StdErr.
onStdOut
and onStdErr
are called asynchronously,
as soon as data arrives (before the process exits).
public static Int32 RunProcess(String path,
String args,
Action<String> onStdOut = null,
Action<String> onStdErr = null)
{
var readStdOut = onStdOut != null;
var readStdErr = onStdErr != null;
var process = new Process
{
StartInfo =
{
FileName = path,
Arguments = args,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = readStdOut,
RedirectStandardError = readStdErr,
}
};
process.Start();
if (readStdOut) Task.Run(() => ReadStream(process.StandardOutput, onStdOut));
if (readStdErr) Task.Run(() => ReadStream(process.StandardError, onStdErr));
process.WaitForExit();
return process.ExitCode;
}
private static void ReadStream(TextReader textReader, Action<String> callback)
{
while (true)
{
var line = textReader.ReadLine();
if (line == null)
break;
callback(line);
}
}
The following will run executable
with args
and print
to the console.
RunProcess(
executable,
args,
s => { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(s); },
s => { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(s); }
);
normally, Maxim Donnie's method can find the reason. But I encountered one 400 bad request will not log to err_log. I found the reason with the help with tcpdump
If you think of the std::list
like a queue, then you can dequeue and enqueue all the items that you want to keep, but only dequeue (and not enqueue) the item you want to remove. Here's an example where I want to remove 5 from a list containing the numbers 1-10...
std::list<int> myList;
int size = myList.size(); // The size needs to be saved to iterate through the whole thing
for (int i = 0; i < size; ++i)
{
int val = myList.back()
myList.pop_back() // dequeue
if (val != 5)
{
myList.push_front(val) // enqueue if not 5
}
}
myList
will now only have numbers 1-4 and 6-10.
The following seemed to work well for me:
=DATEDIF(B2, Today(), "D")
If you're in control of the string, you could also use a 'Raw' string type:
>>> string = r"abcd\n"
>>> print(string)
abcd\n
You can do a port redirect. This is what I do for a Silverlight policy server running on a Linux box
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 943 -j REDIRECT --to-port 1300
Please be advised:
JSONP supports only the GET request method.
*Send request by firefox:*
$.ajax({
type: 'POST',//<<===
contentType: 'application/json',
url: url,
dataType: "json"//<<=============
...
});
Above request send by OPTIONS(while ==>type: 'POST')!!!!
$.ajax({
type: 'POST',//<<===
contentType: 'application/json',
url: url,
dataType: "jsonp"//<<==============
...
});
But above request send by GET(while ==>type: 'POST')!!!!
When you are in "cross-domain communication" , pay attention and be careful.
/*Fully Opaque*/
.class-name {
opacity:1.0;
}
/*Translucent*/
.class-name {
opacity:0.5;
}
/*Transparent*/
.class-name {
opacity:0;
}
/*or you can use a transparent rgba value like this*/
.class-name{
background-color: rgba(255, 242, 0, 0.7);
}
/*Note - Opacity value can be anything between 0 to 1;
Eg(0.1,0.8)etc */
Both proposed possibilities (std::swap
and std::iter_swap
) work, they just have a slightly different syntax.
Let's swap a vector's first and second element, v[0]
and v[1]
.
We can swap based on the objects contents:
std::swap(v[0],v[1]);
Or swap based on the underlying iterator:
std::iter_swap(v.begin(),v.begin()+1);
Try it:
int main() {
int arr[] = {1,2,3,4,5,6,7,8,9};
std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
// put one of the above swap lines here
// ..
for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
std::cout << *i << " ";
std::cout << std::endl;
}
Both times you get the first two elements swapped:
2 1 3 4 5 6 7 8 9
One way that also works is putting it this way in the first line of the your target:
your-target: $(eval SHELL:=/bin/bash)
@echo "here shell is $$0"
Use the following. It works in Firefox and Internet Explorer.
<object id="MediaPlayer1" width="690" height="500" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"
codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"
standby="Loading Microsoft® Windows® Media Player components..." type="application/x-oleobject"
>
<param name="FileName" value='<%= GetSource() %>' />
<param name="AutoStart" value="True" />
<param name="DefaultFrame" value="mainFrame" />
<param name="ShowStatusBar" value="0" />
<param name="ShowPositionControls" value="0" />
<param name="showcontrols" value="0" />
<param name="ShowAudioControls" value="0" />
<param name="ShowTracker" value="0" />
<param name="EnablePositionControls" value="0" />
<!-- BEGIN PLUG-IN HTML FOR FIREFOX-->
<embed type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"
src='<%= GetSource() %>' align="middle" width="600" height="500" defaultframe="rightFrame"
id="MediaPlayer2" />
And in JavaScript,
function playVideo() {
try{
if(-1 != navigator.userAgent.indexOf("MSIE"))
{
var obj = document.getElementById("MediaPlayer1");
obj.Play();
}
else
{
var player = document.getElementById("MediaPlayer2");
player.controls.play();
}
}
catch(error) {
alert(error)
}
}
You mean you want to do "aabbab".toCharArray(); ? Which will return an array of chars. Or do you actually want the resulting array to contain single character string objects?
Use the Nix package manager!
Install Nix, and then do nix-env -iA nixpkgs.watch
and it should be available for use after the completing the install instructions (including sourcing . "$HOME/.nix-profile/etc/profile.d/nix.sh"
in your shell).
I believe this is a Jetty issue. I have not seen any browsers close WebSocket connections due to inactivity nor have I encountered other WebSocket servers that timeout WebSocket connections.
Jetty is (was) primarily focused on building HTTP based application servlets. In that context, HTTP connections need to be cleaned up pretty aggressively and HTTP was not designed for long-lived connections so having a short default timeout is reasonable.
I've not seen the precise problem you described (closing even with activity) but I do see WebSocket connections closed after 30 second of inactivity. It's possible that in older versions of Jetty or in the current version for some other reason, the timer is not reset by WebSocket activity. I get around this by using the setMaxIdleTime method on my BlockingChannelConnector object to set the timeout value to Integer MAX_VALUE.
Do you have installed the android plugin ?
Your project must be of the android type.
new table inherits only "not null" constraint and no other constraint. Thus you can alter the table after creating it with "create table as" command or you can define all constraint that you need by following the
create table t1 (id number default 1 not null);
insert into t1 (id) values (2);
create table t2 as select * from t1;
This will create table t2 with not null constraint. But for some other constraint except "not null" you should use the following syntax
create table t1 (id number default 1 unique);
insert into t1 (id) values (2);
create table t2 (id default 1 unique)
as select * from t1;
A recursive solution to the problem
const findMinMax = (arr, max, min, i) => arr.length === i ? {_x000D_
min,_x000D_
max_x000D_
} :_x000D_
findMinMax(_x000D_
arr,_x000D_
arr[i] > max ? arr[i] : max,_x000D_
arr[i] < min ? arr[i] : min,_x000D_
++i)_x000D_
_x000D_
const arr = [5, 34, 2, 1, 6, 7, 9, 3];_x000D_
const max = findMinMax(arr, arr[0], arr[1], 0)_x000D_
console.log(max);
_x000D_
Cents? If you're calculationg money values you really shouldn't use float values. Money is actually countable values. The cents or pennys etc. could be considered the two (or whatever) least significant digits of an integer. You could store, and calculate money values as integers and divide by 100 (e.g. place dot or comma two before the two last digits). Using float's can lead to strange rounding errors...
Anyway, if your epsilon is supposed to define the accuracy, it looks a bit too small (too accurate)...
if (!$_GET) echo "empty";
why do you need such a checking?
lol
you guys too direct-minded.
don't take as offense but sometimes not-minded at all
$_GET is very special variable, not like others.
it is supposed to be always set. no need to treat it as other variables.
when $_GET is not set and it's expected - it is emergency case and that's what "Undefined variable" notice invented for
I don't know why
cfg_name_unique NOT LIKE '%categories%'
still returns those two values, but maybe exclude them explicit:
SELECT *
FROM developer_configurations_cms
WHERE developer_configurations_cms.cat_id = '1'
AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
AND developer_configurations_cms.cfg_name_unique NOT LIKE '%categories%'
AND developer_configurations_cms.cfg_name_unique NOT IN ('categories_posts', 'categories_news')
One of the way to enable cross domain request on local chrome browser :
Now UI and API running on different ports will be able to work together. I hope this helps.
If you are looking for an example of Cross-domain request . I'll put it in fragments for you to get enough idea.
Angular Client
user.service.ts to call the SpringWebservice.
/** POST: Validates a user for login from Spring webservice */
loginUrl = 'http://localhost:8091/SpringWebService/login'; // URL to web api
validUser (user: User): Observable<User> {
return this.http.post<User>(this.loginUrl, user, httpOptions)
.pipe(
catchError(this.handleError('Login User', user))
);
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'my-auth-token'
})
};
login.component.html: to accept the user Name and pwd.
<form (ngSubmit)="onSubmit(loginForm)" #loginForm="ngForm">
<!-- //ngModel is a must for each form-control -->
<!-- 1st group -->
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required name="name" ngModel #name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Name is required
</div>
</div>
<!-- 2nd group -->
<div class="form-group">
<label for="pwd">Password</label>
<input type="text" class="form-control" id="pwd"
name="pwd" #pwd required ngModel>
</div>
<button type="submit" class="btn btn-success" [disabled]="!loginForm.valid">Submit</button>
</form>
login.component.ts: calls and subscribes validUser method of user.service.
userModel : User;
onSubmit(loginForm : NgForm) {
this.submitted = true;
console.log("User : "+loginForm.value.name + " Valid :"+loginForm.valid)
this.userModel.loggedIn= false;
this.userModel=new
User(loginForm.value.name.trim(),loginForm.value.pwd.trim())
// Passing the userModel to Service method to invoke WebAPI
this.userService.validUser(this.userModel).subscribe(user=>
{
if(user.loggedIn == false){
console.log("Invalid User/PWD");
}
else{
this.userService.changeUser(this.userModel);
this.router.navigate(['/home']);
}
}
);
user.ts: model.
export class User {
constructor(
public name : String,
public pwd : String,
public email ?: String, //optional
public mobile ? : number,//""
public loggedIn : boolean = false
){ }
}
Spring Webservice.
package com.rest;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
// This annotation opens door for cross-domain(Cross-origin resource sharing (CORS)) from any host
@CrossOrigin(origins="*")
public class MainController {
@RequestMapping(value="/login", method=RequestMethod.POST)
public User validUser(@RequestBody User user){
BaseResponse response = new BaseResponse();
if(user.getName().equalsIgnoreCase("shaz") && user.getPwd().equals("pwd")){
user.setLoggedIn(true);
}
else{
user.setLoggedIn(false);
}
return user;
}
}
Now when you pass name as "shaz" and pwd as "pwd" in the form and hit submit,it gets validated from the SpringWebService and the loggedIn flag is set to true and the user entity is returned in response. Based on the loggedIn status from response,the user is redirected to home page or an error is thrown.
Login Page and Network Details
Note: I have not shared the complete setup and code
Refer this: https://shahbaazdesk.wordpress.com/2018/04/03/angular5-with-spring-webservice/
Your module and your class AthleteList
have the same name. The line
import AthleteList
imports the module and creates a name AthleteList
in your current scope that points to the module object. If you want to access the actual class, use
AthleteList.AthleteList
In particular, in the line
return(AthleteList(templ.pop(0), templ.pop(0), templ))
you are actually accessing the module object and not the class. Try
return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))
Nikita's point is an excellent one: don't confuse mature with bad. XML hasn't changed much.
JDOM would be another alternative to DOM4J.
Everyone else has already given you the reason you're getting an error, but here's the best way to do what you want to do:
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
I have to quote Jon (the master of c#) Skeet:
Well, the easiest way would be to open a file stream and then use:
byte[] data = memoryStream.ToArray(); fileStream.Write(data, 0, data.Length);
That's relatively inefficient though, as it involves copying the buffer. It's fine for small streams, but for huge amounts of data you should consider using:
fileStream.Write(memoryStream.GetBuffer(), 0, memoryStream.Position);
check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.
I want to initialize every single element of the array to some initial value. So if I have an array Dim myArray(300) As Integer of 300 integers, for example, all 300 elements would hold the same initial value (say, the number 13).
Can anyone explain how to do this, without looping? I'd like to do it in one statement if possible.
What do I win?
Sub SuperTest()
Dim myArray
myArray = Application.Transpose([index(Row(1:300),)-index(Row(1:300),)+13])
End Sub
Change your gradle version in project setting: If you are using mac,click File->Project structure,then change gradle version,here:
And check your build.gradle of project,change dependency of gradle,like this:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
}
}
just a matter of taste but if you prefer accessing the variable or function directly like this:
<div id="playlist-icon" back-img="playlist.icon">
instead of interpolating like this:
<div id="playlist-icon" back-img="{{playlist.icon}}">
then you can define the directive a bit differently with scope.$watch
which will do $parse
on the
attribute
angular.module('myApp', [])
.directive('bgImage', function(){
return function(scope, element, attrs) {
scope.$watch(attrs.bgImage, function(value) {
element.css({
'background-image': 'url(' + value +')',
'background-size' : 'cover'
});
});
};
})
there is more background on this here: AngularJS : Difference between the $observe and $watch methods
Having the problem that the new TabLayout uses the indicator color from the value colorAccent
, I decided to dig into the android.support.design.widget.TabLayout
implementation, finding that there are no public methods to customize this. However I found this style specification of the TabLayout:
<style name="Base.Widget.Design.TabLayout" parent="android:Widget">
<item name="tabMaxWidth">@dimen/tab_max_width</item>
<item name="tabIndicatorColor">?attr/colorAccent</item>
<item name="tabIndicatorHeight">2dp</item>
<item name="tabPaddingStart">12dp</item>
<item name="tabPaddingEnd">12dp</item>
<item name="tabBackground">?attr/selectableItemBackground</item>
<item name="tabTextAppearance">@style/TextAppearance.Design.Tab</item>
<item name="tabSelectedTextColor">?android:textColorPrimary</item>
</style>
Having this style specification, now we can customize the TabLayout like this:
<android.support.design.widget.TabLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@id/pages_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabIndicatorColor="@android:color/white"
app:tabIndicatorHeight="4dp"/>
And problem solved, both the tab indicator color and height can be changed from their default values.
when reimporting your keys from the old keyring, you need to specify the command:
gpg --allow-secret-key-import --import <keyring>
otherwise it will only import the public keys, not the private keys.
Note also that vertical-align:top;
is often necessary for correct table cell appearance.
in my case adding clipToPadding
solved the problem.
<android.support.v4.view.ViewPager
...
android:clipToPadding="false"
...
/>
Cheers!
To grant permissions to all of the existing tables in the schema use:
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA <schema> TO <role>
To specify default permissions that will be applied to future tables use:
ALTER DEFAULT PRIVILEGES IN SCHEMA <schema>
GRANT <privileges> ON TABLES TO <role>;
e.g.
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO admin;
If you use SERIAL
or BIGSERIAL
columns then you will probably want to do the same for SEQUENCES
, or else your INSERT
will fail (Postgres 10's IDENTITY
doesn't suffer from that problem, and is recommended over the SERIAL
types), i.e.
ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> GRANT ALL ON SEQUENCES TO <role>;
See also my answer to PostgreSQL Permissions for Web App for more details and a reusable script.
Ref:
No, it is not RESTful. The only reason why you should be putting a verb (force_delete
) into the URI is if you would need to overload GET/POST methods in an environment where PUT/DELETE methods are not available. Judging from your use of the DELETE method, this is not the case.
HTTP error code 409/Conflict
should be used for situations where there is a conflict which prevents the RESTful service to perform the operation, but there is still a chance that the user might be able to resolve the conflict himself. A pre-deletion confirmation (where there are no real conflicts which would prevent deletion) is not a conflict per se, as nothing prevents the API from performing the requested operation.
As Alex said (I don't know who downvoted him, he is correct), this should be handled in the UI, because a RESTful service as such just processes requests and should be therefore stateless (i.e. it must not rely on confirmations by holding any server-side information about of a request).
Two examples how to do this in UI would be to:
(*) Please note that HTML versions prior to 5 do not support PUT and DELETE HTTP methods natively, however most modern browsers can do these two methods via AJAX calls. See this thread for details about cross-browser support.
Update (based on additional investigation and discussions):
The scenario where the service would require the force_delete=true
flag to be present violates the uniform interface as defined in Roy Fielding's dissertation. Also, as per HTTP RFC, the DELETE method may be overridden on the origin server (client), implying that this is not done on the target server (service).
So once the service receives a DELETE request, it should process it without needing any additional confirmation (regardless if the service actually performs the operation).
The SQL dialect converts the HQL query which we write in our java or any other object oriented program to the specific database SQL.
For example in the java suppose I write List employees = session.createQuery("FROM Employee").list();
but when my dialect is
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
The HQL ("FROM Employee") gets converted to "SELECT * FROM EMPLOYEE" before hitting the MySQL database
An example:
log4j.rootLogger=ERROR, logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false
log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
netifaces is a good module to use for getting the mac address (and other addresses). It's crossplatform and makes a bit more sense than using socket or uuid.
>>> import netifaces
>>> netifaces.interfaces()
['lo', 'eth0', 'tun2']
>>> netifaces.ifaddresses('eth0')[netifaces.AF_LINK]
[{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]
Now you must have API key. You can generate that in google developer console. Here is LINK to the explanation.
Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings;
confCollection["YourKey"].Value = "YourNewKey";
configManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name);
Make sure to check the phpMyAdmin config file as well! On newer WAMP applications it is set to 128Mb by default. Even if you update php.ini to desired values you still need to update the phpmyadmin.conf!
Sample path: C:\wamp64\alias\phpmyadmin.conf
Or edit through your WAMP icon by: ->Apache -> Alias directories -> phpMyAdmin
While this doesn't avoid the problem of parentheses, for the sake of people getting here via Google, it should be mentioned that newer syntax exists (as of C# 7) to make the rest of your code a little cleaner:
if (!(DocumentPart is IContainer container)) { return; }
foreach(DocumentPart child in container.Children) {
...
This avoids the double-cast, the null-check, and having a variable available in scopes where it could be null.
Elaborating a bit more on Taylor Gautier's reply (sorry, I dont have enough reputation to add a comment), I'd reply to Dean Richardson on how to do what he wanted, without any additional JS code. Pure CSS.
You would replace his .btn
with the following:
<a class="btn showdetails" data-toggle="collapse" data-target="#viewdetails"></a>
And add a small CSS for when the content is displayed:
.in.collapse+a.btn.showdetails:before {
content:'Hide details «';
}
.collapse+a.btn.showdetails:before {
content:'Show details »';
}
Much easier aproach. Consider a task:
provision:
ansible-playbook -vvvv \
-i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory \
--private-key=.vagrant/machines/default/virtualbox/private_key \
--start-at-task="$(AT)" \
-u vagrant playbook.yml
Now when I want to call it I just run something like:
AT="build assets" make provision
or just:
make provision
in this case AT
is an empty string
You need to use MM
as mm
stands for minutes.
There are two ways of producing month pattern.
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01
Full coding snippet:
String startDate="01-Feb-2013"; // Input String
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
System.out.println(sqlStartDate); // Outputs : 2013-02-01
I ran into this issue in a web api project.
Api project was using a nuget package of a library with version 3. And one of the referenced assemblies say X was using older version of the same nuget package with version 2.
Whenever referenced assembly is built or any other project referencing X is rebuilt, api project's assemblies gets updated with lower version. And got this assembly reference error.
Rebuild works but in my case I wanted a long term solution.
I made the assemblies reference same version of nuget package.
public class wordCount
{
public static void main(String ar[]) throws Exception
{
System.out.println("Simple Java Word Count Program");
int wordCount = 1,count=1;
BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
String str2 = "", str1 = "";
while ((str1 = br.readLine()) != null) {
str2 += str1;
}
for (int i = 0; i < str2.length(); i++)
{
if (str2.charAt(i) == ' ' && str2.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " +(wordCount));
}
}
What you are doing right now is you are adding .
on the string and not concatenating. It should be,
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
or simply
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '$email'");
Use sprintf.
int sprintf ( char * str, const char * format, ... );
Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.
The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).
A terminating null character is automatically appended after the content.
After the format parameter, the function expects at least as many additional arguments as needed for format.
str
Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.
format
C string that contains a format string that follows the same specifications as format in printf (see printf for details).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");