For me it worked, by removing the jars in question from the war. With Maven, I just had to exclude for example
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>${resteasy.version}</version>
<exclusions>
<exclusion>
<groupId>com.sun.istack</groupId>
<artifactId>istack-commons-runtime</artifactId>
</exclusion>
<exclusion>
<groupId>org.jvnet.staxex</groupId>
<artifactId>stax-ex</artifactId>
</exclusion>
<exclusion>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>txw2</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.xml.fastinfoset</groupId>
<artifactId>FastInfoset</artifactId>
</exclusion>
</exclusions>
</dependency>
apache-tomcat-8.0.33
If you want to enable debug logging in tomcat for TLD scanned jars then you have to change /conf/logging.properties file in tomcat directory.
uncomment the line :
org.apache.jasper.servlet.TldScanner.level = FINE
FINE level is for debug log.
This should work for normal tomcat.
If the tomcat is running under eclipse. Then you have to set the path of tomcat logging.properties in eclipse.
Now the jar files that scanned for TLDs should show in the log.
You must not use =
. Simply use this:
export CATALINA_OPTS="-Xms512M -Xmx1024M"
I found logs of Apache Tomcat/9.0.33 version in below path:
In tail -f /opt/tomcat/logs/catalina.out
Thanks.
Basic Steps to Debug a Procedure in Toad
Reference:Toad Debugger
ah, the beauty of ternaries:
const now = new Date();
const expiry = now.getMonth() == 11 ? new Date(now.getFullYear()+1, 0 , 1) : new Date(now.getFullYear(), now.getMonth() + 1, 1);
just a simpler version of the solution provided by @paxdiablo and @Tom
I guess what you are wanting to do is database migration. 'Drop'ping a column does not exist in SQLite. But you can however, add an extra column by using the ALTER table query.
// you need to have a list of data that you want the spinner to display
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);
also to find out what is selected you could do something like this
String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}
Try this in angular 8.0:
@ViewChild('result',{static: false}) resultElement: ElementRef;
This solution can be applied only if the issue is on a WordPress installation!
If you don't have FTP access or too lazy to edit files,
You can use Increase Maximum Upload File Size plugin to increase the maximum upload file size.
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
LEA (Load Effective Address) is a shift-and-add instruction. It was added to 8086 because hardware is there to decode and calculate adressing modes.
You can also put the files or links into the root of the solution explorer and then set the files properties:
Build action = Content
and
Copy to Output Directory = Copy if newer
(for example)
For a link drag the file from the windows explorer into the solution explorer holding down the shift and control keys.
I used a deque... seems to work for me. This example has a vector, but you could skip that aspect and simply add them to deque.
#include <deque>
template <typename T>
double mov_avg(vector<T> vec, int len){
deque<T> dq = {};
for(auto i = 0;i < vec.size();i++){
if(i < len){
dq.push_back(vec[i]);
}
else {
dq.pop_front();
dq.push_back(vec[i]);
}
}
double cs = 0;
for(auto i : dq){
cs += i;
}
return cs / len;
}
//Skip the vector portion, track the input number (or size of deque), and the value.
double len = 10;
double val; //Accept as input
double instance; //Increment each time input accepted.
deque<double> dq;
if(instance < len){
dq.push_back(val);
}
else {
dq.pop_front();
dq.push_back(val);
}
}
double cs = 0;
for(auto i : dq){
cs += i;
}
double rolling_avg = cs / len;
//To simplify further -- add values to this, then simply average the deque.
int MAX_DQ = 3;
void add_to_dq(deque<double> &dq, double value){
if(dq.size() < MAX_DQ){
dq.push_back(value);
}else {
dq.pop_front();
dq.push_back(value);
}
}
Another sort of hack I use occasionally is using mod to overwrite values in a vector.
vector<int> test_mod = {0,0,0,0,0};
int write = 0;
int LEN = 5;
int instance = 0; //Filler for N -- of Nth Number added.
int value = 0; //Filler for new number.
write = instance % LEN;
test_mod[write] = value;
//Will write to 0, 1, 2, 3, 4, 0, 1, 2, 3, ...
//Then average it for MA.
//To test it...
int write_idx = 0;
int len = 5;
int new_value;
for(auto i=0;i<100;i++){
cin >> new_value;
write_idx = i % len;
test_mod[write_idx] = new_value;
This last (hack) has no buckets, buffers, loops, nothing. Simply a vector that's overwritten. And it's 100% accurate (for avg / values in vector). Proper order is rarely maintained, as it starts rewriting backwards (at 0), so 5th index would be at 0 in example {5,1,2,3,4}, etc.
Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,
<script type=text/javascript src='/dir/jsfile.js'></script>
or
<script type=text/javascript src='../../scripts/jsfile.js'></script>
If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path
Create a configuration file and put your entries there.
SERVER_PORT=10000
THREAD_POOL_COUNT=3
ROOT_DIR=/home/
You can load this file using Properties.load(fileName)
and retrieved values you get(key)
;
For testing purposes, if you want to test your web page which includes reCaptcha on localhost then add localhost in domain list by Admin Console 1: https://www.google.com/recaptcha/admin. *It is advised to create a separate site key for localhost.
Thanks :)
I had this issue with a package that was added to my app (FancyShowCaseView) and caused this problem on pre-lolipop. that package was written in kotlin and my main codes were written in java. so now I'm checking version in pre-lolipop and don't let its class to be executed. temporary solved the problem. check this out if you have similar problem like me
Taking data of DataBase without sorting is the same as random take
You should not include folder node_modules in your .gitignore file (or rather you should include folder node_modules in your source deployed to Heroku).
If folder node_modules:
npm install
will use those vendored libraries and will rebuild any binary dependencies with npm rebuild
.npm install
will have to fetch all dependencies itself which adds time to the slug compile step.See the Node.js buildpack source for these exact steps.
However, the original error looks to be an incompatibility between the versions of npm and Node.js. It is a good idea to always explicitly set the engines
section of your packages.json file according to this guide to avoid these types of situations:
{
"name": "myapp",
"version": "0.0.1",
"engines": {
"node": "0.8.x",
"npm": "1.1.x"
}
}
This will ensure development/production parity and reduce the likelihood of such situations in the future.
You have referenced the image as a path on your computer (C:\etc\etc)......is it located there? You didn't answer what others have asked. I have taken your code, placed it in dreamweaver and it works apart from the image as I don't have that stored.
Check the location and then let us know.
Try this
var URL = "scratch.mit.edu/projects";
var mainURL = window.location.pathname;
if (mainURL == URL) {
mainURL += ( mainURL.match( /[\?]/g ) ? '&' : '#' ) + '_bypasssharerestrictions_';
console.log(mainURL)
}
I mixed the Rohit Sisodia and MGM answers
// MARK: - Gradient
public enum CAGradientPoint {
case topLeft
case centerLeft
case bottomLeft
case topCenter
case center
case bottomCenter
case topRight
case centerRight
case bottomRight
var point: CGPoint {
switch self {
case .topLeft:
return CGPoint(x: 0, y: 0)
case .centerLeft:
return CGPoint(x: 0, y: 0.5)
case .bottomLeft:
return CGPoint(x: 0, y: 1.0)
case .topCenter:
return CGPoint(x: 0.5, y: 0)
case .center:
return CGPoint(x: 0.5, y: 0.5)
case .bottomCenter:
return CGPoint(x: 0.5, y: 1.0)
case .topRight:
return CGPoint(x: 1.0, y: 0.0)
case .centerRight:
return CGPoint(x: 1.0, y: 0.5)
case .bottomRight:
return CGPoint(x: 1.0, y: 1.0)
}
}
}
extension CAGradientLayer {
convenience init(start: CAGradientPoint, end: CAGradientPoint, colors: [CGColor], type: CAGradientLayerType) {
self.init()
self.frame.origin = CGPoint.zero
self.startPoint = start.point
self.endPoint = end.point
self.colors = colors
self.locations = (0..<colors.count).map(NSNumber.init)
self.type = type
}
}
extension UIView {
func layerGradient(startPoint:CAGradientPoint, endPoint:CAGradientPoint ,colorArray:[CGColor], type:CAGradientLayerType ) {
let gradient = CAGradientLayer(start: .topLeft, end: .topRight, colors: colorArray, type: type)
gradient.frame.size = self.frame.size
self.layer.insertSublayer(gradient, at: 0)
}
}
To Use write:-
btnUrdu.layer.cornerRadius = 25
btnUrdu.layer.masksToBounds = true
btnUrdu.layerGradient(startPoint: .centerRight, endPoint: .centerLeft, colorArray: [UIColor.appBlue.cgColor, UIColor.appLightBlue.cgColor], type: .axial)
Output:
Software application written with Arduino, an IDE used for prototyping electronics; contains source code written in the Arduino programming language; enables developers to control the electronics on an Arduino circuit board.
To avoid file association conflicts with the Processing software, Arduino changed the Sketch file extension to .INO with the version 1.0 release. Therefore, while Arduino can still open ".pde" files, the ".ino" file extension should be used instead.
Each PDE file is stored in its own folder when saved from the Processing IDE. It is saved with any other program assets, such as images. The project folder and PDE filename prefix have the same name. When the PDE file is run, it is opened in a Java display window, which renders and runs the resulting program.
Processing is commonly used in educational settings for teaching basic programming skills in a visual environment.
Is the value of your particular COMMENT column null?
Sometimes NOT LIKE doesn't know how to behave properly around nulls.
I'd do it this way:
[in the public header]
typedef unsigned long E;
void Foo(E e);
[in the internal header]
enum Econtent { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X,
FORCE_32BIT = 0xFFFFFFFF };
By adding FORCE_32BIT we ensure that Econtent compiles to a long, so it's interchangeable with E.
ModRewrite is not the only answer. You could also use Options +MultiViews in .htaccess and then check $_SERVER REQUEST_URI
to find everything that is in URL.
first open the docker image for the postgres
docker exec -it <container_name>
then u will get the root --root@868594e88b53:/#
it need the database connection
psql postgresql://<username>:<databasepassword>@postgres:5432/<database>
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
I had same issue I could resolved issue with replace 'localhost' with IP which is '0.0.0.0'
Aghhh... i was missing some code when i first tried the .submit function.....
This works:
$('#create-card-process.design').submit(function() {
var textStyleCSS = $("#cover-text").attr('style');
var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
$("#cover_text_css").val(textStyleCSS);
$("#cover_text_background_css").val(textbackgroundCSS);
});
Thanks for all the comments.
Unfortunately there's a simple answer to this question, and it's "No"
Kotlin way
editText.setOnFocusChangeListener { _, hasFocus ->
if (!hasFocus) { }
}
If you have to choose between __repr__
or __str__
go for the first one, as by default implementation __str__
calls __repr__
when it wasn't defined.
Custom Vector3 example:
class Vector3(object):
def __init__(self, args):
self.x = args[0]
self.y = args[1]
self.z = args[2]
def __repr__(self):
return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z)
def __str__(self):
return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z)
In this example, repr
returns again a string that can be directly consumed/executed, whereas str
is more useful as a debug output.
v = Vector3([1,2,3])
print repr(v) #Vector3([1,2,3])
print str(v) #x:1, y:2, z:3
FWIW, this BASH script will take a PEM- or DER-format X.509 certificate or OpenSSL public key file (also PEM format) as the first argument and disgorge an OpenSSH RSA public key. This expands upon @mkalkov's answer above. Requirements are cat
, grep
, tr
, dd
, xxd
, sed
, xargs
, file
, uuidgen
, base64
, openssl
(1.0+), and of course bash
. All except openssl
(contains base64
) are pretty much guaranteed to be part of the base install on any modern Linux system, except maybe xxd
(which Fedora shows in the vim-common
package). If anyone wants to clean it up and make it nicer, caveat lector.
#!/bin/bash
#
# Extract a valid SSH format public key from an X509 public certificate.
#
# Variables:
pubFile=$1
fileType="no"
pkEightTypeFile="$pubFile"
tmpFile="/tmp/`uuidgen`-pkEightTypeFile.pk8"
# See if a file was passed:
[ ! -f "$pubFile" ] && echo "Error, bad or no input file $pubFile." && exit 1
# If it is a PEM format X.509 public cert, set $fileType appropriately:
pemCertType="X$(file $pubFile | grep 'PEM certificate')"
[ "$pemCertType" != "X" ] && fileType="PEM"
# If it is an OpenSSL PEM-format PKCS#8-style public key, set $fileType appropriately:
pkEightType="X$(grep -e '-BEGIN PUBLIC KEY-' $pubFile)"
[ "$pkEightType" != "X" ] && fileType="PKCS"
# If this is a file we can't recognise, try to decode a (binary) DER-format X.509 cert:
if [ "$fileType" = "no" ]; then
openssl x509 -in $pubFile -inform DER -noout
derResult=$(echo $?)
[ "$derResult" = "0" ] && fileType="DER"
fi
# Exit if not detected as a file we can use:
[ "$fileType" = "no" ] && echo "Error, input file not of type X.509 public certificate or OpenSSL PKCS#8-style public key (not encrypted)." && exit 1
# Convert the X.509 public cert to an OpenSSL PEM-format PKCS#8-style public key:
if [ "$fileType" = "PEM" -o "$fileType" = "DER" ]; then
openssl x509 -in $pubFile -inform $fileType -noout -pubkey > $tmpFile
pkEightTypeFile="$tmpFile"
fi
# Build the string:
# Front matter:
frontString="$(echo -en 'ssh-rsa ')"
# Encoded modulus and exponent, with appropriate pointers:
encodedModulus="$(cat $pkEightTypeFile | grep -v -e "----" | tr -d '\n' | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 )"
# Add a comment string based on the filename, just to be nice:
commentString=" $(echo $pubFile | xargs basename | sed -e 's/\.crt\|\.cer\|\.pem\|\.pk8\|\.der//')"
# Give the user a string:
echo $frontString $encodedModulus $commentString
# cleanup:
rm -f $tmpFile
You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.
private void AggiornaContatore()
{
if(this.lblCounter.InvokeRequired)
{
this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});
}
else
{
this.lblCounter.Text = this.index.ToString(); ;
}
}
Please go through this chapter and more from this book to get a clear picture about threading:
http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications
Question 1: Restrict to certain characters
You are right, this is easy to solve with regular expressions:
import re
input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
print "Error! Only letters a-z allowed!"
sys.exit()
Question 2: Restrict to certain length
As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:
input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
print "Error! Only 15 characters allowed!"
sys.exit()
Or both in one:
import re
input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
print "Error! Only letters a-z allowed!"
sys.exit()
elif len(input_str) > 15:
print "Error! Only 15 characters allowed!"
sys.exit()
print "Your input was:", input_str
I started with @jhoff's solution, but rewrote it to use width/height parameters, and using arcTo
makes it quite a bit more terse:
CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
if (w < 2 * r) r = w / 2;
if (h < 2 * r) r = h / 2;
this.beginPath();
this.moveTo(x+r, y);
this.arcTo(x+w, y, x+w, y+h, r);
this.arcTo(x+w, y+h, x, y+h, r);
this.arcTo(x, y+h, x, y, r);
this.arcTo(x, y, x+w, y, r);
this.closePath();
return this;
}
Also returning the context so you can chain a little. E.g.:
ctx.roundRect(35, 10, 225, 110, 20).stroke(); //or .fill() for a filled rect
Implement the return statement like the example below! You should be good. I hope it helps someone..
class Example(object):
def the_example(self):
itsProblem = "problem"
return itsProblem
theExample = Example()
print theExample.the_example()
You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
all these answers has the problem, that's always stretching the image to pagesize and cuts off some content at trying this.
Found a little bit easier way.
My own solution only stretch(is this the right word?) if the image is to large, can use multiply copies and pageorientations.
PrintDialog dlg = new PrintDialog();
if (dlg.ShowDialog() == true)
{
BitmapImage bmi = new BitmapImage(new Uri(strPath));
Image img = new Image();
img.Source = bmi;
if (bmi.PixelWidth < dlg.PrintableAreaWidth ||
bmi.PixelHeight < dlg.PrintableAreaHeight)
{
img.Stretch = Stretch.None;
img.Width = bmi.PixelWidth;
img.Height = bmi.PixelHeight;
}
if (dlg.PrintTicket.PageBorderless == PageBorderless.Borderless)
{
img.Margin = new Thickness(0);
}
else
{
img.Margin = new Thickness(48);
}
img.VerticalAlignment = VerticalAlignment.Top;
img.HorizontalAlignment = HorizontalAlignment.Left;
for (int i = 0; i < dlg.PrintTicket.CopyCount; i++)
{
dlg.PrintVisual(img, "Print a Image");
}
}
foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
Console.WriteLine(val);
}
Credit to Jon Skeet here: http://bytes.com/groups/net-c/266447-how-loop-each-items-enum
Your class JSON_result
does not match your JSON string. Note how the object JSON_result
is going to represent is wrapped in another property named "Venue"
.
So either create a class for that, e.g.:
Public Class Container
Public Venue As JSON_result
End Class
Public Class JSON_result
Public ID As Integer
Public Name As String
Public NameWithTown As String
Public NameWithDestination As String
Public ListingType As String
End Class
Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)
or change your JSON string to
{
"ID": 3145,
"Name": "Big Venue, Clapton",
"NameWithTown": "Big Venue, Clapton, London",
"NameWithDestination": "Big Venue, Clapton, London",
"ListingType": "A",
"Address": {
"Address1": "Clapton Raod",
"Address2": "",
"Town": "Clapton",
"County": "Greater London",
"Postcode": "PO1 1ST",
"Country": "United Kingdom",
"Region": "Europe"
},
"ResponseStatus": {
"ErrorCode": "200",
"Message": "OK"
}
}
or use e.g. a ContractResolver
to parse the JSON string.
Hey I thought this may be useful for someone who wants to replace the characters comes after the "By", for example in the text he given has by at the 20th position of his string so if you want to ignore the by you should add + 2 to the position then which will ignore the 20th position and it will replace all after coming the by it will work if you give the exact character length of the text you're gonna replace.
$variable = substr($variable, 0, strpos($variable, "By") + 2 );
By default, when a flutter app gets installed, the app name on the launcher is your Flutter project name. To change that to your desired application name on Android or iOS both, you need to change AndroidManifest.xml
and Info.plist
respectively. here is a two way to achieve this
1 By plugin
You can use a flutter rename plugin. It helps you to change your flutter project's AppName and BundleId for different platforms, currently only available for iOS, Android and macOS
You can change the bundleId and appName in the following steps
Default Usage if you dont pass -t or --target parameter it will try to rename all available platform project folders inside flutter project.
Run this command inside your flutter project root.
pub global run rename --bundleId com.onatcipli.networkUpp
pub global run rename --appname "Test App Name"
Custom Usage if you want to run commands directly (without using pub global run) ensure you add system catche bin directory to your path
rename --appname yourappname -t ios
or
pub global run rename --appname yourappname --target macOS
To target a specific platform use the "--target" option. e.g.
pub global run rename --bundleId com.example.android.app --target android
2 By manual
For Android
App Name is reflected under Android>src>main>Androidmanifest.xml The label name in the Android manifest is responsible for giving the App Name for Android Application
Go to AndroidManifest.xml
, find <application> tag
. Change its android:label
property with your desired app name.
Navigate to the : android/app/src/main/AndroidManifest.xml
The Androidmanifest.xml can now be modified. Choose the
<application
android:name="io.flutter.app.FlutterApplication"
android:label="YourAppName"
android:icon="@mipmap/ic_launcher">
For Package Name
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name">
This portion represents the actual Android file naming system. Important information like Launcher Icon and App name can be controlled here. Modify the android:label
to change the App Name only.
For iOS
For iOS, open info.plist
. Change CFBundleName (Bundle Name).
Go to the Xcode project folder and open Info.plist
for edit (in Xcode you can choose Open As > Source Code in the file context menu). All we need is to edit the value for key CFBundleName
. It’s a user-visible short name for the bundle.
Navigate to the: project/ios/Runner/Info.plist
Find the CFBundleName <key>
. This denotes the Key that holds the app name. The app name now can be changed by modifying the <String> </String>
below that.
<key>CFBundleName</key>
<string>YouAppName</string>
That’s it. By having these changes, That’s achieved, an updated application name in the launcher when an app gets installed on a device. your new app name will be displayed on your phone now.
Replace this :
$('#subscription_order_form').submit(function(e){
e.preventDefault();
});
with this:
$('#subscription_order_form').on('keydown', function(e){
if (e.which===13) e.preventDefault();
});
That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.
According to the website, sizeof()
is an alias of count()
, so they should be running the same code. Perhaps sizeof()
has a little bit of overhead because it needs to resolve it to count()
? It should be very minimal though.
I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY
We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"
--
To make content itself clickable:
HTML
<input type="checkbox" id="activate-div">
<label for="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
</label>
CSS
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked ~ label
.my-div{background-color:#000}
To make button change content:
HTML
<input type="checkbox" id="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
<label for="activate-div">
//MY BUTTON STUFF
</label>
CSS
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked +
.my-div{background-color:#000}
Hope it helps!!
Keep in mind that the previous example:
db.stuff.find( { foo: /bar/i } );
will cause every entries containing bar to match the query ( bar1, barxyz, openbar ), it could be very dangerous for a username search on a auth function ...
You may need to make it match only the search term by using the appropriate regexp syntax as:
db.stuff.find( { foo: /^bar$/i } );
See http://www.regular-expressions.info/ for syntax help on regular expressions
I created this library, may be of help to you. MyPHP client and server side library
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- include MyPHP.js -->
<script src="MyPHP.js"></script>
<!-- use MyPHP class -->
<script>
const php = new MyPHP;
php.auth = 'hashed-key';
// call a php class
const phpClass = php.fromClass('Authentication' or 'Moorexa\\Authentication', <pass aguments for constructor here>);
// call a method in that class
phpClass.method('login', <arguments>);
// you can keep chaining here...
// finally let's call this class
php.call(phpClass).then((response)=>{
// returns a promise.
});
// calling a function is quite simple also
php.call('say_hello', <arguments>).then((response)=>{
// returns a promise
});
// if your response has a script tag and you need to update your dom call just call
php.html(response);
</script>
</body>
</html>
Use the following query:
SELECT E.I_EmpID AS EMPID,
E.I_EMPCODE AS EMPCODE,
E.I_EmpName AS EMPNAME,
REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
TO_CHAR(NOD) AS NOD,
DECODE(A.I_DURATION,
'FD',
'FullDay',
'FN',
'ForeNoon',
'AN',
'AfterNoon') AS DURATION,
L.I_LeaveType AS LEAVETYPE,
REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
FROM T_COMPENSATION C
WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
AND C.I_EMPID = A.I_EMPID),
'DD-Mon-YYYY'),
' ',
'') AS WORKDATE,
A.I_REASON AS REASON,
AP.I_REJECTREASON AS REJECTREASON
FROM T_LEAVEAPPLY A
INNER JOIN T_EMPLOYEE_MS E
ON A.I_EMPID = E.I_EmpID
AND UPPER(E.I_IsActive) = 'YES'
AND A.I_STATUS = '1'
INNER JOIN T_LeaveType_MS L
ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
LEFT OUTER JOIN T_APPROVAL AP
ON A.I_REQDATE = AP.I_REQDATE
AND A.I_EMPID = AP.I_EMPID
AND AP.I_APPROVALSTATUS = '1'
WHERE E.I_EMPID <> '22'
ORDER BY A.I_REQDATE DESC
The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?
You can decode it to str with receive.decode('utf_8')
.
As noted in several blogs, strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.
$dt = date("Y-m-d");
echo date( "Y-m-d", strtotime( "$dt +1 day" ) ); // PHP: 2009-03-04
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP: 2009-03-31
Alternatively you can convert your object into a dataframe first:
df = pd.DataFrame(obj)
and then save this dataframe
in a json
file:
df.to_json(path_or_buf='df.json')
Hope this helps
Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.
fns{i}
teststruct.(fns{i})
Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.
name_as_char = 'a'
name_as_cellstr = {'a'}
<span class="txt">Some Text</span>
.txt:hover {
text-decoration: underline;
}
Try more parameters one which will surely find and if available update and not then it will create new
$save_data= Model::firstOrNew(['key1' => $key1value,'key'=>$key2value]);
//your values here
$save_data->save();
You should create a variable of the type SelectionneNonSelectionne.
struct SelectionneNonSelectionne var;
After that pass that variable to the function like
characterSelection(screen, var);
The error is caused since you are passing the type name SelectionneNonSelectionne
Try this:
#!/usr/bin/env python
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
Apart from the <h:panelGroup>
component (which comes as a bit of a surprise to me), you could use a <f:verbatim>
tag with the escape parameter set to false
to generate any mark-up you want. For example:
<f:verbatim escape="true">
<div id="blah"></div>
</f:verbatim>
Bear in mind it's a little less elegant than the panelGroup
solution, as you have to generate this for both the start and end tags if you want to wrap any of your JSF code with the div
tag.
Alternatively, all the major UI Frameworks have a div
component tag, or you could write your own.
if you are using target sdk as 23 add below code in your build.gradle
android{
useLibrary 'org.apache.http.legacy'
}
additional note here: dont try using the gradle versions of those files. they are broken (28.08.15). I tried over 5 hours to get it to work. it just doesnt. not working:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
another thing dont use:
'org.apache.httpcomponents:httpclient-android:4.3.5.1'
its referring 21 api level.
If you don't want to recreate your model from scratch, you can manually generate a migration file using the following CLI command:
sequelize migration:generate --name [name_of_your_migration]
This will generate a blank skeleton migration file. While it doesn't copy your model structure over to the file, I do find it easier and cleaner than regenerating everything. Note: make sure to run the command from the containing directory of your migrations directory; otherwise the CLI will generate a new migration dir for you
There are a lot of tools mentioned, but one more called JSON Schema inferencer for the record:
https://github.com/rnd0101/json_schema_inferencer
(it's not a library or a product, but a Python script)
With the usual Full Disclosure: I am the author.
You seem to mix up worst-case behaviour with average-case (expected) runtime. The former is indeed O(n) for hash tables in general (i.e. not using a perfect hashing) but this is rarely relevant in practice.
Any dependable hash table implementation, coupled with a half decent hash, has a retrieval performance of O(1) with a very small factor (2, in fact) in the expected case, within a very narrow margin of variance.
This is a more abstract method:
super(self.__class__,self).baz(arg)
I use a string array whenever I define an enum:
Profile.h
#pragma once
struct Profile
{
enum Value
{
Profile1,
Profile2,
};
struct StringValueImplementation
{
const wchar_t* operator[](const Profile::Value profile)
{
switch (profile)
{
case Profile::Profile1: return L"Profile1";
case Profile::Profile2: return L"Profile2";
default: ASSERT(false); return NULL;
}
}
};
static StringValueImplementation StringValue;
};
Profile.cpp
#include "Profile.h"
Profile::StringValueImplementation Profile::StringValue;
def genPrimes():
primes = [] # primes generated so far
last = 1 # last number tried
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last
<html>
<head>
<script type="text/javascript">
function test(){
var map= {'m1': 12,'m2': 13,'m3': 14,'m4': 15}
alert(map['m3']);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="test()"/>
</body>
</html>
If you have an uncommitted change (its only in your working copy) that you wish to revert to the copy in your latest commit, do the following:
git checkout filename
Assuming this is actual production code you'll be writing, then I suggest using the solution to this sort of thing that's already been solved - Apache Commons IO, specifically FileUtils.listFiles()
. It handles nested directories, filters (based on name, modification time, etc).
For example, for your regex:
Collection files = FileUtils.listFiles(
dir,
new RegexFileFilter("^(.*?)"),
DirectoryFileFilter.DIRECTORY
);
This will recursively search for files matching the ^(.*?)
regex, returning the results as a collection.
It's worth noting that this will be no faster than rolling your own code, it's doing the same thing - trawling a filesystem in Java is just slow. The difference is, the Apache Commons version will have no bugs in it.
You can opt for this example below. Hope it will help.
/** @var ClassName $object */
$object->whateverMethod() // any method defined in the class can be accessed by $object
I know this is not a cast but it can be useful sometimes.
Just pressing F5 is not always working.
why?
Because your ISP is also caching web data for you.
Solution: Force Refresh.
Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5
You then can see 200 response instead of 304 in the browser F12 developer tools network tab.
Another trick is to add question mark ?
at the end of the URL string of the requested page:
http://localhost:52199/Customers/Create?
The question mark will ensure that the browser refresh the request without caching any previous requests.
Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):
On the selector .nav-tabs > li > a:hover
add !important
to the background-color
.
.nav-tabs{_x000D_
background-color:#161616;_x000D_
}_x000D_
.tab-content{_x000D_
background-color:#303136;_x000D_
color:#fff;_x000D_
padding:5px_x000D_
}_x000D_
.nav-tabs > li > a{_x000D_
border: medium none;_x000D_
}_x000D_
.nav-tabs > li > a:hover{_x000D_
background-color: #303136 !important;_x000D_
border: medium none;_x000D_
border-radius: 0;_x000D_
color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul class="nav nav-tabs" id="myTab">_x000D_
<li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>_x000D_
<li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>_x000D_
</ul>_x000D_
<div class="tab-content">_x000D_
<div id="search" class="tab-pane fade in active">_x000D_
Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,_x000D_
butcher voluptate nisi qui._x000D_
</div>_x000D_
<div id="advanced" class="tab-pane fade">_x000D_
Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna._x000D_
</div>_x000D_
</div>
_x000D_
Apart from the usages mentioned above, console.log
can also print to the terminal in node.js
. A server created with express (for eg.) can use console.log
to write to the output logger file.
If this is in a class property you could do it in the setter:
public class FooClass
{
private string foo;
public string Foo
{
get { return foo; }
set
{
if(!string.IsNullOrEmpty(value) && value.Length>5)
{
foo=value.Substring(0,5);
}
else
foo=value;
}
}
}
I had the same problem. Check out the comment in https://gist.github.com/khernyo/4226923#comment-812526
It says:
for gradle android plugin v0.3 use "com.android.build.gradle.tasks.PackageApplication"
That should fix your problem.
You can use localStorage
for the purpose.
Steps:
Try npm install -g typescript@latest
. You can also use npm update
instead of install, without the latest modifier.
You can Set the namespace like:
{!! \Illuminate\Support\Str::words($item->description, 10,'....') !!}
The main difference is that var
variable value can change, and let
can't. If you want to have a user input data, you would use var
so the value can be changed and use let
datatype variable so the value can not be changed.
var str = "dog" // str value is "dog"
str = "cat" // str value is now "cat"
let strAnimal = "dog" // strAnimal value is "dog"
strAnimal = "cat" // Error !
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA');
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
};
}
I have searched for this a few minutes and i couldn't find any working code.
But now i finaly did it ! Take a look:
<div class="input-group" id="unified-inputs">
<input type="text" class="form-control" placeholder="MinVal" />
<input type="text" class="form-control" placeholder="MaxVal" />
</div>
And css
#unified-inputs.input-group { width: 100%; }
#unified-inputs.input-group input { width: 50% !important; }
#unified-inputs.input-group input:last-of-type { border-left: 0; }
See the Scripting Guy! Blog:
How Can I Tell Whether a Value Exists in the Registry?
They discuss doing the check on a remote computer and show that if you read a string value from the key, and if the value is Null (as opposed to Empty), the key does not exist.
With respect to using the RegRead method, if the term "key" refers to the path (or folder) where registry values are kept, and if the leaf items in that key are called "values", using WshShell.RegRead(strKey) to detect key existence (as opposed to value existance) consider the following (as observed on Windows XP):
If strKey name is not the name of an existing registry path, Err.Description reads "Invalid root in registry key"... with an Err.Number of 0x80070002.
If strKey names a registry path that exists but does not include a trailing "\" the RegRead method appears to interpret strKey as a path\value reference rather than as a simple path reference, and returns the same Err.Number but with an Err.Description of "Unable to open registry key". The term "key" in the error message appears to mean "value". This is the same result obtained when strKey references a path\value where the path exists, but the value does not exist.
In my case, the problem was solved by adding this line to the module build.gradle:
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'
Why not create a call like:
Service.GetCustomers();
that isn't async.
UPDATE tableName SET col1='000' WHERE id='3' OR id='5'
This should achieve what you'r looking for. Just add more id's. I have tested it.
I ran into this problem today. After spending most of the day trying to fix it, the only thing that ended up working was to create a new workspace and import my project into it. I hope this helps someone avoid all the trouble that I went through.
Adding to other answers already given above. If case insensivity is of any importance to you, then use Jackson. Gson does not support case insensitivity for key names, while jackson does.
Here are two related links
(No) Case sensitivity support in Gson : GSON: How to get a case insensitive element from Json?
Case sensitivity support in Jackson https://gist.github.com/electrum/1260489
matches
tries to match the expression against the entire string and implicitly add a ^
at the start and $
at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:
public static void main(String[] args) throws ParseException {
Pattern p = Pattern.compile("\\d\\d\\d");
Matcher m = p.matcher("a123b");
System.out.println(m.find());
System.out.println(m.matches());
p = Pattern.compile("^\\d\\d\\d$");
m = p.matcher("123");
System.out.println(m.find());
System.out.println(m.matches());
}
/* output:
true
false
true
true
*/
123
is a substring of a123b
so the find()
method outputs true. matches()
only 'sees' a123b
which is not the same as 123
and thus outputs false.
Aside from the particularities of how static method objects behave, there is a certain kind of beauty you can strike with them when it comes to organizing your module-level code.
# garden.py
def trim(a):
pass
def strip(a):
pass
def bunch(a, b):
pass
def _foo(foo):
pass
class powertools(object):
"""
Provides much regarded gardening power tools.
"""
@staticmethod
def answer_to_the_ultimate_question_of_life_the_universe_and_everything():
return 42
@staticmethod
def random():
return 13
@staticmethod
def promise():
return True
def _bar(baz, quux):
pass
class _Dice(object):
pass
class _6d(_Dice):
pass
class _12d(_Dice):
pass
class _Smarter:
pass
class _MagicalPonies:
pass
class _Samurai:
pass
class Foo(_6d, _Samurai):
pass
class Bar(_12d, _Smarter, _MagicalPonies):
pass
...
# tests.py
import unittest
import garden
class GardenTests(unittest.TestCase):
pass
class PowertoolsTests(unittest.TestCase):
pass
class FooTests(unittest.TestCase):
pass
class BarTests(unittest.TestCase):
pass
...
# interactive.py
from garden import trim, bunch, Foo
f = trim(Foo())
bunch(f, Foo())
...
# my_garden.py
import garden
from garden import powertools
class _Cowboy(garden._Samurai):
def hit():
return powertools.promise() and powertools.random() or 0
class Foo(_Cowboy, garden.Foo):
pass
It now becomes a bit more intuitive and self-documenting in which context certain components are meant to be used and it pans out ideally for naming distinct test cases as well as having a straightforward approach to how test modules map to actual modules under tests for purists.
I frequently find it viable to apply this approach to organizing a project's utility code. Quite often, people immediately rush and create a utils
package and end up with 9 modules of which one has 120 LOC and the rest are two dozen LOC at best. I prefer to start with this and convert it to a package and create modules only for the beasts that truly deserve them:
# utils.py
class socket(object):
@staticmethod
def check_if_port_available(port):
pass
@staticmethod
def get_free_port(port)
pass
class image(object):
@staticmethod
def to_rgb(image):
pass
@staticmethod
def to_cmyk(image):
pass
I found following program works for me
test1.sh
a=xxx
test2.sh $a
in test2.sh you use $1
to refer variable a
in test1.sh
echo $1
The output would be xxx
Shameless plug I know, but you might want to consider a jQuery plugin that I wrote:
https://github.com/benmajor/jQuery-Mobile-Events
It does not require jQuery Mobile, only jQuery.
Use:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date
that is 30 days previous including the current time.
Depending on your needs, you could also look at using ADD_MONTHS:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)
Follow the 3 step approach for a one or a few number of tags.
command: git rev-parse <tag name>
example: git rev-parse v0.1.0-Demo
example output: db57b63b77a6bae3e725cbb9025d65fa1eabcde
command: git tag -d <tag name>
example: git tag -d v0.1.0-Demo
example output: Deleted tag 'v0.1.0-Demo' (was abcde)
command: git tag -a <tag name> -m "appropriate message" <commit id>
example: git tag -a v0.1.0-full -m "renamed from v0.1.0-Demo" db57b63b77a6bae3e725cbb9025d65fa1eabcde
example output: Nothing or basically <No error>
Once the local git is ready with the tag name change, these changes can be pushed back to the origin for others to take these:
command: git push origin :<old tag name> <new tag name>
example: git push origin :v0.1.0-Demo v0.1.0-full
example output: <deleted & new tags>
I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.
In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.
I was getting the error:
> ' 0.00'
> 3 0 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 1 800 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 6 0 fast loop, delta = 10.0 weight = 0.0
> ' 0\x00.0'
> Traceback (most recent call last):
> File "measure_weight_speed.py", line 172, in start
> valueScale = float(answer_string)
> ValueError: invalid literal for float(): 0
After some research I wrote few lines of code that work in my case.
replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)
The answers in these posts helped:
Aside from other great responses, I just had to give NTFS permissions to the Oracle installation folder. (I gave read access)
When either a Bitmap object or an Image object is constructed from a file, the file remains locked for the lifetime of the object. As a result, you cannot change an image and save it back to the same file where it originated. http://support.microsoft.com/?id=814675
A generic error occurred in GDI+, JPEG Image to MemoryStream
Image.Save(..) throws a GDI+ exception because the memory stream is closed
http://alperguc.blogspot.in/2008/11/c-generic-error-occurred-in-gdi.html
EDIT:
just writing from memory...
save to an 'intermediary' memory stream, that should work
e.g. try this one - replace
Bitmap newBitmap = new Bitmap(thumbBMP);
thumbBMP.Dispose();
thumbBMP = null;
newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);
with something like:
string outputFileName = "...";
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
thumbBMP.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
user1 = pd.read_csv('dataset/1.csv', names=['Time', 'X', 'Y', 'Z'])
names parameter in read_csv function is used to define column names. If you pass extra name in this list, it will add another new column with that name with NaN values.
header=None is used to trim column names is already exists in CSV file.
Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"
There is a solution to use Web Workers (as mentioned before), because they run in separate process and are not slowed down
I've written a tiny script that can be used without changes to your code - it simply overrides functions setTimeout, clearTimeout, setInterval, clearInterval.
Just include it before all your code.
Don't forget to execute "host +" on your "home" display machine, and when you ssh to the machine you're doing "ssh -x hostname"
I had the same error and ended up solving it by upgrading my Oracle ojdbc driver to a version compatible with the Oracle database version
As the official documentation says:
body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.
When sending JSON you just have to put it in body of the option.
var options = {
uri: 'https://myurl.com',
method: 'POST',
json: true,
body: {'my_date' : 'json'}
}
request(options, myCallback)
Visual Studio 2013 no longer has separate project types for different ASP.Net features.
You must select .NET Framework 4.5 (or higher) in order to see the ASP.NET Web Application template (For ASP.NET One).
So just select Visual C# > Web > ASP.NET Web Application, then select the MVC checkbox in the next step.
Note: Make sure not to select the C# > Web > Visual Studio 2012 sub folder.
In short, a||=b
means: If a
is undefined, nil or false
, assign b
to a
. Otherwise, keep a
intact.
This problem is "best" solved by using an anonymous function to pass-in the jQuery object thusly:
The Anonymous Function Looks Like:
<script type="text/javascript">
(function($) {
// You pass-in jQuery and then alias it with the $-sign
// So your internal code doesn't change
})(jQuery);
</script>
This is JavaScript's method of implementing (poor man's) 'Dependency Injection' when used alongside things like the 'Module Pattern'.
So Your Code Would Look Like:
Of course, you might want to make some changes to your internal code now, but you get the idea.
<script type="text/javascript">
(function($) {
$.fn.pluginbutton = function(options) {
myoptions = $.extend({ left: true });
return this.each(function() {
var focus = false;
if (focus === false) {
this.hover(function() {
this.animate({ backgroundPosition: "0 -30px" }, { duration: 0 });
this.removeClass('VBfocus').addClass('VBHover');
}, function() {
this.animate({ backgroundPosition: "0 0" }, { duration: 0 });
this.removeClass('VBfocus').removeClass('VBHover');
});
}
this.mousedown(function() {
focus = true
this.animate({ backgroundPosition: "0 30px" }, { duration: 0 });
this.addClass('VBfocus').removeClass('VBHover');
}, function() {
focus = false;
this.animate({ backgroundPosition: "0 0" }, { duration: 0 });
this.removeClass('VBfocus').addClass('VBHover');
});
});
}
})(jQuery);
</script>
I'd do:
not any((x[i] != x[i+1] for i in range(0, len(x)-1)))
as any
stops searching the iterable as soon as it finds a True
condition.
Therefore, I would like to separate the string by the furthest delimiter.
I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.
SQL> WITH DATA AS
2 ( SELECT 'F/P/O' str FROM dual
3 )
4 SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
5 SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
6 FROM DATA
7 /
PART1 PART2
----- -----
F/P O
As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.
You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR
function counts back start_position number of characters from the end of string and then searches towards the beginning of string.
Paul Irish has a "Duck Punching" method (see example 2) that modifies jQuery's $.unique()
method to return unique elements of any type:
(function($){
var _old = $.unique;
$.unique = function(arr){
// do the default behavior only if we got an array of elements
if (!!arr[0].nodeType){
return _old.apply(this,arguments);
} else {
// reduce the array to contain no dupes via grep/inArray
return $.grep(arr,function(v,k){
return $.inArray(v,arr) === k;
});
}
};
})(jQuery);
Here is your code in a jsfiddle example. I have tested it and it looks fine.
http://jsfiddle.net/dimshik/9DbEP/4/
I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.
<table border="1" cellpadding="3" id="printTable">
<tbody><tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
</tbody></table>
There is a few benefits of using modules. You can use it only with Apple's framework unless module map is created. @import
is a bit similar to pre-compiling headers files when added to .pch
file which is a way to tune app the compilation process. Additionally you do not have to add libraries in the old way, using @import
is much faster and efficient in fact. If you still look for a nice reference I will highly recommend you reading this article.
You could use preg_split
instead of explode
and split on [ ]+
(one or more spaces). But I think in this case you could go with preg_match_all
and capturing:
preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];
The pattern matches a space, php
, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php
as part of a user name but really only as a command.
An alternative to capturing is the "keep" feature of PCRE. If you use \K
in the pattern, everything before it is discarded in the match:
preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];
I would use preg_match()
. I do something similar for many of my system management scripts. Here is an example:
$test = "user 12052 0.2 0.1 137184 13056 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities";
$lines = explode("\n", $test);
foreach($lines as $line){
if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
print_r($matches);
}
}
The above prints:
Array
(
[0] => .php cust1 cron
[1] => cust1
)
Array
(
[0] => .php cust3 cron
[1] => cust3
)
Array
(
[0] => .php cust4 cron
[1] => cust4
)
Array
(
[0] => .php cust89 cron
[1] => cust89
)
Array
(
[0] => .php cust435 cron
[1] => cust435
)
Array
(
[0] => .php cust16 cron
[1] => cust16
)
You can set $test
to equal the output from exec. the values you are looking for would be in the if
statement under the foreach
. $matches[1]
will have the custx value.
__pycache__
is a folder containing Python 3 bytecode compiled and ready to be executed.
I don't recommend routinely deleting these files or suppressing creation during development as it may hurt performance. Just have a recursive command ready (see below) to clean up when needed as bytecode can become stale in edge cases (see comments).
Python programmers usually ignore bytecode. Indeed __pycache__
and *.pyc
are common lines to see in .gitignore
files. Bytecode is not meant for distribution and can be disassembled using dis
module.
If you are using OS X you can easily hide all of these folders in your project by running following command from the root folder of your project.
find . -name '__pycache__' -exec chflags hidden {} \;
Replace __pycache__
with *.pyc
for Python 2.
This sets a flag on all those directories (.pyc files) telling Finder/Textmate 2 to exclude them from listings. Importantly the bytecode is there, it's just hidden.
Rerun the command if you create new modules and wish to hide new bytecode or if you delete the hidden bytecode files.
On Windows the equivalent command might be (not tested, batch script welcome):
dir * /s/b | findstr __pycache__ | attrib +h +s +r
Which is same as going through the project hiding folders using right-click > hide...
Running unit tests is one scenario (more in comments) where deleting the *.pyc
files and __pycache__
folders is indeed useful. I use the following lines in my ~/.bash_profile
and just run cl
to clean up when needed.
alias cpy='find . -name "__pycache__" -delete'
alias cpc='find . -name "*.pyc" -delete'
...
alias cl='cpy && cpc && ...'
and more lately
# pip install pyclean
pyclean .
There is an opportunity for direct access to the object of window through the document
document.defaultView == window
<input type="name" placeholder="First Name" title="First Name" />
title="First Name"
solves my proble. it worked with bootstrap.
There's a difference between an empty string (email != "") and NULL. NULL is null and an Empty string is something.
An easy fix is to just create a new branch for that commit and checkout to it: git checkout -b <branch-name> <commit-hash>
.
In this way, all the changes you made will be saved in that branch. In case you need to clean up your master branch from leftover commits be sure to run git reset --hard master
.
With this, you will be rewriting your branches so be sure not to disturb anyone with these changes. Be sure to take a look at this article for a better illustration of detached HEAD state.
DESCRIBE DATABASE NAME; you need to specify the name of the database and the results will include the data type of each attribute.
It's the ternary form of the if-else operator. The above statement basically reads like this:
if ($add_review) then {
return FALSE; //$add_review evaluated as True
} else {
return $arg //$add_review evaluated as False
}
See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/
Excel 2013 can do Count distinct in pivots. If no access to 2013, and it's a smaller amount of data, I make two copies of the raw data, and in copy b, select both columns and remove duplicates. Then make the pivot and count your column b.
You can also add the toolbar in Visual Studio to have the buttons available.
View > Toolbars > Text Editor
This worked for me
On the Zipped folder of the ADT you initially downloaded unzip and navigate to:
adt-bundle-windows-x86_64-20140702\eclipse\plugins
Copy all the executable jar files and paste them on the
C:\adt-bundle-windows-x86_64-20140702\adt-bundle-windows-x86_64-20140702\eclipse\plugins
directory (or wherever your adt is located).
Any executable jar files missing in the plugin folder will be added. You should be able to launch eclipse
JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
The answer is "no, you probably can't".
While there is stuff in there that might say who created a given object, there are a lot of "ifs" behind them. A quick (and not necessarily complete) review:
sys.objects (and thus sys.tables, sys.procedures, sys.views, etc.) has column principal_id. This value is a foreign key that relates to the list of database users, which in turn can be joined with the list of SQL (instance) logins. (All of this info can be found in further system views.)
But.
A quick check on our setup here and a cursory review of BOL indicates that this value is only set (i.e. not null) if it is "different from the schema owner". In our development system, and we've got dbo + two other schemas, everything comes up as NULL. This is probably because everyone has dbo rights within these databases.
This is using NT authentication. SQL authentication probably works much the same. Also, does everyone have and use a unique login, or are they shared? If you have employee turnover and domain (or SQL) logins get dropped, once again the data may not be there or may be incomplete.
You can look this data over (select * from sys.objects), but if principal_id is null, you are probably out of luck.
Do you have to use DataTable.Select()
? I prefer to write a linq query for this kind of thing.
var dValue= from row in myDataTable.AsEnumerable()
where row.Field<int>("A") == 1
&& row.Field<int>("B") == 2
&& row.Field<int>("C") == 3
select row.Field<string>("D");
An easy alternative that works for me is to insert the svg code into a div. This simple example uses javascript to manipulate the div innerHTML.
svg = '<svg height=150>';
svg+= '<rect height=100% fill=green /><circle cx=150 cy=75 r=60 fill=yellow />';
svg+= '<text x=150 y=95 font-size=60 text-anchor=middle fill=red>IIIIIII</text></svg>';
document.all.d1.innerHTML=svg;
_x000D_
<div id='d1' style="float:right;"></div><hr>
_x000D_
put the table inside the div to make scrollable table vertically. change overflow-y
to overflow-x
to make table scrollable horizontally. just overflow
to make table scrollable both horizontal and vertical.
<div style="overflow-y: scroll;">
<table>
...
</table>
</div>
This output from https://3v4l.org demonstrates that die and exit are functionally identical.
Easier to understand is like this:
String s = "a,b,c,d,e";
String[] sArr = s.split(",");
List<String> sList = Arrays.asList(sArr);
Actually, The save command is only on instance of Document class. That have a lot of methods and attribute. So you can use lean() function to reduce work load. Refer here. https://hashnode.com/post/why-are-mongoose-mongodb-odm-lean-queries-faster-than-normal-queries-cillvawhq0062kj53asxoyn7j
Another problem with save function, that will make conflict data in with multi-save at a same time. Model.Update will make data consistently. So to update multi items in array of document. Use your familiar programming language and try something like this, I use mongoose in that:
User.findOne({'_id': '4d2d8deff4e6c1d71fc29a07'}).lean().exec()
.then(usr =>{
if(!usr) return
usr.events.forEach( e => {
if(e && e.profile==10 ) e.handled = 0
})
User.findOneAndUpdate(
{'_id': '4d2d8deff4e6c1d71fc29a07'},
{$set: {events: usr.events}},
{new: true}
).lean().exec().then(updatedUsr => console.log(updatedUsr))
})
All of them need to be vertically aligned within the div
Aligned how? Tops of the images aligned with the top of the text?
One of the images needs to be absolute positioned within the div.
Absolutely positioned relative to the DIV? Perhaps you could sketch out what you're looking for...?
fd has described the steps for absolute positioning, as well as adjusting the display of the H1
element such that images will appear inline with it. To that, i'll add that you can align the images by use of the vertical-align
style:
#header h1 { display: inline; }
#header img { vertical-align: middle; }
...this would put the header and images together, with top edges aligned. Other alignment options exist; see the documentation. You might also find it beneficial to drop the DIV and move the images inside the H1
element - this provides semantic value to the container, and removes the need to adjust the display of the H1
:
<h1 id=header">
<img src=".." ></img>
testing...
<img src="..."></img>
</h1>
Most of the suggested solutions can cause a 1 day error depending on the time associated with each date. If you are looking for an integer number of calendar days between to dates, regardless of the time associated with each date, I have found that this works well:
return (dateOne.Value.Date - dateTwo.Value.Date).Days;
In java based regular expression you can use [\s\S]
This should get you started:
R> qplot(hwy, cty, data = mpg) +
facet_grid(. ~ manufacturer) +
theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))
See also this question: How can I manipulate the strip text of facet plots in ggplot2?
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
You can use a regex like this to extract normal url patterns.
(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})
If you need more sophisticated patterns, use a library like this.
Try this:
List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(4);
list.Add(3);
list.Add(2);
foreach (var item in list.OrderByDescending(x => x))
{
Console.WriteLine(item);
}
There's a way by which you can detect if user flipped their device to portrait mode using screen.orientation
Just use the bellow code:
screen.orientation.onchange = function () {
var type = screen.orientation.type;
if (type.match(/portrait/)) {
alert('Please flip to landscape, to use this app!');
}
}
Now, onchange
will get fired when ever user flips the device and alert will pop-up when user using portrait mode.
var test = scala.collection.mutable.Map.empty[String, String]
test("myKey") = "myValue"
Originally ZIP files were created with MS-DOS command line software from PKWare, the two programs were PKZIP.EXE and PKUNZIP.EXE. I think you can still download PKUNZIP at the PKWare site here:
http://www.pkware.com/software-pkzip/dos-compression
The actual command line could look something like this:
C:\>pkunzip c:\myzipfile.zip c:\extracttothisfolder\
You can also consider contract classes implemented with the NVI (Non Virtual Interface Pattern). For instance:
struct Contract1 : boost::noncopyable
{
virtual ~Contract1();
void f(Parameters p) {
assert(checkFPreconditions(p)&&"Contract1::f, pre-condition failure");
// + class invariants.
do_f(p);
// Check post-conditions + class invariants.
}
private:
virtual void do_f(Parameters p) = 0;
};
...
class Concrete : public Contract1, public Contract2
{
private:
virtual void do_f(Parameters p); // From contract 1.
virtual void do_g(Parameters p); // From contract 2.
};
In my opinion, no answer covers all edge cases as parsing a float should result in an error.
function parseInteger(value) {
if(value === '') return NaN;
const number = Number(value);
return Number.isInteger(number) ? number : NaN;
}
parseInteger("4") // 4
parseInteger("5aaa") // NaN
parseInteger("4.33333") // NaN
parseInteger("aaa"); // NaN
To add to the above answer (do steps 1-5).
After hours of searching and trying I found out that on a x64 server the MSOnline modules must be installed for x64, and some programs that need to run them are using the x86 PS version, so they will never find it.
[SOLUTION] What I did to solve the issue was:
Copy the folders called MSOnline
and MSOnline Extended
from the source
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\
to the folder
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\
And then in PS run the Import-Module MSOnline
, and it will automatically get the module :D
$('#id').attr('onclick', 'function()');
Right now (11 Jul 2015) this solution is still working (jquery 2.1.4); in my opinion, it is the best one to pick up.
Use the is_user_logged_in
function:
if ( is_user_logged_in() ) {
// your code for logged in user
} else {
// your code for logged out user
}
I was having the same issue. Just avoid using an emulator with SDK 27. SDK 26 works fine!
We cant connect to iPhones normally by bluetooth.it is so difficult.so,please try any other file transfers like zapya,xender.it seems good
not that hard,
if you take a look at the page source, you'll see that it uses to stream the audio via shoutcast.
this is the stream url
which returns a JSON like that:
{
"Streams": [
{
"StreamId": 3244651,
"Reliability": 92,
"Bandwidth": 64,
"HasPlaylist": false,
"MediaType": "MP3",
"Url": "http://mp3hdfm32.hala.jo:8132",
"Type": "Live"
}
]
}
i believe that's the url you need: http://mp3hdfm32.hala.jo:8132
You can pass as many arguments as you want, separating them by commas:
{{ path('_files_manage', {project: project.id, user: user.id}) }}
Short and sweet:
def remove_prefix(text, prefix):
return text[text.startswith(prefix) and len(prefix):]
The truth is that the tool can never give you a 100% certain answer, but coverage tool can give you a pretty good run for the money.
If you count with comprehensive unit test suite, than you can use test coverage tool to see exactly what lines of code were not executed during the test run. You will still need to analyze the code manually: either eliminate what you consider dead code or write test to improve test coverage.
One such tool is NCover, with open source precursor on Sourceforge. Another alternative is PartCover.
Check out this answer on stackoverflow.
With Selenium Webdriver would be something like this:
assertTrue(!isElementPresent(By.linkText("Empresas en Misión")));
First use pkill
or kill -9 <pid>
to kill the process.
Then use following userdel
command to delete user,
userdel -f cafe_fixer
According to userdel
man page:
-f, --force
This option forces the removal of the user account, even if the user is still logged in. It also forces userdel to remove the user's home directory and mail spool, even if another user uses the same home directory or if the mail spool is not owned by the specified user. If USERGROUPS_ENAB is defined to yes in /etc/login.defs and if a group exists with the same name as the deleted user, then this group will be removed, even if it is still the primary group of another user.
Edit 1: (by @Ajedi32)
Note: This option (i.e. --force
) is dangerous and may leave your system in an inconsistent state.
Edit 2: (by @socketpair)
In spite of the description about some files, this key allows removing the user while it is in use. Don't forget to chdir /
before, because this command will also remove home directory.
You can use Ctrl + M and Ctrl + P
It's called Edit.StopOutlining
I got it and explained in below:
//This table with two rows containing each row, one select in first td, and one input tags in second td and second input in third td;
<table id="tableID" class="table table-condensed">
<thead>
<tr>
<th><label>From Group</lable></th>
<th><label>To Group</lable></th>
<th><label>Level</lable></th>
</tr>
</thead>
<tbody>
<tr id="rowCount">
<td>
<select >
<option value="">select</option>
<option value="G1">G1</option>
<option value="G2">G2</option>
<option value="G3">G3</option>
<option value="G4">G4</option>
</select>
</td>
<td>
<input type="text" id="" value="" readonly="readonly" />
</td>
<td>
<input type="text" value="" readonly="readonly" />
</td>
</tr>
<tr id="rowCount">
<td>
<select >
<option value="">select</option>
<option value="G1">G1</option>
<option value="G2">G2</option>
<option value="G3">G3</option>
<option value="G4">G4</option>
</select>
</td>
<td>
<input type="text" id="" value="" readonly="readonly" />
</td>
<td>
<input type="text" value="" readonly="readonly" />
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-default generate-btn search-btn white-font border-6 no-border" id="saveDtls">Save</button>
//call on click of Save button;
$('#saveDtls').click(function(event) {
var TableData = []; //initialize array;
var data=""; //empty var;
//Here traverse and read input/select values present in each td of each tr, ;
$("table#tableID > tbody > tr").each(function(row, tr) {
TableData[row]={
"fromGroup": $('td:eq(0) select',this).val(),
"toGroup": $('td:eq(1) input',this).val(),
"level": $('td:eq(2) input',this).val()
};
//Convert tableData array to JsonData
data=JSON.stringify(TableData)
//alert('data'+data);
});
});
You need to install some packages such as Unlocker, GuestOSx, etc.
You also can get it from any ContainerAware (f.i. Controller) class from the request service:
If you are using apache as a webserver (I suppose for other
webservers the solution would be similar) and are using
virtualhosting (your urls look like this - localhost/app.php
then you can use:
$container->get('request')->server->get('DOCUMENT_ROOT');
// in controller:
$this->getRequest()->server->get('DOCUMENT_ROOT');
Else (your urls look like this - localhost/path/to/Symfony/web/app.php
:
$container->get('request')->getBasePath();
// in controller:
$this->getRequest()->getBasePath();
The following is equivalent to your second code block:
var f = function () {
//Some logic here...
};
var fr = f;
fr(pars);
If you want to actually pass a reference to a function to some other function, you can do something like this:
function fiz(x, y, z) {
return x + y + z;
}
// elsewhere...
function foo(fn, p, q, r) {
return function () {
return fn(p, q, r);
}
}
// finally...
f = foo(fiz, 1, 2, 3);
f(); // returns 6
You're almost certainly better off using a framework for this sort of thing, though.
In case you prefer to use jQuery to set the image from Base64:
$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
Not the easiest way, but still straightforward. The main difference from cgi.escape module - it still will work properly if you already have &
in your text. As you see from comments to it:
cgi.escape version
def escape(s, quote=None):
'''Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.'''
s = s.replace("&", "&") # Must be done first!
s = s.replace("<", "<")
s = s.replace(">", ">")
if quote:
s = s.replace('"', """)
return s
regex version
QUOTE_PATTERN = r"""([&<>"'])(?!(amp|lt|gt|quot|#39);)"""
def escape(word):
"""
Replaces special characters <>&"' to HTML-safe sequences.
With attention to already escaped characters.
"""
replace_with = {
'<': '>',
'>': '<',
'&': '&',
'"': '"', # should be escaped in attributes
"'": ''' # should be escaped in attributes
}
quote_pattern = re.compile(QUOTE_PATTERN)
return re.sub(quote_pattern, lambda x: replace_with[x.group(0)], word)
Here's a natural way to do it with styles:
If your AppTheme
is inherited from Theme.MaterialComponents
, then:
<style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
<item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
<item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>
<style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">#f00</item>
</style>
<style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">#00f</item>
</style>
If your AppTheme
is inherited from Theme.AppCompat
:
<style name="AlertDialogTheme" parent="ThemeOverlay.AppCompat.Dialog.Alert">
<item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
<item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>
<style name="NegativeButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">#f00</item>
</style>
<style name="PositiveButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">#00f</item>
</style>
Use your AlertDialogTheme
in your AppTheme
<item name="alertDialogTheme">@style/AlertDialogTheme</item>
or in constructor
androidx.appcompat.app.AlertDialog.Builder(context, R.style.AlertDialogTheme)
An HttpOnly
cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly
attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly
.
Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly
by just XSS and still have access to the cookie via JS and thus make the HttpOnly
on your cookie completely useless.
In addition to AIXroot's answer, there is also a logout function that can be used to write a utmp logout record. So if you don't have any processes for user xxxx, but userdel says "userdel: account xxxx is currently in use", you can add a logout record manually. Create a file logout.c like this:
#include <stdio.h>
#include <utmp.h>
int main(int argc, char *argv[])
{
if (argc == 2) {
return logout(argv[1]);
}
else {
fprintf(stderr, "Usage: logout device\n");
return 1;
}
}
Compile it:
gcc -lutil -o logout logout.c
And then run it for whatever it says in the output of finger's "On since" line(s) as a parameter:
# finger xxxx
Login: xxxx Name:
Directory: /home/xxxx Shell: /bin/bash
On since Sun Feb 26 11:06 (GMT) on 127.0.0.1:6 (messages off) from 127.0.0.1
On since Fri Feb 24 16:53 (GMT) on pts/6, idle 3 days 17:16, from 127.0.0.1
Last login Mon Feb 10 14:45 (GMT) on pts/11 from somehost.example.com
Mail last read Sun Feb 27 08:44 2014 (GMT)
No Plan.
# userdel xxxx
userdel: account `xxxx' is currently in use.
# ./logout 127.0.0.1:6
# ./logout pts/6
# userdel xxxx
no crontab for xxxx
I created a small library that does this, no code change needed other than replacing your wrapping view and import of TextInput:
import { Form, TextInput } from 'react-native-autofocus'
export default () => (
<Form>
<TextInput placeholder="test" />
<TextInput placeholder="test 2" />
</Form>
)
https://github.com/zackify/react-native-autofocus
Explained in detail here: https://zach.codes/autofocus-inputs-in-react-native/
NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];
or use
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
Just an upgrade from above answers
function strsearch($findme, $source){
if(is_array($findme)){
if(str_replace($findme, '', $source) != $source){
return true;
}
}else{
if(strpos($source,$findme)){
return true;
}
}
return false;
}
You could also create an ssh tunnel.
docker-compose.yml
:
---
version: '2'
services:
kibana:
image: "kibana:4.5.1"
links:
- elasticsearch
volumes:
- ./config/kibana:/opt/kibana/config:ro
elasticsearch:
build:
context: .
dockerfile: ./docker/Dockerfile.tunnel
entrypoint: ssh
command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"
docker/Dockerfile.tunnel
:
FROM buildpack-deps:jessie
RUN apt-get update && \
DEBIAN_FRONTEND=noninteractive \
apt-get -y install ssh && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
chmod 600 /root/.ssh/config && \
chown $USER:$USER -R /root/.ssh
config/ssh/config
:
# Elasticsearch Server
Host elasticsearch
HostName jump.host.czerasz.com
User czerasz
ForwardAgent yes
IdentityFile ~/.ssh/id_rsa
This way the elasticsearch
has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.
Could you use online services like this ?
Update: (as per request)
Google chrome will do this also http://cristian-radulescu.ro/article/pretty-print-javascript-with-google-chrome.html
The following steps are needed to start multi dexing:
Add android-support-multidex.jar to your project. The jar can be found in your Android SDK folder /sdk/extras/android/support/multidex/library/libs
Now you either let your apps application class extend MultiDexApplication
public class MyApplication extends MultiDexApplication
or you override attachBaseContext like this:
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
I used the override approach because that does not mess with the class hierarchy of your application class.
Now your app is ready to use multi dex. The next step is to convince gradle to build a multi dexed apk. The build tools team is working on making this easier, but for the moment you need to add the following to the android part of your apps build.gradle
dexOptions {
preDexLibraries = false
}
And the following to the general part of your apps build.gradle
afterEvaluate {
tasks.matching {
it.name.startsWith('dex')
}.each { dx ->
if (dx.additionalParameters == null) {
dx.additionalParameters = ['--multi-dex']
} else {
dx.additionalParameters += '--multi-dex'
}
}
}
More info can be found on Alex Lipovs blog.
An input type="image"
only defines that image as the submit button and not as an input that can carry over a value to the server.
To ignore all binary results from grep
grep -Ri "pattern" * | awk '{if($1 != "Binary") print $0}'
The awk part will filter out all the Binary file foo matches lines
None of the solutions in Intellij is as elegant (or useful) as in Eclipse. What we need is feature request to the intellij so that we can add a hook (what actions to perform) when the IDE autosaves.
In Eclipse we can add "post-save" actions, such as organize imports and format the class. Yes you have to do a "save" or ctrl-s but the hook is very convenient.
I came here to learn how to create a function pointer (not a method pointer) from a method but none of the answers here provide a solution. Here is what I came up with:
template <class T> struct MethodHelper;
template <class C, class Ret, class... Args> struct MethodHelper<Ret (C::*)(Args...)> {
using T = Ret (C::*)(Args...);
template <T m> static Ret call(C* object, Args... args) {
return (object->*m)(args...);
}
};
#define METHOD_FP(m) MethodHelper<decltype(m)>::call<m>
So for your example you would now do:
Dog dog;
using BarkFunction = void (*)(Dog*);
BarkFunction bark = METHOD_FP(&Dog::bark);
(*bark)(&dog); // or simply bark(&dog)
Edit:
Using C++17, there is an even better solution:
template <auto m> struct MethodHelper;
template <class C, class Ret, class... Args, Ret (C::*m)(Args...)> struct MethodHelper<m> {
static Ret call(C* object, Args... args) {
return (object->*m)(args...);
}
};
which can be used directly without the macro:
Dog dog;
using BarkFunction = void (*)(Dog*);
BarkFunction bark = MethodHelper<&Dog::bark>::call;
(*bark)(&dog); // or simply bark(&dog)
For methods with modifiers like const
you might need some more specializations like:
template <class C, class Ret, class... Args, Ret (C::*m)(Args...) const> struct MethodHelper<m> {
static Ret call(const C* object, Args... args) {
return (object->*m)(args...);
}
};
if you want to override that onConfigurationChanged method and still want it to do the basic stuff then consider using super.onConfigyrationChanged() as the first statement in the overriden method.
Grid-ML Schema Viewer is great for searching and visualizing XML Schemas: https://gridml.com/xml-schema-viewer. I find it better than other tools when it comes to large schemas or when browsing through a diagram is not feasible. The tool also allows you to copy the XPath or JSON path of the selection item.
Simply doing the vim "save and quit" command :wq
should do the trick.
In order to have Git open it in another editor, you need to change the Git core.editor
setting to a command which runs the editor you want.
git config --global core.editor "command to start sublime text 2"
Your Intellij IDEA plugin and the Kotlin runtime/compiler that you use in the project need to match. For example if IDE plugin is Beta 1, but your Gradle/Maven project using M12, you'll have issues exactly as you described. So check that everything lines up.
If you still have issues, with some older plugins you need to clear the caches in Intellij IDEA (file menu, Clear Caches and Restart, select option to restart).
Do not set a height on the .collapse
tag. It affects the animation, if the height is overridden with css; it will not animate correctly.
"tail" is command to display the last part of a file, using proper available switches helps us to get more specific output. the most used switch for me is -n and -f
SYNOPSIS
tail [-F | -f | -r] [-q] [-b number | -c number | -n number] [file ...]
Here
-n number : The location is number lines.
-f : The -f option causes tail to not stop when end of file is reached, but rather to wait for additional data to be appended to the input. The -f option is ignored if the standard input is a pipe, but not if it is a FIFO.
Retrieve last 100 lines logs
To get last static 100 lines
tail -n 100 <file path>
To get real time last 100 lines
tail -f -n 100 <file path>
To do it in a generic JPA way using getter annotations, the example below works for me with Hibernate 3.5.4 and Oracle 11g. Note that the mapped getter and setter (getOpenedYnString
and setOpenedYnString
) are private methods. Those methods provide the mapping but all programmatic access to the class is using the getOpenedYn
and setOpenedYn
methods.
private String openedYn;
@Transient
public Boolean getOpenedYn() {
return toBoolean(openedYn);
}
public void setOpenedYn(Boolean openedYn) {
setOpenedYnString(toYesNo(openedYn));
}
@Column(name = "OPENED_YN", length = 1)
private String getOpenedYnString() {
return openedYn;
}
private void setOpenedYnString(String openedYn) {
this.openedYn = openedYn;
}
Here's the util class with static methods toYesNo
and toBoolean
:
public class JpaUtil {
private static final String NO = "N";
private static final String YES = "Y";
public static String toYesNo(Boolean value) {
if (value == null)
return null;
else if (value)
return YES;
else
return NO;
}
public static Boolean toBoolean(String yesNo) {
if (yesNo == null)
return null;
else if (YES.equals(yesNo))
return true;
else if (NO.equals(yesNo))
return false;
else
throw new RuntimeException("unexpected yes/no value:" + yesNo);
}
}
Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.
Also based on your markup your selector is wrong. it should be #advisersDiv
function fadeIn() {
$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
setTimeout(fadeOut,1); //<-- Provide any delay here
};
function fadeOut() {
$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
type: 'POST',_x000D_
url: '/form/',_x000D_
data: Data,_x000D_
success: function(data) { alert('data: ' + data); },_x000D_
contentType: "application/json",_x000D_
dataType: 'json'_x000D_
});
_x000D_
Have you changed your Windows password recently, or at least the one you use to connect to your proxy?
This was my problem, and git status
couldn't help me. I had to change my login credentials in the ".git/config" file to get past this error.
/* Current time */
select now();
/* Epoch from current time;
Epoch is number of seconds since 1970-01-01 00:00:00+00 */
select extract(epoch from now());
/* Get back time from epoch */
-- Option 1 - use to_timestamp function
select to_timestamp( extract(epoch from now()));
-- Option 2 - add seconds to 'epoch'
select timestamp with time zone 'epoch'
+ extract(epoch from now()) * interval '1 second';
/* Cast timestamp to date */
-- Based on Option 1
select to_timestamp(extract(epoch from now()))::date;
-- Based on Option 2
select (timestamp with time zone 'epoch'
+ extract(epoch from now()) * interval '1 second')::date;
/* For column epoch_ms */
select to_timestamp(extract(epoch epoch_ms))::date;
Fixed version of java's Integer.parseInt(text) to work with negative numbers:
public static int parseInt(String binary) {
if (binary.length() < Integer.SIZE) return Integer.parseInt(binary, 2);
int result = 0;
byte[] bytes = binary.getBytes();
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] == 49) {
result = result | (1 << (bytes.length - 1 - i));
}
}
return result;
}
You did not mention what the command was that you were trying to run that produced the error message. However, the bottom line problem is that you are trying to run and/or install 32-bit (i686) packages on a 64-bit (x86_64) system which is not a good idea. For example, if you were trying to run the 32-bit version of Perl on a 64-bit system, the result would be something like
perl: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory
If you still want to use the rpm command to install the 32-bit versions of glibc and glibc-common on your system, then you need to know that you must install both of the packages at the same time and as a single command because they are dependencies of each other. The command to run in your case would be:
rpm -Uvh glibc-2.12-1.80.el6.i686.rpm glibc-common-2.12-1.80.el6.i686.rpm
With bootstrap you can use
<a href="#/new-page.html" class="btn btn-primary">
Click
</a>
[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
import subprocess
p = subprocess.run(["ls", "-ltr"], capture_output=True)
print(p.stdout.decode(), p.stderr.decode())
Alternatively, in situations where I want to return a number of things from a method I will sometimes use a callback mechanism instead of a container. This works very well in situations where I cannot specify ahead of time just how many objects will be generated.
With your particular problem, it would look something like this:
public class ResultsConsumer implements ResultsGenerator.ResultsCallback
{
public void handleResult( String name, Object value )
{
...
}
}
public class ResultsGenerator
{
public interface ResultsCallback
{
void handleResult( String aName, Object aValue );
}
public void generateResults( ResultsGenerator.ResultsCallback aCallback )
{
Object value = null;
String name = null;
...
aCallback.handleResult( name, value );
}
}
CSS
select.inpSelect {
//Remove original arrows
-webkit-appearance: none;
//Use png at assets/selectArrow.png for the arrow on the right
//Set the background color to a BadAss Green color
background: url(assets/selectArrow.png) no-repeat right #BADA55;
}
This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:
The client have two network cards,a wireless one and a normal one.
The ping to server can be succeed.However telnet serverAddress 3306
would fail.
And would complain
Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)
when try to connect to server.So I forbidden the normal network adapters.
And tried telnet serverAddress 3306
it works.And then it work when connect to MySQL server.
I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)
I think you should define your origins
for client side as bellow:
//server.js_x000D_
const socket = require('socket.io');_x000D_
const app = require('express')();_x000D_
const server = app.listen('port');_x000D_
_x000D_
const io = socket().attach(server);_x000D_
io.origins("your_domain:port www.your_domain:port your_IP:port your_domain:*")_x000D_
_x000D_
io.on('connection', (socket) => {_x000D_
console.log('connected a new client');_x000D_
});_x000D_
_x000D_
//client.js_x000D_
var socket = io('ws://:port');
_x000D_
You asked why it happens, let's see:
The official language specificaion dictates a call to the internal [[GetValue]]
method. Your .attr
returns undefined and you're trying to access its length.
If Type(V) is not Reference, return V.
This is true, since undefined is not a reference (alongside null, number, string and boolean)
Let base be the result of calling GetBase(V).
This gets the undefined
part of myVar.length
.
If IsUnresolvableReference(V), throw a ReferenceError exception.
This is not true, since it is resolvable and it resolves to undefined.
If IsPropertyReference(V), then
This happens since it's a property reference with the .
syntax.
Now it tries to convert undefined
to a function which results in a TypeError.
As noted by S.Lott,
Variable set outside init belong to the class. They're shared by all instances.
Variables created inside init (and all other method functions) and prefaced with self. belong to the object instance.
However, Note that class variables can be accessed via self.<var> until they are masked by an object variable with a similar name This means that reading self.<var> before assigning it a value will return the value of Class.<var> but afterwards it will return obj.<var> . Here is an example
In [20]: class MyClass:
...: elem = 123
...:
...: def update(self,i):
...: self.elem=i
...: def print(self):
...: print (MyClass.elem, self.elem)
...:
...: c1 = MyClass()
...: c2 = MyClass()
...: c1.print()
...: c2.print()
123 123
123 123
In [21]: c1.update(1)
...: c2.update(42)
...: c1.print()
...: c2.print()
123 1
123 42
In [22]: MyClass.elem=22
...: c1.print()
...: c2.print()
22 1
22 42
Second note: Consider slots. They may offer a better way to implement object variables.
Extract the jar, and put it somewhere in your Java project (usually under a "lib" subdirectory).
Right click the project, open its preferences, go for Java build path, and then the Libraries tab. You can add the library there with "add a jar".
If your jar is not open source, you may want to store it elsewhere and connect to it as an external jar.
A full-fledged component can be implemented only if you redefine the API (change the methods of object ' history ') I will share the class just written. Tested on Chrome and Mozilla Support only HTML5 and ECMAScript5-6
class HistoryNavigation {
static init()
{
if(HistoryNavigation.is_init===true){
return;
}
HistoryNavigation.is_init=true;
let history_stack=[];
let n=0;
let current_state={timestamp:Date.now()+n};
n++;
let init_HNState;
if(history.state!==null){
current_state=history.state.HNState;
history_stack=history.state.HNState.history_stack;
init_HNState=history.state.HNState;
} else {
init_HNState={timestamp:current_state.timestamp,history_stack};
}
let listenerPushState=function(params){
params=Object.assign({state:null},params);
params.state=params.state!==null?Object.assign({},params.state):{};
let h_state={ timestamp:Date.now()+n};
n++;
let key = history_stack.indexOf(current_state.timestamp);
key=key+1;
history_stack.splice(key);
history_stack.push(h_state.timestamp);
h_state.history_stack=history_stack;
params.state.HNState=h_state;
current_state=h_state;
return params;
};
let listenerReplaceState=function(params){
params=Object.assign({state:null},params);
params.state=params.state!==null?Object.assign({},params.state):null;
let h_state=Object.assign({},current_state);
h_state.history_stack=history_stack;
params.state.HNState=h_state;
return params;
};
let desc=Object.getOwnPropertyDescriptors(History.prototype);
delete desc.constructor;
Object.defineProperties(History.prototype,{
replaceState:Object.assign({},desc.replaceState,{
value:function(state,title,url){
let params={state,title,url};
HistoryNavigation.dispatchEvent('history.state.replace',params);
params=Object.assign({state,title,url},params);
params=listenerReplaceState(params);
desc.replaceState.value.call(this,params.state,params.title,params.url);
}
}),
pushState:Object.assign({},desc.pushState,{
value:function(state,title,url){
let params={state,title,url};
HistoryNavigation.dispatchEvent('history.state.push',params);
params=Object.assign({state,title,url},params);
params=listenerPushState(params);
return desc.pushState.value.call(this, params.state, params.title, params.url);
}
})
});
HistoryNavigation.addEventListener('popstate',function(event){
let HNState;
if(event.state==null){
HNState=init_HNState;
} else {
HNState=event.state.HNState;
}
let key_prev=history_stack.indexOf(current_state.timestamp);
let key_state=history_stack.indexOf(HNState.timestamp);
let delta=key_state-key_prev;
let params={delta,event,state:Object.assign({},event.state)};
delete params.state.HNState;
HNState.history_stack=history_stack;
if(event.state!==null){
event.state.HNState=HNState;
}
current_state=HNState;
HistoryNavigation.dispatchEvent('history.go',params);
});
}
static addEventListener(...arg)
{
window.addEventListener(...arg);
}
static removeEventListener(...arg)
{
window.removeEventListener(...arg);
}
static dispatchEvent(event,params)
{
if(!(event instanceof Event)){
event=new Event(event,{cancelable:true});
}
event.params=params;
window.dispatchEvent(event);
};
}
HistoryNavigation.init();
// exemple
HistoryNavigation.addEventListener('popstate',function(event){
console.log('Will not start because they blocked the work');
});
HistoryNavigation.addEventListener('history.go',function(event){
event.params.event.stopImmediatePropagation();// blocked popstate listeners
console.log(event.params);
// back or forward - see event.params.delta
});
HistoryNavigation.addEventListener('history.state.push',function(event){
console.log(event);
});
HistoryNavigation.addEventListener('history.state.replace',function(event){
console.log(event);
});
history.pushState({h:'hello'},'','');
history.pushState({h:'hello2'},'','');
history.pushState({h:'hello3'},'','');
history.back();
```
One of the values you pass on to Ancestors
becomes None
at some point, it says, so check if otu
, tree
, tree[otu]
or tree[otu][0]
are None
in the beginning of the function instead of only checking tree[otu][0][0] == None
. But perhaps you should reconsider your path of action and the datatype in question to see if you could improve the structure somewhat.