The "problem" with the media library in wordpress is always interesting. Check the following plugin to solve this: WordPress Real Media Library. WP RML creates a virtual folder structure based on an own taxonomy.
It allows you to organize your wordpress media library in a nice way with folders. It is easy to use, just drag&drop your files and move it to a specific folder. Filter when inserting media or create a gallery from a folder.
Turn your WordPress media library to the next level with folders / categories. Get organized with thousands of images.
RML (Real Media Library) is one of the most wanted media wordpress plugins. It is easy to use and it allows you to organize your thousands of images in folders. It is similar to wordpress categories like in the posts.
Use your mouse (or touch) to drag and drop your files. Create, rename, delete or reorder your folders If you want to select a image from the “Select a image”-dialog (e. g. featured image) you can filter when inserting media. Just install this plugin and it works fine with all your image and media files. It also supports multisite.
If you buy, you get: Forever FREE updates and high quality and fast support.
From the product description i can quote. If you want to try the plugin, there is also a demo on the plugin page.
A long time ago I started to open this thread and now there is a usable extension plugin for Real Media Library which allows you to physically manage your uploads folder.
Check out this plugin: https://wordpress.org/plugins/physical-custom-upload-folder/
Do you know the wp-content/uploads folder? There, the files are stored in year/month based folders. This can be a very complicated and mass process, especially when you are working with a FTP client like FileZilla.
Moving already uploaded files: This plugin does not allow to move the files physically when you move a file in the Real Media Library because WordPress uses the URL's in different places. It is very hard to maintain such a process. So this only works for new uploads.
(Please read on if you are developer) I as developer thought about a solution about this. Does it make sense to organize the uploads on server, too? Yes, i think. Many people ask to organize it physically. I think also that the process of moving files on server and updating the image references is very hard to develop. There are many plugins out now, which are saving the URLs in their own-created database-tables.
Please check this thread where i explained the problem: https://wordpress.stackexchange.com/questions/226675/physical-organization-of-wordpress-media-library-real-media-library-plugin
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
Try the Content-Disposition
header
Content-Disposition: attachment; filename=<file name.ext>
val drawable = ContextCompat.getDrawable(context, R.drawable.my_icon)
// or resources.getDrawable(R.drawable.my_icon, theme)
val sizePx = 25
drawable?.setBounds(0, 0, sizePx, sizePx)
// (left, top, right, bottom)
my_button.setCompoundDrawables(drawable, null, null, null)
I suggest creating an extension function on TextView (Button extends it) for easy reuse.
button.leftDrawable(R.drawable.my_icon, 25)
// Button extends TextView
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = context.resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
Use below function
// Enable error reporting
ini_set('display_errors', 1);
//Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//error_reporting(E_ALL & ~E_NOTICE);
// Tell php where your custom php error log is
ini_set('error_log', 'php_error.log');
$dateTime=date("Y-m-d H:i:s");
$ip= $_SERVER['REMOTE_ADDR'];
$errorString="Error occured on time $dateTime by ip $ip";
$php_error_msg.=$errorString;
// Append the error message to the php-error log
//error_log($php_error_msg);
error_log("A custom error has been triggered",1,"email_address","From: email_address");
Above function will create a log in file php_error with proper description and email will be sent.
Here's typescript version. works on "react-router-dom": "^4.3.1"
export const AppRouter: React.StatelessComponent = () => {
return (
<BrowserRouter>
<Switch>
<Route exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />} />
<Route path="/" exact component={App} />
</Switch>
</BrowserRouter>
);
};
and component
export class ProblemPage extends React.Component<ProblemRouteTokens> {
public render(): JSX.Element {
return <div>{this.props.problemId}</div>;
}
}
where ProblemRouteTokens
export interface ProblemRouteTokens { problemId: string; }
Point 1: Add require()
function calling line of code only in the app.js
file or main.js
file.
Point 2: Make sure the required package is installed by checking the pacakage.json
file. If not updated, run "npm i".
Try invoking your command with Invoke-Expression
:
Invoke-Expression $cmd1
Here is a working example on my machine:
$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd
iex
is an alias for Invoke-Expression
so you could do:
iex $cmd1
For a full list :
Visit https://ss64.com/ps/ for more Powershell
stuff.
Good Luck...
I had a very related issue but for higher Java versions:
$ ./gradlew clean assemble
... <other normal Gradle output>
Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'.
I noticed that the task succeeded when running using InteliJ. Adding a file (same level as build.gradle) called .java-version
solved my issue:
# .java-version
11.0.3
VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.
I've made a file in my snippets directory called styles.js
, and I think it might help anybody who wants to import a single file.
It's a small modification to the styles.js
file of color.js and has helped me a lot.
Here's the file's contents:
// Original: https://github.com/Marak/colors.js/blob/master/lib/styles.js
const styleCodes = {
// Reset all styles.
reset: [0, 0],
// Text styles.
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
// Foregound classic colours.
fgBlack: [30, 39],
fgRed: [31, 39],
fgGreen: [32, 39],
fgYellow: [33, 39],
fgBlue: [34, 39],
fgMagenta: [35, 39],
fgCyan: [36, 39],
fgWhite: [37, 39],
fgGray: [90, 39],
// Foreground bright colours.
fgBrightRed: [91, 39],
fgBrightGreen: [92, 39],
fgBrightYellow: [93, 39],
fgBrightBlue: [94, 39],
fgBrightMagenta: [95, 39],
fgBrightCyan: [96, 39],
fgBrightWhite: [97, 39],
// Background basic colours.
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
bgGray: [100, 49],
bgGrey: [100, 49],
// Background bright colours.
bgBrightRed: [101, 49],
bgBrightGreen: [102, 49],
bgBrightYellow: [103, 49],
bgBrightBlue: [104, 49],
bgBrightMagenta: [105, 49],
bgBrightCyan: [106, 49],
bgBrightWhite: [107, 49],
};
// This object will contain the string representation for all style codes.
const styles = {};
// Loop over all the style codes and assign them to the `styles` object.
//
// The a `styleCode` in the `styleCodes` object consists of two numbers:
// Index 0: The opening style code (In HTML this can be the opening <b> tag).
// Index 1: The closing style code (In HTML this can be the closing </b> tag).
for (let styleCode of Object.keys(styleCodes)) {
styles[styleCode] = {
open: `\x1B[${styleCodes[styleCode][0]}m`,
close: `\x1B[${styleCodes[styleCode][1]}m`,
};
}
module.exports = styles;
It's actually quite simple to use.
const styles = require("/path/to/styles.js");
// Let's say we've got an error:
const errorOpen = styles.bold.open + styles.bgRed.open + styles.fgWhite.open;
const errorClose = styles.reset.close; // Close everything
console.log(errorOpen, "ERROR", errorClose, ": Missing semicolon at line 9.");
In drawable I use this xml code to define the border and background:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#D8FDFB" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="7dp" />
<corners android:radius="4dp" />
<solid android:color="#f0600000"/>
</shape>
Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed; for a reference type --> the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.
Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed. If a field is a reference type --> a new copy of the referred object is performed. The classes to be cloned must be flagged as [Serializable].
There are two parts to that answer (I wrote it). One part is easy to quantify, the other is more empirical.
This is the easy to quantify part. Appendix F of the current CUDA programming guide lists a number of hard limits which limit how many threads per block a kernel launch can have. If you exceed any of these, your kernel will never run. They can be roughly summarized as:
If you stay within those limits, any kernel you can successfully compile will launch without error.
This is the empirical part. The number of threads per block you choose within the hardware constraints outlined above can and does effect the performance of code running on the hardware. How each code behaves will be different and the only real way to quantify it is by careful benchmarking and profiling. But again, very roughly summarized:
The second point is a huge topic which I doubt anyone is going to try and cover it in a single StackOverflow answer. There are people writing PhD theses around the quantitative analysis of aspects of the problem (see this presentation by Vasily Volkov from UC Berkley and this paper by Henry Wong from the University of Toronto for examples of how complex the question really is).
At the entry level, you should mostly be aware that the block size you choose (within the range of legal block sizes defined by the constraints above) can and does have a impact on how fast your code will run, but it depends on the hardware you have and the code you are running. By benchmarking, you will probably find that most non-trivial code has a "sweet spot" in the 128-512 threads per block range, but it will require some analysis on your part to find where that is. The good news is that because you are working in multiples of the warp size, the search space is very finite and the best configuration for a given piece of code relatively easy to find.
The problem I see here is that "sum" is an aggregate function.
first, you need to fix the query itself.
Select sum(c_counts + f_counts) total, [column to group sums by]
from table
group by [column to group sums by]
then, you can sort it:
Select *
from (query above) a
order by total
EDIT: But see post by Virat. Perhaps what you want is not the sum of your total fields over a group, but just the sum of those fields for each record. In that case, Virat has the right solution.
Float to string - String.valueOf()
float amount=100.00f;
String strAmount=String.valueOf(amount);
// or Float.toString(float)
String to Float - Float.parseFloat()
String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or Float.valueOf(string)
I had Xamarin installed and tried to use Unity. Basically in any case you have to kill any application that might be talking to your device through ADB
I write out a rule in web.config after $locationProvider.html5Mode(true)
is set in app.js
.
Hope, helps someone out.
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
In my index.html I added this to <head>
<base href="/">
Don't forget to install IIS URL Rewrite on server.
Also if you use Web API and IIS, this will work if your API is at www.yourdomain.com/api
because of the third input (third line of condition).
you could use the Thread.Sleep() function
Thread.sleep(4000);
myfunction();
Your function will execute after 4 seconds. However this might pause the entire program...
I'm going to expand your question a bit and also include the compile function.
compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link'
attribute is ignored if the 'compile'
attribute is defined.)
link function - normally use for registering listener callbacks (i.e., $watch
expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>
, the link function is executed after the <li>
template (tElement) has been cloned (into an iElement) for that particular <li>
element. A $watch
allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.
controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.
For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this
(rather than on $scope
), please see 'this' vs $scope in AngularJS controllers.
In general, you can put methods, $watches
, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.
If you have npm version 5 or above, try this first:
$ sudo npm cache verify
Otherwise:
$ sudo npm cache clean
My node and npm versions are:
$ node -v
v0.10.0
$ npm -v
1.2.14
If you're working from some network that requires you to use a proxy in your browser to connect to the internet (likely an office building), that might be it. I had the same issue and adding the proxy configs to the network settings solved it.
If you don't know the proxy url and port, talk to your network admin.
It's more of an aesthetics thing, much easier to read code where you explicitly know why the loop will stop right in the declaration of the loop.
This took me way too long to track down. Make sure you minisafe your controller within your directive.
.directive('my_directive', ['injected_item', function (injected_item){
return {
controller: ['DO_IT_HERE_TOO', function(DO_IT_HERE_TOO){
}]
}
}
Hope that helps
If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES
automagically:
#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = {
1,
2,
3,
4 };
Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.
I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.
So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.
Delete all the shutdown simulators:
xcrun simctl list | grep -w "Shutdown" | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete uuid
If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.
I had tried all of the solutions on this page: refresh project, rebuild, all projects clean, restart Eclipse, re-import (even) the projects, rebuild maven and refresh. Nothing worked. What did work was copying the class to a new name which runs fine -- bizarre but true.
After putting up with this for some time, I just fixed it by:
Run
menuRun Configurations
Run Configuration
by pressing delete or clicking the red X.Something must have been screwed up with the cached run configuration.
Are you asking about the Collections class versus the classes which implement the Collection interface?
If so, the Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.
The Collection interface defines methods common to structures which hold other objects. List and Set are subinterfaces of Collection, and ArrayList and HashSet are examples of concrete collections.
I was facing with this problem some time ago and I found java.util.LinkedList
is best for my case. It has several methods, with different namings, but they're doing what is needed:
push() -> LinkedList.addLast(); // Or just LinkedList.add();
pop() -> LinkedList.pollLast();
shift() -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();
Here you have the angularjs http request to the API that any client will have to do. Just adapt the WS url and params (if you have) to your case. It's a mixture between Naoe's answer and this one:
$http({
url: '/path/to/your/API',
method: 'POST',
params: {},
headers: {
'Content-type': 'application/pdf',
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
// TODO when WS success
var file = new Blob([data], {
type: 'application/csv'
});
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = 'yourfilename.pdf';
document.body.appendChild(a); //create the link "a"
a.click(); //click the link "a"
document.body.removeChild(a); //remove the link "a"
}).error(function (data, status, headers, config) {
//TODO when WS error
});
Explanation of the code:
/path/to/your/API
.<a>
.<a>
tag, using the JS click()
function<a>
tag, after its click.Here is the simple arraylist example for insertion at specific index
ArrayList<Integer> str=new ArrayList<Integer>();
str.add(0);
str.add(1);
str.add(2);
str.add(3);
//Result = [0, 1, 2, 3]
str.add(1, 11);
str.add(2, 12);
//Result = [0, 11, 12, 1, 2, 3]
$('li[rel=7]').siblings().andSelf();
// or:
$('li[rel=7]').parent().children();
Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:
var rels = [];
$('ul').each(function() {
var localRels = [];
$(this).find('li').each(function(){
localRels.push( $(this).attr('rel') );
});
rels.push(localRels);
});
It appears that you are using the default route which is defined as this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The key part of that route is the {id}
piece. If you look at your action method, your parameter is k
instead of id
. You need to change your action method to this so that it matches the route parameter:
// change int k to int id
public ActionResult DetailsData(int id)
If you wanted to leave your parameter as k, then you would change the URL to be:
http://localhost:7317/Employee/DetailsData?k=4
You also appear to have a problem with your connection string. In your web.config, you need to change your connection string to this (provided by haim770 in another answer that he deleted):
<connectionStrings>
<add name="EmployeeContext"
connectionString="Server=.;Database=mytry;integrated security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
public partial class result : System.Web.UI.Page
{
static DataTable table1 = new DataTable("Shashank");
static DataSet set = new DataSet("office");
protected void Page_Load(object sender, EventArgs e)
{
lblEmployeeNumber.Text = HttpContext.Current.Request.Form["txtEmployeeNumber"];
lblFirstName.Text = Request.Form["txtFirstName"];
lblLastName.Text = Request.Form["txtLastName"];
lblTitle.Text = Request.Form["txtTitle"];
Int32 Rcount = Convert.ToInt32(table1.Rows.Count);
if (Rcount == 0)
{
table1.Columns.Add("ID");
table1.Columns.Add("FName");
table1.Columns.Add("LName");
table1.Columns.Add("Title");
table1.Rows.Add(lblEmployeeNumber.Text, lblFirstName.Text, lblLastName.Text, lblTitle.Text);
set.Tables.Add(table1);
}
else
{
if (lblEmployeeNumber.Text != "")
{
DataRow dr = table1.NewRow();
dr["ID"] = lblEmployeeNumber.Text;
dr["FName"] = lblFirstName.Text;
dr["LName"] = lblLastName.Text;
dr["Title"] = lblTitle.Text;
table1.Rows.Add(dr);
}
}
gvrEmp.DataSource = set;
gvrEmp.DataBind();
}
}
The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html
private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
public int compare(String str1, String str2) {
return ComparisonChain.start().
compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
compare(str1,str2).
result();
}
};
Collections.sort(list, stringAlphabeticalComparator);
The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:
"AA","Aa","aa","Development","development"
You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package
You are testing against the string minus the last character:
>>> '"xxx"'[:-1]
'"xxx'
Note how the last character, the "
, is not part of the output of the slice.
I think you wanted just to test against the last character; use [-1:]
to slice for just the last element.
However, there is no need to slice here; just use str.startswith()
and str.endswith()
directly.
I made a small adaptation in Nicko's solution so that it is not necessary to use the Apache Commons BeanUtils library and replace it with the solution already available in spring, for those using it as I can be simpler:
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {
private String firstFieldName;
private String secondFieldName;
@Override
public void initialize(final FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
@Override
public boolean isValid(final Object object, final ConstraintValidatorContext context) {
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
final Object firstObj = beanWrapper.getPropertyValue(firstFieldName);
final Object secondObj = beanWrapper.getPropertyValue(secondFieldName);
boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
if (!isValid) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addPropertyNode(firstFieldName)
.addConstraintViolation();
}
return isValid;
}
}
All have already stated (recommended) using paramiko and I am just sharing a python code (API one may say) that will allow you to execute multiple commands in one go.
to execute commands on different node use : Commands().run_cmd(host_ip, list_of_commands)
You will see one TODO, which I have kept to stop the execution if any of the commands fails to execute, I don't know how to do it. please share your knowledge
#!/usr/bin/python
import os
import sys
import select
import paramiko
import time
class Commands:
def __init__(self, retry_time=0):
self.retry_time = retry_time
pass
def run_cmd(self, host_ip, cmd_list):
i = 0
while True:
# print("Trying to connect to %s (%i/%i)" % (self.host, i, self.retry_time))
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host_ip)
break
except paramiko.AuthenticationException:
print("Authentication failed when connecting to %s" % host_ip)
sys.exit(1)
except:
print("Could not SSH to %s, waiting for it to start" % host_ip)
i += 1
time.sleep(2)
# If we could not connect within time limit
if i >= self.retry_time:
print("Could not connect to %s. Giving up" % host_ip)
sys.exit(1)
# After connection is successful
# Send the command
for command in cmd_list:
# print command
print "> " + command
# execute commands
stdin, stdout, stderr = ssh.exec_command(command)
# TODO() : if an error is thrown, stop further rules and revert back changes
# Wait for the command to terminate
while not stdout.channel.exit_status_ready():
# Only print data if there is data to read in the channel
if stdout.channel.recv_ready():
rl, wl, xl = select.select([ stdout.channel ], [ ], [ ], 0.0)
if len(rl) > 0:
tmp = stdout.channel.recv(1024)
output = tmp.decode()
print output
# Close SSH connection
ssh.close()
return
def main(args=None):
if args is None:
print "arguments expected"
else:
# args = {'<ip_address>', <list_of_commands>}
mytest = Commands()
mytest.run_cmd(host_ip=args[0], cmd_list=args[1])
return
if __name__ == "__main__":
main(sys.argv[1:])
Thank you!
In case it is not working in your default region, try providing a region close to you. This worked for me:
PS C:\Users\shrig> aws configure
AWS Access Key ID [****************C]:**strong text**
AWS Secret Access Key [****************WD]:
Default region name [us-east1]: ap-south-1
Default output format [text]:
This can also happen if data model is out of date.
Hopefully this will save someone else frustration :)
Everyone seems to want to tell you what you should be doing rather than just answering the question.
The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.
From PEP 328:
Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.
Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.
Try this: (For Preview)
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<body>
<form id="form1" runat="server">
<input type="file" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
Working Demo here>
Just write require with path inside the src of image. it will work. like:
<img alt="Clock" src={require('../assets/images/search_icon.svg')}/>
I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:
It's a real short VB.Net app: I can post code if any one is interested.
Java applets do create a security risk, hence are disabled in most modern browsers. You have to lower the security to run it. There is a guide by Oracle for that.
Add a static method inside your functional interface
package example;
interface Action<T, U> {
U execute(T t);
static Action<Void,Void> invoke(Runnable runnable){
return (v) -> {
runnable.run();
return null;
};
}
}
public class Lambda {
public static void main(String[] args) {
Action<Void, Void> a = Action.invoke(() -> System.out.println("Do nothing!"));
Void t = null;
a.execute(t);
}
}
Output
Do nothing!
Little known: the GO sql statement can take an integer for the number of times to repeat previous command.
So if you:
ALTER DATABASE [DATABASENAME] SET SINGLE_USER
GO
Then:
USE [DATABASENAME]
GO 2000
This will repeat the USE command 2000 times, force deadlock on all other connections, and take ownership of the single connection. (Giving your query window sole access to do as you wish.)
select getdate()
O/P
----
2011-05-25 17:29:44.763
select convert(varchar(30),getdate(),131) >= '12/04/2011 12:00:00 AM'
O/P
---
22/06/1432 5:29:44:763PM
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
If your master branch git log
looks something like following:
commit ac72a4308ba70cc42aace47509a5e
Author: <[email protected]>
Date: Tue Jun 11 10:23:07 2013 +0500
Added algorithms for Cosine-similarity
commit 77df2a40e53136c7a2d58fd847372
Author: <[email protected]>
Date: Tue Jun 11 13:02:14 2013 -0700
Set stage for similar objects
commit 249cf9392da197573a17c8426c282
Author: Ralph <[email protected]>
Date: Thu Jun 13 16:44:12 2013 -0700
Fixed a bug in space world automation
and you want to merge the top two commits just do following easy steps:
git checkout 77df2a40e53136c7a2d58fd847372 -b merged-commits
git cherry-pick -n -x ac72a4308ba70cc42aace47509a5e
. (Resolve conflicts if arise any)git commit --amend
.That's it. You may push this merged version in branch "merged-commits" if you like.
Also, you can discard the back-to-back two commits in your master branch now. Just update your master branch as:
git checkout master
git reset --hard origin/master (CAUTION: This command will remove any local changes to your master branch)
git pull
You are looking for the DateTime.Parse()
method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime
typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact
(MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
I would instead write a helper bash script that runs svn commit
on all the files you need to and none of the ones you don't. This way you have much more control.
For example, with one line, you can commit all files with extension .h
and .cpp
to which you made changes (and which wouldn't cause a conflict):
svn commit -m "" `svn status | grep "^M.*[h|cpp]$" | awk '{print $2}' | tr "\\n" " "`
Change / add extensions to the [h|cpp]
part. Add a log message in between the quotes of -m ""
if needed.
According to fresh Quirksmode the clientX
and clientY
methods are supported in all major browsers.
So, here it goes - the good, working code that works in a scrolling div on a page with scrollbars:
function getCursorPosition(canvas, event) {
var x, y;
canoffset = $(canvas).offset();
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - Math.floor(canoffset.left);
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1;
return [x,y];
}
This also requires jQuery for $(canvas).offset()
.
From the proxy_pass documentation:
A special case is using variables in the proxy_pass statement: The requested URL is not used and you are fully responsible to construct the target URL yourself.
Since you're using $1 in the target, nginx relies on you to tell it exactly what to pass. You can fix this in two ways. First, stripping the beginning of the uri with a proxy_pass is trivial:
location /service/ {
# Note the trailing slash on the proxy_pass.
# It tells nginx to replace /service/ with / when passing the request.
proxy_pass http://apache/;
}
Or if you want to use the regex location, just include the args:
location ~* ^/service/(.*) {
proxy_pass http://apache/$1$is_args$args;
}
This page contains all the cached urls
chrome://cache
Unfortunately to actually see the file you have to select everything on the page and paste it in this tool: http://www.sensefulsolutions.com/2012/01/viewing-chrome-cache-easy-way.html
String upToNCharacters = String.format("%."+ n +"s", str);
Awful if n
is a variable (so you must construct the format string), but pretty clear if a constant:
String upToNCharacters = String.format("%.10s", str);
If your object could contain any key/value pairs, you could declare an interface called keyable
like :
interface keyable {
[key: string]: any
}
then use it as follows :
let countryProviders: keyable[];
or
let countryProviders: Array<keyable>;
Have a look at the white-space
property, used like this:
th {
white-space: nowrap;
}
This will force the contents of <th>
to display on one line.
From linked page, here are the various options for white-space
:
normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.
I know this is an old question but I just want to comment here: To any extent email addresses ARE case sensitive, most users would be "very unwise" to actively use an email address that requires capitals. They would soon stop using the address because they'd be missing a lot of their mail. (Unless they have a specific reason to make things difficult, and they expect mail only from specific senders they know.)
That's because imperfect humans as well as imperfect software exist, (Surprise!) which will assume all email is lowercase, and for this reason these humans and software will send messages using a "lower cased version" of the address regardless of how it was provided to them. If the recipient is unable to receive such messages, it won't be long before they notice they're missing a lot, and switch to a lowercase-only email address, or get their server set up to be case-insensitive.
UsernamePasswordAuthenticationFilter
is only used for/login
, and latter filters are not?
No, UsernamePasswordAuthenticationFilter
extends AbstractAuthenticationProcessingFilter
, and this contains a RequestMatcher
, that means you can define your own processing url, this filter only handle the RequestMatcher
matches the request url, the default processing url is /login
.
Later filters can still handle the request, if the UsernamePasswordAuthenticationFilter
executes chain.doFilter(request, response);
.
More details about core fitlers
Does the form-login namespace element auto-configure these filters?
UsernamePasswordAuthenticationFilter
is created by <form-login>
, these are Standard Filter Aliases and Ordering
Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?
It depends on whether the before fitlers are successful, but FilterSecurityInterceptor
is the last fitler normally.
Does configuring two http elements create two springSecurityFitlerChains?
Yes, every fitlerChain has a RequestMatcher
, if the RequestMatcher
matches the request, the request will be handled by the fitlers in the fitler chain.
The default RequestMatcher
matches all request if you don't config the pattern, or you can config the specific url (<http pattern="/rest/**"
).
If you want to konw more about the fitlers, I think you can check source code in spring security.
doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
For Git Bash for Windows (in ConEmu), the following works for me (for Docker Windows containers):
docker run --rm -it -v `pwd -W`:c:/api microsoft/dotnet:2-runtime
Note the backticks/backquotes around pwd -W
!
With all other variations of PWD I've tried I've received: "Error response from daemon: invalid volume specification: ..."
Update: The above was for Docker Windows containers, for Linux containers use:
docker run --rm -it -v `pwd -W`:/api -p 8080:80 microsoft/aspnetcore:2
I'm against using when others
so I would use (returning an "boolean integer" due to SQL not suppporting booleans)
create or replace function is_number(param in varchar2) return integer
is
ret number;
begin
ret := to_number(param);
return 1; --true
exception
when invalid_number then return 0;
end;
In the SQL call you would use something like
select case when ( is_number(myTable.id)=1 and (myTable.id >'0') )
then 'Is a number greater than 0'
else 'it is not a number or is not greater than 0'
end as valuetype
from table myTable
Here is a function by which you can concatenate multiple number of arrays
function concatNarrays(args) {
args = Array.prototype.slice.call(arguments);
var newArr = args.reduce( function(prev, next) {
return prev.concat(next) ;
});
return newArr;
}
Example -
console.log(concatNarrays([1, 2, 3], [5, 2, 1, 4], [2,8,9]));
will output
[1,2,3,5,2,1,4,2,8,9]
Why not just translate your id to a string? You just need a function that maps a digit between, say, 0 and 61 to a single letter (upper/lower case) or digit. Then apply this to create, say, 4-letter codes, and you've got 14.7 million URLs covered.
im
is "image process name"
example /f /im notepad.exe
is specified to kill image process name (program) notepad.exe
Use the array module. With it you can store collections of the same type efficiently.
>>> import array
>>> import itertools
>>> a = array_of_signed_ints = array.array("i", itertools.repeat(0, 10))
For more information - e.g. different types, look at the documentation of the array module. For up to 1 million entries this should feel pretty snappy. For 10 million entries my local machine thinks for 1.5 seconds.
The second parameter to array.array is a generator, which constructs the defined sequence as it is read. This way, the array module can consume the zeros one-by-one, but the generator only uses constant memory. This generator does not get bigger (memory-wise) if the sequence gets longer. The array will grow of course, but that should be obvious.
You use it just like a list:
>>> a.append(1)
>>> a.extend([1, 2, 3])
>>> a[-4:]
array('i', [1, 1, 2, 3])
>>> len(a)
14
...or simply convert it to a list:
>>> l = list(a)
>>> len(l)
14
Surprisingly
>>> a = [0] * 10000000
is faster at construction than the array method. Go figure! :)
echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk -v var="test" 'BEGIN { FS = "[ \t]+" } ; { print $1 "\t" var "\t" $3 }'
If you'd like to write interesting code that nobody else can ever update, try this:
~--x
I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:
borrowed from: https://gist.github.com/gsakkis/4572159
The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:
# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime
from sqlalchemy.orm import Query
try:
basestring
except NameError:
basestring = str
def render_query(statement, dialect=None):
"""
Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement.
WARNING: This method of escaping is insecure, incomplete, and for debugging
purposes only. Executing SQL statements with inline-rendered user values is
extremely insecure.
Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
"""
if isinstance(statement, Query):
if dialect is None:
dialect = statement.session.bind.dialect
statement = statement.statement
elif dialect is None:
dialect = statement.bind.dialect
class LiteralCompiler(dialect.statement_compiler):
def visit_bindparam(self, bindparam, within_columns_clause=False,
literal_binds=False, **kwargs):
return self.render_literal_value(bindparam.value, bindparam.type)
def render_array_value(self, val, item_type):
if isinstance(val, list):
return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
return self.render_literal_value(val, item_type)
def render_literal_value(self, value, type_):
if isinstance(value, long):
return str(value)
elif isinstance(value, (basestring, date, datetime, timedelta)):
return "'%s'" % str(value).replace("'", "''")
elif isinstance(value, list):
return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
return super(LiteralCompiler, self).render_literal_value(value, type_)
return LiteralCompiler(dialect, statement).process(statement)
Tested to two levels of nested arrays.
Since you already have all the files in a folder, say "Project", you simply have to open Netbeans and go to
File -> Open Project
(or Ctrl + Shift+ O
on Windows) and then from the dialog box navigate to the folder containing the Folder "Project".
You will see in the dialog box of Netbeans a 'Java cup'. Well, that's your project.
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
Look at https://expressjs.com/en/resources/middleware/cors.html You have to use cors.
Install:
$ npm install cors
const cors = require('cors');
app.use(cors());
You have to put this code in your node server.
And for Windows, this does not work
FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec mp3 "%~nG.mp3"
even if I do double those %
.
I would even suggest:
-acodec ***libmp3lame***
also:
FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec libmp3lame "%~nG.mp3"
Adding to above answers, we can create on the fly
df= pd.DataFrame()
list1 = list(range(10))
list2 = list(range(10,20))
df['list1'] = list1
df['list2'] = list2
print(df)
hope it helps !
There is a tiny workaround script on Google Code that worked for me:
http://code.google.com/p/download-data-uri/
It adds a form with the data in it, submits it and then removes the form again. Hacky, but it did the job for me. Requires jQuery.
This thread showed up in Google before the Google Code page and I thought it might be helpful to have the link in here, too.
<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);" placeholder="MobileNumber">
<script>
function checkNumber(key) {
console.log(key);
var inputNumber = document.querySelector("#MobileNumber").value;
if(key.key >= 0 && key.key <= 9) {
inputNumber += key.key;
}
else {
key.preventDefault();
}
}
</script>
var $th = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');
Or a little bit simplified
var $th = $td.closest('table').find('th').eq($td.index());
// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10
For IntelliJ IDEA (Community Edition) 3-way git mergetool configuration in Windows environment (~/.gitconfig
)
Cygwin
[mergetool "ideamerge"]
cmd = C:/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe merge `cygpath -wa $LOCAL` `cygpath -wa $REMOTE` `cygpath -wa $BASE` `cygpath -wa $MERGED`
[merge]
tool = ideamerge
Msys
[mergetool "ideamerge"]
cmd = "/c/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe" merge `~/winpath.sh $LOCAL` `~/winpath.sh $REMOTE` `~/winpath.sh $BASE` `~/winpath.sh $MERGED`
[merge]
tool = ideamerge
The ~/winpath.sh is to convert paths to Windows on msys and is taken from msys path conversion question on stackoverflow
#! /bin/sh
function wpath {
if [ -z "$1" ]; then
echo "$@"
else
if [ -f "$1" ]; then
local dir=$(dirname "$1")
local fn=$(basename "$1")
echo "$(cd "$dir"; echo "$(pwd -W)/$fn")" | sed 's|/|\\|g';
else
if [ -d "$1" ]; then
echo "$(cd "$1"; pwd -W)" | sed 's|/|\\|g';
else
echo "$1" | sed 's|^/\(.\)/|\1:\\|g; s|/|\\|g';
fi
fi
fi
}
wpath "$@"
How about this
var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);
[root]# cat time.c
#include <time.h>
int main(int argc, char** argv)
{
time_t test;
return 0;
}
[root]# gcc -E time.c | grep __time_t
typedef long int __time_t;
It's defined in $INCDIR/bits/types.h
through:
# 131 "/usr/include/bits/types.h" 3 4
# 1 "/usr/include/bits/typesizes.h" 1 3 4
# 132 "/usr/include/bits/types.h" 2 3 4
In bash version 3 you can use the '=~' operator:
if [[ "$date" =~ ^[0-9]{8}$ ]]; then
echo "Valid date"
else
echo "Invalid date"
fi
Reference: http://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF
NOTE: The quoting in the matching operator within the double brackets, [[ ]], is no longer necessary as of Bash version 3.2
Try this:
grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c
Sample:
grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
6 SMTP connect from unknown [188.190.118.90]
54 SMTP connect from unknown [62.193.131.114]
3 SMTP connect from unknown [91.222.51.253]
In addition to the Thomas's answer , static variable are stored in non heap area which is called Method Area.
My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.
Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.
If you are interested in new way of page event handling take a look here, in any other case feel free to continue with this article. You should read this answer even if you are using jQuery Mobile 1.4 +, it goes beyond page events so you will probably find a lot of useful information.
This article can also be found as a part of my blog HERE.
$(document).on('pageinit')
vs $(document).ready()
The first thing you learn in jQuery is to call code inside the $(document).ready()
function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready()
will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.
Classic jQuery syntax:
$(document).ready(function() {
});
To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. In a nutshell page events are events triggered in a particular point of page execution. One of those page events is a pageinit event and we can use it like this:
$(document).on('pageinit', function() {
});
We can go even further and use a page id instead of document selector. Let's say we have jQuery Mobile page with an id index:
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3>
First Page
</h3>
<a href="#second" class="ui-btn-right">Next</a>
</div>
<div data-role="content">
<a href="#" data-role="button" id="test-button">Test button</a>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
To execute code that will only available to the index page we could use this syntax:
$('#index').on('pageinit', function() {
});
Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.
Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.
Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.
There's also another special jQuery Mobile event and it is called mobileinit. When jQuery Mobile starts, it triggers a mobileinit event on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior.
$(document).on("mobileinit", function(){
//apply overrides here
});
First all events can be found here: http://api.jquerymobile.com/category/events/
Lets say we have a page A and a page B, this is a unload/load order:
page B - event pagebeforecreate
page B - event pagecreate
page B - event pageinit
page A - event pagebeforehide
page A - event pageremove
page A - event pagehide
page B - event pagebeforeshow
page B - event pageshow
For better page events understanding read this:
pagebeforeload
, pageload
and pageloadfailed
are fired when an external page is loadedpagebeforechange
, pagechange
and pagechangefailed
are page change events. These events are fired when a user is navigating between pages in the applications.pagebeforeshow
, pagebeforehide
, pageshow
and pagehide
are page transition events. These events are fired before, during and after a transition and are named.pagebeforecreate
, pagecreate
and pageinit
are for page initialization.pageremove
can be fired and then handled when a page is removed from the DOMPage loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/
If AJAX is not enabled, some events may not fire.
If for some reason page transition needs to be prevented on some condition it can be done with this code:
$(document).on('pagebeforechange', function(e, data){
var to = data.toPage,
from = data.options.fromPage;
if (typeof to === 'string') {
var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname.substring(1);
if (from) from = '#' + from.attr('id');
if (from === '#index' && to === '#second') {
alert('Can not transition from #index to #second!');
e.preventDefault();
e.stopPropagation();
// remove active status on a button, if transition was triggered with a button
$.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');;
}
}
});
This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.
Here's a working example:
jQuery Mobile
works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile
handles its pages. For example, take a look at this code snippet:
$(document).on('pagebeforeshow','#index' ,function(e,data){
$(document).on('click', '#test-button',function(e) {
alert('Button click');
});
});
Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/
Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:
Best solution would be to use pageinit
to bind events. If you take a look at an official documentation you will find out that pageinit
will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.
Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/
This working solution is made on a basis of a previous problematic example.
Remove event before you bind it:
$(document).on('pagebeforeshow', '#index', function(){
$(document).off('click', '#test-button').on('click', '#test-button',function(e) {
alert('Button click');
});
});
Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/
Use a jQuery Filter selector, like this:
$('#carousel div:Event(!click)').each(function(){
//If click is not bind to #carousel div do something
});
Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/
In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.
A new one, probably an easiest of them all.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#test-button',function(e) {
if(e.handled !== true) // This will prevent event triggering more than once
{
alert('Clicked');
e.handled = true;
}
});
});
Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/
Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/
pageChange event quirks - triggering twice
Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.
The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.
In few words this is happening because you are sending additional parameters through pageChange.
Example:
<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&name=Sat"><h3>Sat</h3></a>
To fix this problem use any page event listed in Page events transition order.
As mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:
This is a average page transition benchmark:
Page load and processing: 3 ms
Page enhance: 45 ms
Transition: 604 ms
Total time: 670 ms
*These values are in milliseconds.
So as you can see a transition event is eating almost 90% of execution time.
It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.
Reference: https://stackoverflow.com/a/13932240/1848600
Solution 1:
You can pass values with changePage:
$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });
And read them like this:
$(document).on('pagebeforeshow', "#index", function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
index.html
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
<meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
<meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
<title>_x000D_
</title>_x000D_
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
</script>_x000D_
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
<script>_x000D_
$(document).on('pagebeforeshow', "#index",function () {_x000D_
$(document).on('click', "#changePage",function () {_x000D_
$.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });_x000D_
});_x000D_
});_x000D_
_x000D_
$(document).on('pagebeforeshow', "#second",function () {_x000D_
var parameters = $(this).data("url").split("?")[1];;_x000D_
parameter = parameters.replace("parameter=","");_x000D_
alert(parameter);_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<!-- Home -->_x000D_
<div data-role="page" id="index">_x000D_
<div data-role="header">_x000D_
<h3>_x000D_
First Page_x000D_
</h3>_x000D_
</div>_x000D_
<div data-role="content">_x000D_
<a data-role="button" id="changePage">Test</a>_x000D_
</div> <!--content-->_x000D_
</div><!--page-->_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
second.html
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
<meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
<meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
<title>_x000D_
</title>_x000D_
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
</script>_x000D_
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<!-- Home -->_x000D_
<div data-role="page" id="second">_x000D_
<div data-role="header">_x000D_
<h3>_x000D_
Second Page_x000D_
</h3>_x000D_
</div>_x000D_
<div data-role="content">_x000D_
_x000D_
</div> <!--content-->_x000D_
</div><!--page-->_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Solution 2:
Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.
var storeObject = {
firstname : '',
lastname : ''
}
Example: http://jsfiddle.net/Gajotres/9KKbx/
Solution 3:
You can also access data from the previous page like this:
$(document).on('pagebeforeshow', '#index',function (e, data) {
alert(data.prevPage.attr('id'));
});
prevPage object holds a complete previous page.
Solution 4:
As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.
if(typeof(Storage)!=="undefined") {
localStorage.firstname="Dragan";
localStorage.lastname="Gaic";
}
Example: http://jsfiddle.net/Gajotres/J9NTr/
Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.
.live()
/ .bind()
/ .delegate()
I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.
The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live()
method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live()
method is extremely slow. The .live()
method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.
It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live()
method than with it.
Instead of .live()
you should use .on()
. .on()
is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.
There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert
notification system (each “change page” is going to show you this data by halting the app) and change it to console.log
function.
Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....
Always, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.
The 'c' means it's a character special file.
You can use document.write
or even console.write
(this is good for debugging).
But your best bet and it gives you more control is to use DOM to update the page.
Go to your project in the navigator, right click on properties.
Go to the Java Build Path tab on the left.
Go to the libraries tab on top.
Click add external jars.
Go to your ADT Bundle folder, go to sdk/extras/android/support/v7/appcompat/libs.
Select the file android-support-v7-appcompat.jar
Go to order and export and check the box next to your new jar.
Click ok.
For SASS/SCSS user using Bourbon, it has a built-in function.
//main.scss
@import 'bourbon';
input {
width: 300px;
@include placeholder {
color: red;
}
}
CSS Output, you can also grab this portion and paste into your code.
//main.css
input {
width: 300px;
}
input::-webkit-input-placeholder {
color: red;
}
input:-moz-placeholder {
color: red;
}
input::-moz-placeholder {
color: red;
}
input:-ms-input-placeholder {
color: red;
}
In linear regression the outcome is continuous whereas in logistic regression, the outcome has only a limited number of possible values(discrete).
example: In a scenario,the given value of x is size of a plot in square feet then predicting y ie rate of the plot comes under linear regression.
If, instead, you wanted to predict, based on size, whether the plot would sell for more than 300000 Rs, you would use logistic regression. The possible outputs are either Yes, the plot will sell for more than 300000 Rs, or No.
use Below command in terminal
php artisan cache:clear
php artisan route:cache
php artisan config:cache
php artisan view:clear
There is many good answer already posted. I'm adding few new points and summarizing it.
HashMap
and Hashtable
both are used to store data in key and value form. Both are using hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMap
HashMap
is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code. HashMap
allows one null key and multiple null values. HashMap
is a new class introduced in JDK 1.2. HashMap
is fast. HashMap
as synchronized by calling this codeMap m = Collections.synchronizedMap(HashMap);
HashMap
is traversed by Iterator. HashMap
is fail-fast. HashMap
inherits AbstractMap class. Hashtable
Hashtable
is synchronized. It is thread-safe and can be shared with many threads. Hashtable
doesn't allow any null key or value. Hashtable
is a legacy class. Hashtable
is slow. Hashtable
is internally synchronized and can't be unsynchronized. Hashtable
is traversed by Enumerator and Iterator. Hashtable
is not fail-fast. Hashtable
inherits Dictionary class.Further reading What is difference between HashMap and Hashtable in Java?
The CSS working group has publish a Draft on Content Formatting in 2008. But nothing new right now.
As mentioned by @physicsGuy above, You can use the hinterland extension. Simple steps to do it.
Installing nbextension using conda forge channel. Simply run the below command in conda terminal:
conda install -c conda-forge jupyter_nbextensions_configurator
Next Step enabling the hinterland extension. Run the below command in conda terminal:
jupyter nbextension enable hinterland/hinterland
That's it, done.
As sklearn.cross_validation
module was deprecated, you can use:
import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)
X_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)
As Cubbi pointed out in one of the comments, std::wstring_convert
(C++11) provides a neat simple solution (you need to #include
<locale>
and <codecvt>
):
std::wstring string_to_convert;
//setup converter
using convert_type = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_type, wchar_t> converter;
//use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
std::string converted_str = converter.to_bytes( string_to_convert );
I was using a combination of wcstombs
and tedious allocation/deallocation of memory before I came across this.
http://en.cppreference.com/w/cpp/locale/wstring_convert
update(2013.11.28)
One liners can be stated as so (Thank you Guss for your comment):
std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes("some string");
Wrapper functions can be stated as so: (Thank you ArmanSchwarz for your comment)
std::wstring s2ws(const std::string& str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
std::string ws2s(const std::wstring& wstr)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
Note: there's some controversy on whether string
/wstring
should be passed in to functions as references or as literals (due to C++11 and compiler updates). I'll leave the decision to the person implementing, but it's worth knowing.
Note: I'm using std::codecvt_utf8
in the above code, but if you're not using UTF-8 you'll need to change that to the appropriate encoding you're using:
As setYear()
is deprecated, correct variant is:
// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)
All examples return Unix timestamp, if you want to get Date
object - just wrap it with another new Date(...)
declare @date datetime;
set @date = getdate(); -- or some date
select dateadd(month,1+datediff(month,0,@date),-1);
Kyle's answer is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (count
) is available when the lambda function executes.
The command is date
To customise the output there are a myriad of options available, see date --help
for a list.
For example, date '+%A %W %Y %X'
gives Tuesday 34 2013 08:04:22
which is the name of the day of the week, the week number, the year and the time.
Tested on Mac OSX after installing via instructions on composer website:
sudo mv composer.phar /usr/local/bin/composer
Simply go to https://console.developers.google.com/iam-admin/projects you must be signed in of course. There you will see the all your projects google console projects so just select the project you want to delete, and click delete project
option which is shown at the top of the table. I have provided the screenshot
DialogFragment has a public getTheme() method that you can over ride for this exact reason. This solution uses less lines of code:
public class MyCustomDialogFragment extends DialogFragment{
...
@Override
public int getTheme() {
return R.style.MyThemeWithCustomAnimation;
}
}
I can tell you from personal experience this is a bad idea. Native Windows programs cannot accept Cygwin paths. For example with Cygwin you might run a command
grep -r --color foo /opt
with no issue. With Cygwin /
represents the root directory. Native Windows programs have no concept of this, and will likely fail if invoked this way. You should not mix Cygwin and Native Windows programs unless you have no other choice.
Uninstall what Git you have and install the Cygwin git package, save yourself the headache.
Here is an idea as you may have multiple newline in a textbox:
var text=document.getElementById('post-text').value.split('\n');
var html = text.join('<br />');
This HTML value will preserve newline. Hope this helps.
Currently both deletedir() and cleanWs() do not work properly when using Jenkins kubernetes plugin, the pod workspace is deleted but the master workspace persists
it should not be a problem for persistant branches, when you have a step to clean the workspace prior to checkout scam. It will basically reuse the same workspace over and over again: but when using multibranch pipelines the master keeps the whole workspace and git directory
I believe this should be an issue with Jenkins, any enlightenment here?
Use the "has attribute" selector:
$('p[MyTag]')
Or to select one where that attribute has a specific value:
$('p[MyTag="Sara"]')
There are other selectors for "attribute value starts with", "attribute value contains", etc.
A local variable is only accessible from within the block of it's initialization. Also a local variable begins with a lower case letter (a-z) or underscore (_).
And instance variable is an instance of self
and begins with a @
Also an instance variable belongs to the object itself. Instance variables are the ones that you perform methods on i.e. .send
etc
example:
@user = User.all
The @user
is the instance variable
And Uninitialized instance variables have a value of Nil
This way worked for me:
adding the path that you like:
export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add
checking: you can run 'export' cmd and check the output or you can check it using this cmd:
python -c "import sys; print(sys.path)"
Just a reminder of a mistake I made myself too, the
__block
declaration must be done when first declaring the variable, that is, OUTSIDE of the block, not inside of it. This should resolve problems mentioned in the comments about the variable not retaining its value outside of the block.
You should take decodeURI
for it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI
As simple as this:
decodeURI('https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B');
// "https://developer.mozilla.org/ru/docs/JavaScript_?????"
Consider to use it inside try catch
block for not missing an URIError
.
Also it has full browsers support.
SELECT DATEDIFF(max_date, min_date) as days from my table.
This works even if the col max_date
and min_date
are in string data types.
you have to iterate gridview Rows
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
{
((Label)grd.Rows[count].FindControl("labelID")).Text
}
}
Check your environment variables.
In my case I had JAVA_HOME set in the System variables as well as in my User Account variables and the latter was set to a wrong version of Java. I also had the same problem with the Path variable.
After deleting JAVA_HOME from my User Account variables and removing the wrong path from the Path variable it worked correctly.
I had a the same problem and I found the solution that I should put the code to retrieve the drop down list from database in the Edit Method. It worked for me. Solution for the similar problem
In the newer version of datatables (version 1.10.7) it seems things have changed. The way to prevent DataTables from automatically sorting by the first column is to set the order
option to an empty array.
You just need to add the following parameter to the DataTables options:
"order": []
Set up your DataTable as follows in order to override the default setting:
$('#example').dataTable( {
"order": [],
// Your other options here...
} );
That will override the default setting of "order": [[ 0, 'asc' ]]
.
You can find more details regarding the order
option here:
https://datatables.net/reference/option/order
You can implement two tic()
and tac()
functions, where tic()
captures the time which it is called, and tac()
prints the time difference since tic()
was called. Here is a short implementation:
import time
_start_time = time.time()
def tic():
global _start_time
_start_time = time.time()
def tac():
t_sec = round(time.time() - _start_time)
(t_min, t_sec) = divmod(t_sec,60)
(t_hour,t_min) = divmod(t_min,60)
print('Time passed: {}hour:{}min:{}sec'.format(t_hour,t_min,t_sec))
Now in your code you can use it as:
tic()
do_some_stuff()
tac()
and it will, for example, output:
Time passed: 0hour:7min:26sec
From my experience and Maven best practices there are two kinds of "parent poms"
"company" parent pom - this pom contains your company specific information and configuration that inherit every pom and doesn't need to be copied. These informations are:
Preparing this parent pom need to be done with caution, because all your company poms will inherit from it, so this pom have to be mature and stable (releasing a version of parent pom should not affect to release all your company projects!)
The intention is to be scalable to a large scale build so should be scalable to a large number of projects and artifacts.
Mutliprojects have structure of trees - so you aren't arrown down to one level of parent pom. Try to find a suitable project struture for your needs - a classic exmample is how to disrtibute mutimodule projects
distibution/
documentation/
myproject/
myproject-core/
myproject-api/
myproject-app/
pom.xml
pom.xml
A few bonus questions:
- Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).
This configuration has to be wisely splitted into a "company" parent pom and project parent pom(s). Things related to all you project go to "company" parent and this related to current project go to project one's.
- How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?
Company parent pom have to be released first. For multiprojects standard rules applies. CI server need to know all to build the project correctly.
As mentioned in comments, this is a scoping issue. Specifically, $con
is not in scope within your getPosts
function.
You should pass your connection object in as a dependency, eg
function getPosts(mysqli $con) {
// etc
I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
getPosts($con);
Contents are shallow copied.
So if the original dict
contains a list
or another dictionary
, modifying one them in the original or its shallow copy will modify them (the list
or the dict
) in the other.
elasticsearch(ES) supports both a GET or a POST request for getting the data from the ES cluster index.
When we do a GET:
http://localhost:9200/[your index name]/_search?size=[no of records you want]&q=*:*
When we do a POST:
http://localhost:9200/[your_index_name]/_search
{
"size": [your value] //default 10
"from": [your start index] //default 0
"query":
{
"match_all": {}
}
}
I would suggest to use a UI plugin with elasticsearch http://mobz.github.io/elasticsearch-head/ This will help you get a better feeling of the indices you create and also test your indices.
For method decorator declaration
with configuration "noImplicitAny": true,
you can specify type of this variable explicitly depends on @tony19's answer
function logParameter(this:any, target: Object, propertyName: string) {
//...
}
std::vector<int> first;
std::vector<int> second;
first.insert(first.end(), second.begin(), second.end());
Replace
values = ",".join(value_list)
with
values = ','.join([str(i) for i in value_list])
OR
values = ','.join(str(value_list)[1:-1])
String interpolation is going to be included with Python 3.6 as specified in PEP 498. You will be able to do this:
name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')
Note that I hate Spongebob, so writing this was slightly painful. :)
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
Dim adapter As System.Data.SqlClient.SqlDataAdapter
Dim dsdetailwk As New DataSet
Try
adapter = New System.Data.SqlClient.SqlDataAdapter
adapter.SelectCommand = cmd
adapter.Fill(dsdetailwk, "delivery")
Catch Err As System.Exception
End Try
sqlConnection1.Close()
datagridview1.DataSource = dsdetailwk.Tables(0)
Since the question is tagged as JQuery
:
If you are also using JQuery UI
you can use $.datepicker.formatDate()
:
$.datepicker.formatDate('yy/mm/dd', new Date());
See this demo.
To invoke Firefox Browser headlessly, you can set the headless
property through Options()
class as follows:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()
There's another way to accomplish headless mode. If you need to disable or enable the headless mode in Firefox, without changing the code, you can set the environment variable MOZ_HEADLESS
to whatever if you want Firefox to run headless, or don't set it at all.
This is very useful when you are using for example continuous integration and you want to run the functional tests in the server but still be able to run the tests in normal mode in your PC.
$ MOZ_HEADLESS=1 python manage.py test # testing example in Django with headless Firefox
or
$ export MOZ_HEADLESS=1 # this way you only have to set it once
$ python manage.py test functional/tests/directory
$ unset MOZ_HEADLESS # if you want to disable headless mode
How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?
In case of image stacks, I find it easier to use scikit-image
to read, and matplotlib
to show or save. I have handled 16-bit TIFF image stacks with the following code.
from skimage import io
import matplotlib.pyplot as plt
# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(mol,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)
If any one is interested here is what query is executed by psql
on postgres 9.1:
SELECT n.nspname as "Schema",
p.proname as "Name",
pg_catalog.pg_get_function_result(p.oid) as "Result data type",
pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
CASE
WHEN p.proisagg THEN 'agg'
WHEN p.proiswindow THEN 'window'
WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
ELSE 'normal'
END as "Type"
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;
You can get what psql
runs for a backslash command by running psql
with the -E
flag.
You can add ?modestbranding=1
to your url. That will remove the logo.
modestbranding (supported players: AS3, HTML5)
This parameter lets you use a YouTube player that does not show a YouTube logo. Set the parameter value to 1 to prevent the YouTube logo from displaying in the control bar. Note that a small YouTube text label will still display in the upper-right corner of a paused video when the user's mouse pointer hovers over the player.
&showinfo=0
will remove the title bar.
showinfo (supported players: AS3, AS2, HTML5)
Values: 0 or 1. The parameter's default value is 1. If you set the parameter value to 0, then the player will not display information like the video title and uploader before the video starts playing.
You can find all options on the Google Developers website.
It doesn't fully remove the logo. There is still a small logo on the bottom left.
showinfo
is deprecated and will be ignored after September 25, 2018: https://developers.google.com/youtube/player_parameters
I suggest you use TO_CHAR()
when converting to string. In order to do that, you need to build a date first.
SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
(SELECT EXTRACT( DAY FROM
(SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
FROM DUAL
)) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
(SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
)), 09) AS MONTH, EXTRACT(YEAR FROM
(SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
)) AS YEAR
FROM DUAL
);
Here's the answer after a bit of research:
df.loc[:,'quantity'] *= -1 #seems to prevent SettingWithCopyWarning
it's also a good thing to make sure you have the right import
I had an issue like that and I found out that the bean was using
javax.faces.view.ViewScoped;
^
instead of
javax.faces.bean.ViewScoped;
^
You can do it easily with puse CSS without any kind of JS. you have to add position: sticky; top: 0; z-index:999;
in table th
. But this won't work on Chrome Browser but other browser. To work on chrome you have to add those code in table thead th
.table-fixed {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
/*This will work on every browser but Chrome Browser*/_x000D_
.table-fixed thead {_x000D_
position: sticky;_x000D_
position: -webkit-sticky;_x000D_
top: 0;_x000D_
z-index: 999;_x000D_
background-color: #000;_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
/*This will work on every browser*/_x000D_
.table-fixed thead th {_x000D_
position: sticky;_x000D_
position: -webkit-sticky;_x000D_
top: 0;_x000D_
z-index: 999;_x000D_
background-color: #000;_x000D_
color: #fff;_x000D_
}
_x000D_
<table class="table-fixed">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Table Header 1</th>_x000D_
<th>Table Header 2</th>_x000D_
<th>Table Header 3</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
It's a solution for Ubuntu (the idea also works for Windows or Mac) I just tried today and it works like a charm.
Material
Prerequisites on your ubuntu
Install network-manager
$sudo apt-get install network-manager
Install nmap
$sudo apt-get install nmap
Edit Wired connection on your laptop (Ubuntu)
Share WiFi connection of your laptop via Ethernet crossover cable
Hook up your RPi with your laptop using the Ethernet cable
Look up the broadcast address of the Ethernet connection (Laptop),
$/sbin/ifconfig eth1 | grep "Bcast" | awk -F: '{print $3}' | awk '{print $1}'
10.42.0.255
Use this address to find out the IP address of your RPi, it's 10.42.0.96 in my case because 10.42.0.1 is my laptop
$nmap -n -sP 10.42.0.255/24
Starting Nmap 6.40 ( http://nmap.org ) at 2016-02-20 23:07 CET Nmap scan report for 10.42.0.1 Host is up (0.00031s latency). Nmap scan report for 10.42.0.96 Host is up (0.0023s latency). Nmap done: 256 IP addresses (2 hosts up) scanned in 2.71 seconds
Login to your RPi from your laptop (-Y with X-forwarding)
$ssh -Y [email protected]
Lo and behold! Now your RPi is connected to your laptop and RPi can share the WiFi connection.
pi@raspberrypi ~ $
Share display & keyboard of your laptop with RPi
Install vncserver on Raspberry Pi
$ sudo apt-get update
$ sudo apt-get install tightvncserver
Install vncviewer on your laptop by downloading RealVNC (it supports multiple platforms) http://www.realvnc.com/download/vnc/
To be able to copy & paste from VNC server <--> VNC viewer, you need to install autocutsel on your RPi.
$sudo apt-get install autocutsel
If this site doesn't work, try to download the .deb directly from a mirror site, e.g.
mirror.hmc.edu/debian/pool/main/a/autocutsel/autocutsel_0.10.0-1_armhf.deb
and install it
$sudo dpkg -i autocutsel_0.10.0-1_armhf.deb
Start vncserver on your RPi (You have to restart vncserver after installing autocutsel, you can issue $vncserver -kill :1
)
$vncserver :1
Add autocutsel -fork to /home/pi/.vnc/xstartup
#!/bin/sh xrdb $HOME/.Xresources xsetroot -solid grey autocutsel -fork #x-terminal-emulator -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" & #x-window-manager & # Fix to make GNOME work export XKL_XMODMAP_DISABLE=1 /etc/X11/Xsession
Start vncviewer on your laptop
$vncviewer
A vncviewer window will pop up and type in the IP address of your RPi (given by your laptop) followed by port 1, which is your VNC server. for example: 10.42.0.96:1 in my case.
Connect it to the vncserver hosted on your RPi by typing in a password (set up a password yourself)
12.Now you can see the desktop of RPi on your laptop, and I opened my browser to show the shared WiFi connection is working as well.
Check this: System.currentTimeMillis.
With this you can calculate the time of your method by doing:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML. Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field.
User.find({ "username": { "$ne": 'admin' } })
$nin selects the documents where: the field value is not in the specified array or the field does not exist.
User.find({ "groups": { "$nin": ['admin', 'user'] } })
Code Formatting Shortcut:
VSCode on Windows - Shift + Alt + F
VSCode on MacOS - Shift + Option + F
VSCode on Ubuntu - Ctrl + Shift + I
You can also customize this shortcut using preference setting if needed.
column selection with keyboard Ctrl + Shift + Alt + Arrow
My own class request with wsse authentication
class Request {
protected $_url;
protected $_username;
protected $_apiKey;
public function __construct($url, $username, $apiUserKey) {
$this->_url = $url;
$this->_username = $username;
$this->_apiKey = $apiUserKey;
}
public function getHeader() {
$nonce = uniqid();
$created = date('c');
$digest = base64_encode(sha1(base64_decode($nonce) . $created . $this->_apiKey, true));
$wsseHeader = "Authorization: WSSE profile=\"UsernameToken\"\n";
$wsseHeader .= sprintf(
'X-WSSE: UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"', $this->_username, $digest, $nonce, $created
);
return $wsseHeader;
}
public function curl_req($path, $verb=NULL, $data=array()) {
$wsseHeader[] = "Accept: application/vnd.api+json";
$wsseHeader[] = $this->getHeader();
$options = array(
CURLOPT_URL => $this->_url . $path,
CURLOPT_HTTPHEADER => $wsseHeader,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
);
if( !empty($data) ) {
$options += array(
CURLOPT_POSTFIELDS => $data,
CURLOPT_SAFE_UPLOAD => true
);
}
if( isset($verb) ) {
$options += array(CURLOPT_CUSTOMREQUEST => $verb);
}
$ch = curl_init();
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if(false === $result ) {
echo curl_error($ch);
}
curl_close($ch);
return $result;
}
}
There's a go edit -replace command to append a specific commit (even from another forked repository) on top of the current version of a package. What's cool about this option, is that you don't need to know the exact pseudo version beforehand, just the commit hash id.
For example, I'm using the stable version of package "github.com/onsi/ginkgo v1.8.0".
Now I want - without modifying this line of required package in go.mod - to append a patch from my fork, on top of the ginkgo version:
$ GO111MODULE="on" go mod edit -replace=github.com/onsi/ginkgo=github.com/manosnoam/ginkgo@d6423c2
After the first time you build or test your module, GO will try to pull the new version, and then generate the "replace" line with the correct pseudo version. For example in my case, it will add on the bottom of go.mod:
replace github.com/onsi/ginkgo => github.com/manosnoam/ginkgo v0.0.0-20190902135631-1995eead7451
In your link function, do this:
// link function
function (scope, element, attrs) {
var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}
Also, in your link function, don't name your scope
variable using a $
. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.
CTRL+/ on windows, no need to select whole line, Just use key combination on line which you want to comment out.
If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.
Update:
According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).
This solution working for me
window.open(doc.output('bloburl'))
I had the same issue on 14.04 with docker 1.9.1.
The upstart service command did work when I used sudo, even though I was root:
$ whoami
root
$ service docker status
status: Unbekannter Auftrag: docker
$ sudo service docker status
docker start/running, process 7394
It seems to depend on the environment variables.
service docker status
works when becoming root with su -
, but not when only using su
:
$ su
Password:
$ service docker status
status: unknown job: docker
$ exit
$ su -
Password:
$ service docker status
docker start/running, process 2342
Rejecting the WiFi networks idea!
Sorry folks... I don't see it. Using WiFi networks around you seems to be a highly inaccurate and ineffective method of collecting data. WiFi networks these days simply don't stay long in one place.
Think about it, the WiFi networks change every day. Not to mention MiFi and Adhoc networks which are "designed" to be mobile and travel with the users. Equipment breaks, network settings change, people move... Relying on "WiFi Networks" in your area seems highly inaccurate and in the end may not even offer a significant improvement in granularity over IP lookup.
I think the idea that iPhone users are "scanning and sending" the WiFi survey data back to google, and the wardriving, perhaps in conjunction with the Google Maps "Street View" mapping might seem like a very possible method of collecting this data however, in practicality, it does not work as a business model.
Oh and btw, I forgot to mention in my prior post... when I originally pulled my location the time I was pinpointed "precisely" on the map I was connecting to a router from my desktop over an ethernet connection. I don't have a WiFi card on my desktop.
So if that "nearby WiFi networks" theory was true... then I shouldn't have been able to pinpoint my location with such precision.
I'll call my ISP, SKyrim, and ask them as to whether they share their network topology to enable geolocation on their networks.
The best way to understand is to simply think from top to bottom ( Large Desktops to Mobile Phones)
Firstly, as B3 is mobile first so if you use xs then the columns will be same from Large desktops to xs ( i recommend using xs or sm as this will keep everything the way you want on every screen size )
Secondly if you want to give different width to columns on different devices or resolutions, than you can add multiple classes e.g
the above will change the width according to the screen resolutions, REMEMBER i am keeping the total columns in each class = 12
I hope my answer would help!
use padding tags the above float tags didnt worked out, I used
padding left:5px;
padding left :30px
Multiple statements are to be separated by a new line:
If SkyIsBlue Then
StartEngines
Pollute
ElseIf SkyIsRed Then
StopAttack
Vent
ElseIf SkyIsYellow Then
If Sunset Then
Sleep
ElseIf Sunrise or IsMorning Then
Smoke
GetCoffee
Else
Error
End If
Else
Joke
Laugh
End If
I don't believe you can do just a string, but if you put the string inside of a <span>
with the correct attributes (size, font-weight, etc); you should then be able to use jQuery to get the width of the span.
<span id='string_span' style='font-weight: bold; font-size: 12'>Here is my string</span>
<script>
$('#string_span').width();
</script>
You can use localStorage
for the purpose.
Steps:
You can use sp_columns, a stored procedure for describing the table.
exec sp_columns TableName
You can also use sp_help.
What do you think about this approach?
<body class="thatClass anotherClass"> </body>
var bodyClasses = document.querySelector('body').className;
var myClass = new RegExp("thatClass");
var trueOrFalse = myClass.test( bodyClasses );
Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.
I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:
<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
If value IsNot Nothing Then
If value = True Then
Return Visibility.Visible
Else
Return Visibility.Collapsed
End If
Else
Return Visibility.Collapsed
End If
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Throw New NotImplementedException
End Function
End Class
A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.
How easy :)
date("F j, Y", strtotime( '-1 days' ) );
Example:
echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43
Output:
2018-07-17 07:02:43
Not for the questioner, but for all others, which are interested: See: How to define Typescript Map of key value pair. where key is a number and value is an array of objects
The solution is therefore:
let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;
Cheers!
Updated answer for 2019.
Regex object is thread-safe for Matching functions. Knowing that and there are some performance options or cultural / language issues, I propose this simple solution.
public static Regex _regex = new Regex(
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Singleline);
public static bool IsValidEmailFormat(string emailInput)
{
return _regex.IsMatch(emailInput);
}
Alternative Configuration for Regex:
public static Regex _regex = new Regex(
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
I find that compiled is only faster on big string matches, like book parsing for example. Simple email matching is faster just letting Regex interpret.
There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.
For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):
<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>
This line helps find the program executable that will run the script. This shebang notation is fairly standard across most scripting languages (at least as used on grown-up operating systems).
An important aspect of this line is specifying which interpreter will be used. On many development-centered Linux distributions, for example, it is normal to have several versions of python installed at the same time.
Python 2.x and Python 3 are not 100% compatible, so this difference can be very important. So #! /usr/bin/python
and #! /usr/bin/python3
are not the same (and neither are quite the same as #! /usr/bin/env python3
as noted elsewhere on this page.
In Sqlite
:
CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
Very ugly but does the trick if you only want compile time info (e.g. for debugging):
auto testVar = std::make_tuple(1, 1.0, "abc");
decltype(testVar)::foo= 1;
Returns:
Compilation finished with errors:
source.cpp: In function 'int main()':
source.cpp:5:19: error: 'foo' is not a member of 'std::tuple<int, double, const char*>'
Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.
An example:
try {
// Create temp file.
File temp = File.createTempFile("pattern", ".suffix");
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}
After many attempts I was finally able to get this working. Essentially what I did was download and use the vmware converter to merge the two disks into one. After that I was able to attach the newly created disk to VitrualBox.
The steps involved are very simple:
BEFORE YOU DO ANYTHING!
1) MAKE A BACKUP!!! Even if you follow these instruction, you could screw things up, so make a backup. Just shutdown the VM and then make a copy of the directory where VM resides.
2) Uninstall VMware Tools from the VM that you are going to convert. If for some reason you forget this step, you can still uninstall it after getting everything running under VirtualBox by following these steps. Do yourself the favor and just do it now.
NOW THE FUN PART!!!
1) Download and install the VMware Converter. I used 5.0.1 build-875114, just use the latest.
2) Download and install VirtualBox
3) Fire up VMWare convertor:
4) Click on Convert machine
6) Browse to the .vmx
for your VM and click Next
.
7) Give the new VM a name and select the location where you want to put it. Click Next
8) Click Next
on the Options
screen. You shouldn't have to change anything here.
9) Click Finish
on the Summary
screen to begin the conversion.
10) The conversion should start. This will take a LOOONG time so be patient.
11) Hopefully all went well, if it did, you should see that the conversion is completed:
12) Now open up VirtualBox and click New
.
13) Give your VM a name and select what Type
and Version
it is. Click Next
.
14) Select the size of the memory you want to give it. Click Next
.
15) For the Hard Drive
, click Use and existing hard drive file
and select the newly converted .vmdk
file.
16) Now Click Settings
and select the Storage
menu. The issue is that by default VirtualBox will add the drive as an IDE. This won't work and we need as we need to put it on a SCSI controller.
17) Select the IDE controller and the Remove Controller
button.
18) Now click the Add Controller
button and select Add SCSI Controller
19) Click the Add Hard Disk
button.
20) Click Choose existing disk
21) Select your .vmdk
file. Click OK
22) Select the System
menu.
23) Click Enable IO APIC
. Then click OK
24) Congrats!!! Your VM is now confgiured! Click Start
to startup the VM!
I suggest you to use provider
.
Provide is good when you want to configure it first before to use (against Service/Factory)
Something like:
.provider('Magazines', function() {
this.url = '/';
this.urlArray = '/';
this.organId = 'Default';
this.$get = function() {
var url = this.url;
var urlArray = this.urlArray;
var organId = this.organId;
return {
invoke: function() {
return ......
}
}
};
this.setUrl = function(url) {
this.url = url;
};
this.setUrlArray = function(urlArray) {
this.urlArray = urlArray;
};
this.setOrganId = function(organId) {
this.organId = organId;
};
});
.config(function(MagazinesProvider){
MagazinesProvider.setUrl('...');
MagazinesProvider.setUrlArray('...');
MagazinesProvider.setOrganId('...');
});
And now controller:
function MyCtrl($scope, Magazines) {
Magazines.invoke();
....
}
Here is an input box with a search icon on the right.
<div class="input-group">
<input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
<div class="input-group-append">
<div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
</div>
</div>
Here is an input box with a search icon on the left.
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
</div>
<input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
</div>
I need to do this frequently, so I use this:
var loadJS = function(url, implementationCode, location){
//url is URL of external file, implementationCode is the code
//to be called from the file, location is the location to
//insert the <script> element
var scriptTag = document.createElement('script');
scriptTag.src = url;
scriptTag.onload = implementationCode;
scriptTag.onreadystatechange = implementationCode;
location.appendChild(scriptTag);
};
var yourCodeToBeCalled = function(){
//your code goes here
}
loadJS('yourcode.js', yourCodeToBeCalled, document.body);
For more information, see this site How do I include a JavaScript file in another JavaScript file?, which is the source of my function idea.
This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.
If you don't want a fixed layout, specify a class for the column to be size appropriately.
CSS:
.special_column { width: 120px; }
HTML:
<td class="special_column">...</td>
In bash $1
is the first argument passed to the script, $2
second and so on
/usr/local/bin/abbyyocr9 -rl Swedish -if "$1" -of "$2" 2>&1
So you can use:
./your_script.sh some_source_file.png destination_file.txt
Explanation on double quotes;
consider three scripts:
# foo.sh
bash bar.sh $1
# cat foo2.sh
bash bar.sh "$1"
# bar.sh
echo "1-$1" "2-$2"
Now invoke:
$ bash foo.sh "a b"
1-a 2-b
$ bash foo2.sh "a b"
1-a b 2-
When you invoke foo.sh "a b"
then it invokes bar.sh a b
(two arguments), and with foo2.sh "a b"
it invokes bar.sh "a b"
(1 argument). Always have in mind how parameters are passed and expaned in bash, it will save you a lot of headache.
This is the simplest solution working for me.
$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
My RestSharp POST method:
var client = new RestClient(ServiceUrl);
var request = new RestRequest("/resource/", Method.POST);
// Json to post.
string jsonToSend = JsonHelper.ToJson(json);
request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
try
{
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
// OK
}
else
{
// NOK
}
});
}
catch (Exception error)
{
// Log
}
Closure
is versatile. bobince has well summarized the prototype vs. closure approaches when creating objects. However you can mimic some aspects of OOP
using closure in a functional programming way. Remember functions are objects in JavaScript; so use function as object in a different way.
Here is an example of closure:
function outer(outerArg) {
return inner(innerArg) {
return innerArg + outerArg; //the scope chain is composed of innerArg and outerArg from the outer context
}
}
A while ago I came across the Mozilla's article on Closure. Here is what jump at my eyes: "A closure lets you associate some data (the environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods". It was the very first time I read a parallelism between closure and classic OOP with no reference to prototype.
How?
Suppose you want to calculate the VAT of some items. The VAT is likely to stay stable during the lifetime of an application. One way to do it in OOP (pseudo code):
public class Calculator {
public property VAT { get; private set; }
public Calculator(int vat) {
this.VAT = vat;
}
public int Calculate(int price) {
return price * this.VAT;
}
}
Basically you pass a VAT value into your constructor and your calculate method can operate upon it via closure. Now instead of using a class/constructor, pass your VAT as an argument into a function. Because the only stuff you are interested in is the calculation itself, returns a new function, which is the calculate method:
function calculator(vat) {
return function(item) {
return item * vat;
}
}
var calculate = calculator(1.10);
var jsBook = 100; //100$
calculate(jsBook); //110
In your project identify top-level values that are good candidate of what VAT is for calculation. As a rule of thumb whenever you pass the same arguments on and on, there is a way to improve it using closure. No need to create traditional objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
I am using API level 27 and found a best solution after struggling for around two days. If you want to read a xml file from a class which doesn't derive from Activity or Application then do the following.
Put the testdata.xml file inside the assets directory.
Write the following code to get the testdata document parsed.
InputStream inputStream = this.getClass().getResourceAsStream("/assets/testdata.xml");
// create a new DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// use the factory to create a documentbuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// create a new document from input stream
Document doc = builder.parse(inputStream);
Reducing just the padding on the columns won't make the trick, as you will extend the width of the page, making it uneven with the rest of your page, say navbar. You need to equally reduce the negative margin on the row. Taking @martinedwards' LESS example:
.row-no-padding {
margin-left: 0;
margin-right: 0;
[class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
}
Yes. :-) But not in a way you would expect.
int f1(int arg1, double arg2, char* name, char *opt);
int f2(int arg1, double arg2, char* name)
{
return f1(arg1, arg2, name, "Some option");
}
Unfortunately, C doesn't allow you to overload methods so you'd end up with two different functions. Still, by calling f2, you'd actually be calling f1 with a default value. This is a "Don't Repeat Yourself" solution, which helps you to avoid copying/pasting existing code.
a piece of code who work with python to read rs232 just in case somedoby else need it
ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()
.vscode/launch.json file is only used by Visual Studio as well as /Properties/launchSettings.json file. Don't use these files in production.
The launchSettings.json file:
contains profile settings.
To use a file 'appSettings.QA.json' for example. You can use 'ASPNETCORE_ENVIRONMENT'. Follow the steps below.
Incase its useful to others, the following is what worked for me:
On my machine, although npm proxy was set correctly, npm install
waits forever doing something like sill extract. Re-trying npm install
waits forever on the same package again and again.
After waiting for a long timeout, npm install
printed an error message implying that git was trying to fetch something.
The problem vanished after configuring git proxy using the below command:
git config --global http.proxy https://proxy-server:port
Note the https
in the value of http.proxy
without which the configuration did not take effect. Proxy server settings (http / https / port) might vary for users; hence its worth spending a bit of time experimenting with npm and git proxy server settings.
<div id="my_id" class="my_class"></div>
if that is the first div then address it like so:
document.write("div CSS class: " + document.getElementsByTagName('div')[0].className);
alternatively do this:
document.write("alternative way: " + document.getElementById('my_id').className);
It yields the following results:
div CSS class: my_class
alternative way: my_class
<div class="small hidden-xs">
Some Content Here
</div>
This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.
This answer satisfies the question in the OP title (which is how I found this Q/A).
convert_objects is deprecated.
For pandas >= 0.17.0, use pd.to_numeric
df["2nd"] = pd.to_numeric(df["2nd"])
you don't need to set the width of header in css, just put the background image as center using this code:
background: url("images/logo.png") no-repeat top center;
or you can just use img
tag and put align="center"
in the div
@Controller
is used in legacy systems which use JSPs. it can return views.
@RestController
is to mark the controller is providing REST services with JSON response type. so it wraps @Controller
and @ResponseBody
annotations together.
ALTER TABLE `users` ADD COLUMN
`COLUMN NAME` DATATYPE(SIZE) AFTER `EXISTING COLUMN NAME`;
You can do it with this, working fine for me.
It means that es3.c
does not define a main
function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.
To compile only to an object file, use the -c
option:
gcc es3.c -c
gcc es3.o main.c -o es3
The above compiles es3.c
to an object file, then compiles a file main.c
that would contain the main
function, and the linker merges es3.o
and main.o
into an executable called es3
.
There are a couple of ways you can do this. Terminal to execute the script:
#!/bin/bash
SCRIPT_PATH="/path/to/script.sh"
# Here you execute your script
"$SCRIPT_PATH"
# or
. "$SCRIPT_PATH"
# or
source "$SCRIPT_PATH"
# or
bash "$SCRIPT_PATH"
# or
eval '"$SCRIPT_PATH"'
# or
OUTPUT=$("$SCRIPT_PATH")
echo $OUTPUT
# or
OUTPUT=`"$SCRIPT_PATH"`
echo $OUTPUT
# or
("$SCRIPT_PATH")
# or
(exec "$SCRIPT_PATH")
All this is correct for the path with spaces!!!
This works for me:
try {
$statusUpdate = $facebook->api('/me/feed', 'post',
array('name'=>'My APP on Facebook','message'=> 'I am here working',
'privacy'=> array('value'=>'CUSTOM','friends'=>'SELF'),
'description'=>'testing my description',
'picture'=>'https://fbcdn-photos-a.akamaihd.net/mypicture.gif',
'caption'=>'apps.facebook.com/myapp','link'=>'http://apps.facebook.com/myapp'));
} catch (FacebookApiException $e) {
d($e);
}
Had one of these as well, but the parameter of the action was an interface with no public properties. Ended up using It.Is() with a seperate method and within this method had to do some mocking of the interface
public interface IQuery
{
IQuery SetSomeFields(string info);
}
void DoSomeQuerying(Action<IQuery> queryThing);
mockedObject.Setup(m => m.DoSomeQuerying(It.Is<Action<IQuery>>(q => MyCheckingMethod(q)));
private bool MyCheckingMethod(Action<IQuery> queryAction)
{
var mockQuery = new Mock<IQuery>();
mockQuery.Setup(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition())
queryAction.Invoke(mockQuery.Object);
mockQuery.Verify(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition(), Times.Once)
return true
}
Use \n
for a line break and \t
if you want to insert a tab.
You can also use some XML tags for basic formatting: <b>
for bold text, <i>
for italics, and <u>
for underlined text.
Other formatting options are shown in this article on the Android Developers' site:
https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
If you want to compare image for similarity,I suggest you to used OpenCV. In OpenCV, there are few feature matching and template matching. For feature matching, there are SURF, SIFT, FAST and so on detector. You can use this to detect, describe and then match the image. After that, you can use the specific index to find number of match between the two images.
std::less<>
when using custom classes with operator<
If you are dealing with a set of your custom class that has operator<
defined, then you can just use std::less<>
.
As mentioned at http://en.cppreference.com/w/cpp/container/set/find C++14 has added two new find
APIs:
template< class K > iterator find( const K& x );
template< class K > const_iterator find( const K& x ) const;
which allow you to do:
main.cpp
#include <cassert>
#include <set>
class Point {
public:
// Note that there is _no_ conversion constructor,
// everything is done at the template level without
// intermediate object creation.
//Point(int x) : x(x) {}
Point(int x, int y) : x(x), y(y) {}
int x;
int y;
};
bool operator<(const Point& c, int x) { return c.x < x; }
bool operator<(int x, const Point& c) { return x < c.x; }
bool operator<(const Point& c, const Point& d) {
return c.x < d;
}
int main() {
std::set<Point, std::less<>> s;
s.insert(Point(1, -1));
s.insert(Point(2, -2));
s.insert(Point(0, 0));
s.insert(Point(3, -3));
assert(s.find(0)->y == 0);
assert(s.find(1)->y == -1);
assert(s.find(2)->y == -2);
assert(s.find(3)->y == -3);
// Ignore 1234, find 1.
assert(s.find(Point(1, 1234))->y == -1);
}
Compile and run:
g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
More info about std::less<>
can be found at: What are transparent comparators?
Tested on Ubuntu 16.10, g++
6.2.0.
Just be warned - When using a Nullable its obviously no longer a 'pure' datetime object, as such you cannot access the DateTime members directly. I'll try and explain.
By using Nullable<> you're basically wrapping DateTime in a container (thank you generics) of which is nullable - obviously its purpose. This container has its own properties which you can call that will provide access to the aforementioned DateTime object; after using the correct property - in this case Nullable.Value - you then have access to the standard DateTime members, properties etc.
So - now the issue comes to mind as to the best way to access the DateTime object. There are a few ways, number 1 is by FAR the best and 2 is "dude why".
Using the Nullable.Value property,
DateTime date = myNullableObject.Value.ToUniversalTime(); //Works
DateTime date = myNullableObject.ToUniversalTime(); //Not a datetime object, fails
Converting the nullable object to datetime using Convert.ToDateTime(),
DateTime date = Convert.ToDateTime(myNullableObject).ToUniversalTime(); //works but why...
Although the answer is well documented at this point, I believe the usage of Nullable was probably worth posting about. Sorry if you disagree.
edit: Removed a third option as it was a bit overly specific and case dependent.
@vimal answer did not provide solution for me. It seems the orientation is not the current orientation, but from previous orientation. To fix it, I use [[UIDevice currentDevice] orientation]
- (void)orientationChanged:(NSNotification *)notification{
[self adjustViewsForOrientation:[[UIDevice currentDevice] orientation]];
}
Then
- (void) adjustViewsForOrientation:(UIDeviceOrientation) orientation { ... }
With this code I get the current orientation position.
My first answer!
This will set the safemode switch:
bcdedit /set {current} safeboot minimal
with networking:
bcdedit /set {current} safeboot network
then reboot the machine with
shutdown /r
to put back in normal mode via dos:
bcdedit /deletevalue {current} safeboot
You can use the event.target.result to reset the input from a component directly.
event.target.value = ""