You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
Though this does not directly answer the question, but I think it is a good alternative to avoid the question altogether.
To avoid all the autoload_paths
or eager_load_paths
hassle, create a "lib" or a "misc" directory under "app" directory. Place codes as you would normally do in there, and Rails will load files just like how it will load (and reload) model files.
You could also use find_by_sql
# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
I just came across a similar problem. Try
require './st.rb'
This should do the trick.
As of ruby 2.3.0
class Check
def self.first_method
second_method
end
private
def self.second_method
puts "well I executed"
end
end
Check.first_method
#=> well I executed
When I've done this, rather than fiddling the original migration, I create a new one with just the add column in the up section and a drop column in the down section.
You can change the original and rerun it if you migrate down between, but in this case I think that's made a migration that won't work properly.
As currently posted, you're adding the column and then creating the table.
If you change the order it might work. Or, as you're modifying an existing migration, just add it to the create table instead of doing a separate add column.
IRB has a setting for this awful "feature", which you can customize.
Create a file called ~/.irbrc
that includes the following line:
IRB.conf[:BACK_TRACE_LIMIT] = 100
This will allow you to see 100 stack frames in irb
, at least. I haven't been able to find an equivalent setting for the non-interactive runtime.
Detailed information about IRB customization can be found in the Pickaxe book.
Instanceof works if you don't depend on specific classes, but also keep in mind that you can have nulls in the list, so obj.getClass() will fail, but instanceof always returns false on null.
Setting the timeout in the web.xml is the correct way to set the timeout.
When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
Here's something which might be useful. Selecting the entire column based on a row containing data, in this case i am using 5th row:
Dim lColumn As Long
lColumn = ActiveSheet.Cells(5, Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
Assuming your page size is 20 record, and you wanna get page number 2, here is how you would do it:
SQL Server, Oracle:
SELECT * -- <-- pick any columns here from your table, if you wanna exclude the RowNumber
FROM (SELECT ROW_NUMBER OVER(ORDER BY ID DESC) RowNumber, *
FROM Reflow
WHERE ReflowProcessID = somenumber) t
WHERE RowNumber >= 20 AND RowNumber <= 40
MySQL:
SELECT *
FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 20 OFFSET 20
I found the solution for this problem here. Don't forget to allow verb OPTIONS on IIS app service handler.
Works fine. Thank you André Pedroso. :-)
PowerShell 3 supports this out of the box now.
If you're stuck on PowerShell 2, you basically have to use the legacy net use
command (as suggested earlier).
Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt
). You can check where you are spooling by issuing spool
command.
I encountered the same issue on Mac OSX, using a ZSH shell: in this case there is no -t
option for mv
, so I had to find another solution.
However the following command succeeded:
find .* * -maxdepth 0 -not -path '.git' -not -path '.backup' -exec mv '{}' .backup \;
The secret was to quote the braces. No need for the braces to be at the end of the exec
command.
I tested under Ubuntu 14.04 (with BASH and ZSH shells), it works the same.
However, when using the +
sign, it seems indeed that it has to be at the end of the exec
command.
you can use this function to download file from base64.
function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}
This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.
i hope this will help of you thanks
Give full path as input. Avoid relative paths.
return File.Exists(FinalPath);
I came across this question, and the answers here didn't work for me; i couldn't figure out why i can't login and got the above error.
It turns out that postgresql saves usernames lowercase, but during authentication it uses both upper- and lowercase.
CREATE USER myNewUser WITH PASSWORD 'passWord';
will create a user with the username 'mynewuser' and password 'passWord'.
This means you have to authenticate with 'mynewuser', and not with 'myNewUser'. For a newbie in pgsql like me, this was confusing. I hope it helps others who run into this problem.
tl;dr What to do in modern (2018) times? Assume tel:
is supported, use it and forget about anything else.
The tel:
URI scheme RFC5431 (as well as sms:
but also feed:
, maps:
, youtube:
and others) is handled by protocol handlers (as mailto:
and http:
are).
They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto:
protocol handler with same meaning and behaviour of tel:
but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.
What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler()
and related functions) simplifying also the check for their support through isProtocolHandlerRegistered()
function.
There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).
In general what I suggest is:
tel:
is supported (yes, it's not true for very old devices but IMO you can ignore them).tel:
isn't supported then change links to use callto:
and repeat check desctibed in 3.tel:
and callto:
aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href
with javascript:void(0)
and (if number isn't repeated in text span) putting, telephone number in title
. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto:
and tel:
.Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:
tel:
is supported.tel:
with callto:
.tel:
or leave it as is (assuming there are good chances Skype is installed).Code for Simple circle
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="#9F2200"/>
<stroke android:width="2dp" android:color="#fff" />
<size android:width="80dp" android:height="80dp"/>
</shape>
Nginx operates within the directory, so if you can't cd
to that directory from the nginx user then it will fail (as does the stat
command in your log). Make sure the www-user
can cd
all the way to the /username/test/static
. You can confirm that the stat
will fail or succeed by running
sudo -u www-data stat /username/test/static
In your case probably the /username
directory is the issue here. Usually www-data
does not have permissions to cd
to other users home directories.
The best solution in that case would be to add www-data
to username
group:
gpasswd -a www-data username
and make sure that username
group can enter all directories along the path:
chmod g+x /username && chmod g+x /username/test && chmod g+x /username/test/static
For your changes to work, restart nginx
nginx -s reload
Type in command line :
$ export http_proxy=http://proxy_host:proxy_port
for authenticated proxy,
$ export http_proxy=http://username:password@proxy_host:proxy_port
and then run
$ wget fileurl
for https, just use https_proxy instead of http_proxy. You could also put these lines in your ~/.bashrc file so that you don't need to execute this everytime.
My solution as SymLinks did not work on my server so I used an If in my PHP.
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
$redirect = str_replace("www.", "", curPageURL());
$remove_http_root = str_replace('http://', '', $redirect);
$split_url_array = explode('/', $remove_http_root );
if($split_url_array[0] == "olddomain.com"){
header("Location: http://www.newdomain.com/$split_url_array[1]");
die();
}
System apps installed /system/app/ or /system/priv-app. Other apps can be installed in /data/app or /data/preload/.
Connect to your android mobile with USB and run the following commands. You will see all the installed packages.
$ adb shell
$ pm list packages -f
Try like this
String sql = "SELECT t FROM table t";
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();
It should work
UPDATE*
You can also try like this
query.setMaxResults(1).getResultList();
You can use white-space: nowrap;
to define this behaviour:
// HTML:
.nowrap {_x000D_
white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
<span class="nowrap">How do I wrap this line of text</span>_x000D_
<span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
</p>
_x000D_
// CSS:
.nowrap {
white-space: nowrap ;
}
if you have API level smaller than 23 than you must use it this way. it worked for me declare this under v21/style.
<item name="colorPrimaryDark" tools:targetApi="23">@color/colorPrimary</item>
<item name="android:windowLightStatusBar" tools:targetApi="23">true</item>
Source: My Blog Post (better formatting)
Example
numbers = [1,2,3]
letters = 'abcd'
zip(numbers, letters)
# [(1, 'a'), (2, 'b'), (3, 'c')]
Zero or more iterables [1] (ex. list, string, tuple, dictionary)
1st tuple = (element_1 of numbers, element_1 of letters)
2nd tuple = (e_2 numbers, e_2 letters)
…
n-th tuple = (e_n numbers, e_n letters)
i
th tuple = (element_i arg1, element_i arg2…, element_i argn
)1) Empty String: len(str)= 0 = no tuples
2) Single String: len(str) == 2 tuples with len(args) == 1 element(s)
zip()
# []
zip('')
# []
zip('hi')
# [('h',), ('i',)]
1. Build a dictionary [2] out of two lists
keys = ["drink","band","food"]
values = ["La Croix", "Daft Punk", "Sushi"]
my_favorite = dict( zip(keys, values) )
my_favorite["drink"]
# 'La Croix'
my_faves = dict()
for i in range(len(keys)):
my_faves[keys[i]] = values[i]
zip
is an elegant, clear, & concise solution2. Print columns in a table
"*" [3] is called "unpacking": f(*[arg1,arg2,arg3]) == f(arg1, arg2, arg3)
student_grades = [
[ 'Morty' , 1 , "B" ],
[ 'Rick' , 4 , "A" ],
[ 'Jerry' , 3 , "M" ],
[ 'Kramer' , 0 , "F" ],
]
row_1 = student_grades[0]
print row_1
# ['Morty', 1, 'B']
columns = zip(*student_grades)
names = columns[0]
print names
# ('Morty', 'Rick', 'Jerry', 'Kramer')
zip(*args)
is called “unzipping” because it has the inverse effect of zip
numbers = (1,2,3)
letters = ('a','b','c')
zipped = zip(numbers, letters)
print zipped
# [(1, 'a'), (2, 'b'), (3, 'c')]
unzipped = zip(*zipped)
print unzipped
# [(1, 2, 3), ('a', 'b', 'c')]
unzipped
: tuple_1 = e1 of each zipped tuple. tuple_2 = e2 of each zipped
*
Code:
# foo - function, returns sum of two arguments
def foo(x,y):
return x + y
print foo(3,4)
# 7
numbers = [1,2]
print foo(numbers)
# TypeError: foo() takes exactly 2 arguments (1 given)
print foo(*numbers)
# 3
*
took numbers
(1 arg) and “unpacked” its’ 2 elements into 2 args
Here an approach to have count distinct over multiple columns. Let's have some data:
data = {'CLIENT_CODE':[1,1,2,1,2,2,3],
'YEAR_MONTH':[201301,201301,201301,201302,201302,201302,201302],
'PRODUCT_CODE': [100,150,220,400,50,80,100]
}
table = pd.DataFrame(data)
table
CLIENT_CODE YEAR_MONTH PRODUCT_CODE
0 1 201301 100
1 1 201301 150
2 2 201301 220
3 1 201302 400
4 2 201302 50
5 2 201302 80
6 3 201302 100
Now, list the columns of interest and use groupby in a slightly modified syntax:
columns = ['YEAR_MONTH', 'PRODUCT_CODE']
table[columns].groupby(table['CLIENT_CODE']).nunique()
We obtain:
YEAR_MONTH PRODUCT_CODE CLIENT_CODE
1 2 3
2 2 3
3 1 1
See this post to find difference between range and xrange:
To quote:
range
returns exactly what you think: a list of consecutive integers, of a defined length beginning with 0.xrange
, however, returns an "xrange object", which acts a great deal like an iterator
Set the tabindex of the canvas element to 1 or something like this
<canvas tabindex='1'></canvas>
It's an old trick to make any element focusable
Using android:singleLine="true"
is deprecated.
Just add your input type and set maxline to 1 and everything will work fine
android:inputType="text"
android:maxLines="1"
You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:
SELECT DISTINCT
coaches.id,
people.*,
users.*,
coaches.*
FROM "COACHES"
INNER JOIN people ON people.id = coaches.person_id
INNER JOIN users ON coaches.person_id = users.person_id
LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
rownum <= 25
It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.
Method overriding is made possible by dynamic dispatching, meaning that the declared type of an object doesn't determine its behavior, but rather its runtime type:
Animal lassie = new Dog();
lassie.speak(); // outputs "woof!"
Animal kermit = new Frog();
kermit.speak(); // outputs "ribbit!"
Even though both lassie
and kermit
are declared as objects of type Animal
, their behavior (method .speak()
) varies because dynamic dispatching will only bind the method call .speak()
to an implementation at run time - not at compile time.
Now, here's where the static
keyword starts to make sense: the word "static" is an antonym for "dynamic". So the reason why you can't override static methods is because there is no dynamic dispatching on static members - because static literally means "not dynamic". If they dispatched dynamically (and thus could be overriden) the static
keyword just wouldn't make sense anymore.
Add InitialValue="0"
in Required field validator tag
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID"
Display="Dynamic" ValidationGroup="g1" runat="server"
ControlToValidate="ControlID"
InitialValue="0" ErrorMessage="ErrorMessage">
</asp:RequiredFieldValidator>
A simple example from the book Dive Into Python works ok for me, this is the download link, the example is fileinfo.py. Don't know if it's the best, but it can do the basic job.
The entire book is available online here.
This is a complete procedure to transfer database and logins from an istance to a new one, scripting logins and relocating datafile and log files on the destination. Everything using metascripts.
Sorry for the off-site procedure but scripts are very long. You have to:
- Script logins with original SID and HASHED password
- Create script to backup database using metascripts
- Create script to restore database passing relocate parameters using again metascripts
- Run the generated scripts on source and destination instance.
See details and download scripts following the link above.
XSLT 2.0 has upper-case()
and lower-case()
functions. In case of XSLT 1.0, you can use translate()
:
<xsl:value-of select="translate("xslt", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")" />
This issue happen because of few jars are getting references from other jar and reference jar is missing .
Example : Spring framework
Description Resource Path Location Type
The project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project SpringBatch Unknown Java Problem
In this case "org.springframework.beans.factory.annotation.Autowire" is missing.
Spring-bean.jar is missing
Once you add dependency in your class path issue will resolve.
Normally you can configure Environment variables in Global properties in Configure System.
However for dynamic variables with shell substitution, you may want to create a script file in Jenkins HOME dir and execute it during the build. The SSH access is required. For example.
sudo su - jenkins
or sudo su - jenkins -s /bin/bash
Create a shell script, e.g.:
echo 'export VM_NAME="$JOB_NAME"' > ~/load_env.sh
echo "export AOEU=$(echo aoeu)" >> ~/load_env.sh
chmod 750 ~/load_env.sh
In Jenkins Build (Execute shell), invoke the script and its variables before anything else, e.g.
source ~/load_env.sh
CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)
I guess this is what you want:
l = range(100)
index = 0
for i in l:
print i,
try:
print l.pop(index+1),
print l.pop(index+1)
except:
pass
index += 1
It is quite handy to code when the number of item to be popped is a run time decision. But it runs with very a bad efficiency and the code is hard to maintain.
In my case, it was not using a DataTemplate for the ItemsControl.
Old:
<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
<StackPanel Orientation="Horizontal">
<TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
<Label Content="{Binding Path=Property2}"/>
</StackPanel>
</ItemsControl>
New:
<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
<Label Content="{Binding Path=Property2}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
At least on firefox, you can set a "title" attribute on the option tag:
<option value="" title="Tooltip">Some option</option>
In your own (base) class, willSet
and didSet
are quite reduntant , as you could instead define a calculated property (i.e get- and set- methods) that access a _propertyVariable
and does the desired pre- and post- prosessing.
If, however, you override a class where the property is already defined, then the willSet
and didSet
are useful and not redundant!
I had the same issue while working with web services. Here Microsoft has a (long) walk-thru showing you how to install stuff on the client to basically say that your self-signed cert is ok. In the end, I just spent the $30 and bought a full certificate from Godaddy.com.
P.S. I know that you can code around the error message but we didn't want to do that for testing reasons.
You should use a KeyGenerator to generate the Key,
AES key lengths are 128, 192, and 256 bit depending on the cipher you want to use.
Take a look at the tutorial here
Here is the code for Password Based Encryption, this has the password being entered through System.in you can change that to use a stored password if you want.
PBEKeySpec pbeKeySpec;
PBEParameterSpec pbeParamSpec;
SecretKeyFactory keyFac;
// Salt
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
// Iteration count
int count = 20;
// Create PBE parameter set
pbeParamSpec = new PBEParameterSpec(salt, count);
// Prompt user for encryption password.
// Collect user password as char array (using the
// "readPassword" method from above), and convert
// it into a SecretKey object, using a PBE key
// factory.
System.out.print("Enter encryption password: ");
System.out.flush();
pbeKeySpec = new PBEKeySpec(readPassword(System.in));
keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// Our cleartext
byte[] cleartext = "This is another example".getBytes();
// Encrypt the cleartext
byte[] ciphertext = pbeCipher.doFinal(cleartext);
%>%
has no builtin meaning but the user (or a package) is free to define operators of the form %whatever%
in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.
"%,%" <- function(x, y) paste0(x, ", ", y)
# test run
"Hello" %,% "World"
## [1] "Hello, World"
The base of R provides %*%
(matrix mulitiplication), %/%
(integer division), %in%
(is lhs a component of the rhs?), %o%
(outer product) and %x%
(kronecker product). It is not clear whether %%
falls in this category or not but it represents modulo.
expm The R package, expm, defines a matrix power operator %^%
. For an example see Matrix power in R .
operators The operators R package has defined a large number of such operators such as %!in%
(for not %in%
). See http://cran.r-project.org/web/packages/operators/operators.pdf
igraph This package defines %--% , %->% and %<-% to select edges.
lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .
magrittr In the case of %>%
the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html
magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%
, %<>%
and %$%
and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.
dplyr The dplyr R package used to define a %.%
operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>%
which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>%
: Differences between %.% (dplyr) and %>% (magrittr)
pipeR The R package, pipeR, defines a %>>%
operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/
The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf
postlogic The postlogic package defined %if%
and %unless%
operators.
wrapr The R package, wrapr, defines a dot pipe %.>%
that is an explicit version of %>%
in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%
. See https://winvector.github.io/wrapr/articles/dot_pipe.html
Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:
1:8 %>% sum %>% sqrt
## [1] 6
one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.
) . We follow that with a semicolon.
1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6
Update Added info on expm package and simplified example at top. Added postlogic package.
This should give you the result you want.
double total = 0;
int number = 0;
float percentage = number / total * 100
printf("%.2f",percentage);
Note that the first operand is a double
Using ThorsSerializer
Dog *d1 = new Dog();
d1->name = "myDog";
std::stringstream stream << ThorsAnvil::Serialize::jsonExport(d1);
string serialized = stream.str();
Dog *d2 = nullptr;
stream >> ThorsAnvil::Serialize::jsonImport(d2);
std::cout << d2->name; // This will print "myDog"
I think that is pretty close to your original.
There is a tiny bit of set up. You need to declare your class is Serializable.
#include "ThorSerialize/Traits.h"
#include "ThorSerialize/JsonThor.h"
struct Dog
{
std::string name;
};
// Declare the "Dog" class is Serializable; Serialize the member "name"
ThorsAnvil_MakeTrait(Dog, name);
No other coding is required.
Complete Examples can be found:
I would strongly recommend that you bundle the DateJS library with your plugin and document the fact that you've done it. Nothing is more frustrating than having to hunt down dependencies.
That said, for legal reasons, you may not always be able to bundle everything. It also never hurts to be cautious and check for the existence of the plugin using Eran Galperin's answer.
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
The following helps in any case (no matter if you're using IIS, Cassini or whatever):
Why does this work? When web.config is changed, the web server (IIS, Cassini, etc.) does a recycle, but in this case (for whatever reason), the process keeps the same, so you keep attached to it with the debugger (Visual Studio).
FYI you dont have string datatype in C. Use array of characters to store the value and manipulate it. Change your variable c into an array of characters and use it inside a loop to get values.
char c[10];
int i=0;
while(i!=10)
{
c[i]=fgetc(fp);
i++;
}
The other way to do is to use pointers and allocate memory dynamically and assign values.
There is a operator < between lists e.g.:
[12, 'tall', 'blue', 1] < [4, 'tall', 'blue', 13]
will give
False
I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/
I renamed your container
div to overlay
, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.
The resulting html is :
<div class="overlay">
<div id="loading-img"></div>
</div>
<div class="content">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
<button id="button">Submit</button>
</div>
The css of the overlay is the following
.overlay {
background: #e9e9e9; <- I left your 'gray' background
display: none; <- Not displayed by default
position: absolute; <- This and the following properties will
top: 0; make the overlay, the element will expand
right: 0; so as to cover the whole body of the page
bottom: 0;
left: 0;
opacity: 0.5;
}
I added some dummy text so as to have something to overlay.
Then, in the click
handler we just need to show the overlay :
$("#button").click(function () {
$(".overlay").show();
});
The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.
Wireshark + OSX + iOS:
Great overview so far, but if you want specifics for Wireshark + OSX + iOS:
rvictl -s x
where x
is the UDID of your iOS device. You can find the UDID of your iOS device via iTunes (make sure you are using the UDID and not the serial number).Capture->Options
, a dialog box appears, click on the line rvi0
then press the Start
button.Now you will see all network traffic on the iOS device. It can be pretty overwhelming. A couple of pointers:
ip.addr==204.144.14.134
views traffic with a source or destination address of 204.144.14.134http
views only http trafficHere's a sample window depicting TCP traffic for for pdf download from 204.144.14.134:
You can kill a thread by installing trace into the thread that will exit the thread. See attached link for one possible implementation.
To set parameters to your HttpPostRequest
you can use BasicNameValuePair
, something like this :
HttpClient httpclient;
HttpPost httpPost;
ArrayList<NameValuePair> postParameters;
httpclient = new DefaultHttpClient();
httpPost = new HttpPost("your login link");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
HttpResponse response = httpclient.execute(httpPost);
I'd expect anchor tags to lead to a static page with a url. I think that a buttons suits more to your use case, and then you can use ngDisabled to disable it. From the docs: https://docs.angularjs.org/api/ng/directive/ngDisabled
May be you can use something like this:
public class Test {
public interface Option<T> {
T get();
T getOrElse(T def);
boolean hasValue();
}
final static class Some<T> implements Option<T> {
private final T value;
public Some(T value) {
this.value = value;
}
@Override
public T get() {
return value;
}
@Override
public T getOrElse(T def) {
return value;
}
@Override
public boolean hasValue() {
return true;
}
}
final static class None<T> implements Option<T> {
@Override
public T get() {
throw new UnsupportedOperationException();
}
@Override
public T getOrElse(T def) {
return def;
}
@Override
public boolean hasValue() {
return false;
}
}
public static Option<Integer> parseInt(String s) {
Option<Integer> result = new None<Integer>();
try {
Integer value = Integer.parseInt(s);
result = new Some<Integer>(value);
} catch (NumberFormatException e) {
}
return result;
}
}
I was missing somehow more dynamic array of strings, where amount of strings could be varied depending on run-time selection, but otherwise strings should be fixed.
I've ended up of coding code snippet like this:
#define INIT_STRING_ARRAY(...) \
{ \
char* args[] = __VA_ARGS__; \
ev = args; \
count = _countof(args); \
}
void InitEnumIfAny(String& key, CMFCPropertyGridProperty* item)
{
USES_CONVERSION;
char** ev = nullptr;
int count = 0;
if( key.Compare("horizontal_alignment") )
INIT_STRING_ARRAY( { "top", "bottom" } )
if (key.Compare("boolean"))
INIT_STRING_ARRAY( { "yes", "no" } )
if( ev == nullptr )
return;
for( int i = 0; i < count; i++)
item->AddOption(A2T(ev[i]));
item->AllowEdit(FALSE);
}
char** ev
picks up pointer to array strings, and count picks up amount of strings using _countof
function. (Similar to sizeof(arr) / sizeof(arr[0])
).
And there is extra Ansi to unicode conversion using A2T
macro, but that might be optional for your case.
This error, as you can read on the question linked in comments above, results to be:
"[...] a problem with loading {some} hardware module. This could be something to do with GPU support, sdcard handling, basically anything."
The step 1 below should resolve this problem. Also as I can see, you have some strange package names inside your manifest:
<manifest>
tag,<application>
<activity>
As you know, these things do not prevent your app to be displayed. But I think:
the
Couldn't load memtrack module error
could occur because of emulators configurations problems and, because your project contains many organization problems, it might help to give a fresh redesign.
For better using and with few things, this can be resolved by following these tips:
And even a real device! The memtrack module
error seems related to your emulator. So change it into Run configuration
, don't forget to change the API
too.
For OpenGl
errors, as called unimplemented OpenGL ES API
, it's not an error but a statement! You should enable it in your manifest (you can read this answer if you're using GLSurfaceView inside HomeActivity.java
, it might help you):
<uses-feature android:glEsVersion="0x00020000"></uses-feature>
// or
<uses-feature android:glEsVersion="0x00010001" android:required="true" />
Don't declare different package names to all the tags in Manifest
. You should have the same for Manifest
, Activities
, etc. Something like this looks right:
<!-- set the general package -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sit.gems.activity"
android:versionCode="1"
android:versionName="1.0" >
<!-- don't set a package name in <application> -->
<application ... >
<!-- then, declare the activities -->
<activity
android:name="com.sit.gems.activity.SplashActivity" ... >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- same package here -->
<activity
android:name="com.sit.gems.activity.HomeActivity" ... >
</activity>
</application>
</manifest>
You should set another layout for SplashScreenActivity.java
because you're not using the TabHost
for the splash screen and this is not a safe resource way. Declare a specific layout with something different, like the app name and the logo:
// inside SplashScreen class
setContentView(R.layout.splash_screen);
// layout splash_screen.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/appname" />
Avoid using a layout in activities which don't use it.
Finally, I don't understand clearly the purpose of your SplashScreenActivity
. It sets a content view and directly finish. This is useless.
As its name is Splash Screen, I assume that you want to display a screen before launching your HomeActivity
. Therefore, you should do this and don't use the TabHost
layout ;):
// FragmentActivity is also useless here! You don't use a Fragment into it, so, use traditional Activity
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set your splash_screen layout
setContentView(R.layout.splash_screen);
// create a new Thread
new Thread(new Runnable() {
public void run() {
try {
// sleep during 800ms
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
// start HomeActivity
startActivity(new Intent(SplashActivity.this, HomeActivity.class));
SplashActivity.this.finish();
}
}).start();
}
}
I hope this kind of tips help you to achieve what you want.
If it's not the case, let me know how can I help you.
Use a loop
for(var i = 0; i < obj.length; ++i){
//do something with obj[i]
for(var ind in obj[i]) {
console.log(ind);
for(var vals in obj[i][ind]){
console.log(vals, obj[i][ind][vals]);
}
}
}
For those who want the results from a plain command, the solution could be:
begin
DBMS_OUTPUT.PUT_LINE(TO_Char(SQL%ROWCOUNT)||' rows affected.');
end;
The basic problem is that SQL%ROWCOUNT is a PL/SQL variable (or function), and cannot be directly accessed from an SQL command. By using a noname PL/SQL block, this can be achieved.
... If anyone has a solution to use it in a SELECT Command, I would be interested.
When you create a folder with N entries, you create a list of N items at file-system level. This list is a system-wide shared data structure. If you then start modifying this list continuously by adding/removing entries, I expect at least some lock contention over shared data. This contention - theoretically - can negatively affect performance.
For read-only scenarios I can't imagine any reason for performance degradation of directories with large number of entries.
PROBLEM RESOLVED
In my case the problem was that I do the ajax call (with $.ajax, $.get or $.getJSON methods from jQuery) with full path in the url param:
But the correct way is to pass the value of url as:
url: "site/cgi-bin/serverApp.php"
Some browser don't conflict and make no distiction between one text or another, but in Firefox 3.6 for Mac OS take this full path as "cross site scripting"... another thing, in the same browser there is a distinction between:
http://mydomain.com/site/index.html
And put
http://www.mydomain.com/site/index.html
In fact it is the correct point view, but most implementations make no distinction, so the solution was to remove all the text that specify the full path to the script in the methods that do the ajax request AND.... remove any BASE tag in the index.html file
base href="http://mydomain.com/" <--- bad idea, remove it!
If you don't remove it, this version of browser for this system may take your ajax request like if it is a cross site request!
I have the same problem but only on the Mac OS machine. The problem is that Firefox treat the ajax response as an "cross site" call, in any other machine/browser it works fine. I didn't found any help about this (I think that is a firefox implementation issue), but I'm going to prove the next code at the server side:
header('Content-type: application/json');
to ensure that browser get the data as "json data" ...
One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.
assert type(A) is type(""), "requires a string"
In PHP 5 you can use SoapClient on the WSDL to call the web service functions. For example:
$client = new SoapClient("some.wsdl");
and $client is now an object which has class methods as defined in some.wsdl. So if there was a method called getTime in the WSDL then you would just call:
$result = $client->getTime();
And the result of that would (obviously) be in the $result variable. You can use the __getFunctions method to return a list of all the available methods.
If you are using Spring Framework with application.yml
and having trouble to make the test find the SQL file on the INIT
property, you can use the classpath:
notation.
For example, if you have a init.sql
SQL file on the src/test/resources
, just use:
url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM 'classpath:init.sql';DB_CLOSE_DELAY=-1;
Never ever use for
it may cause almost untraceable bugs.
Don't be fooled, this is not about idiomatic code or style issues. Ruby's implementation of for
has a serious flaw and should not be used.
Here is an example where for
introduces a bug,
class Library
def initialize
@ary = []
end
def method_with_block(&block)
@ary << block
end
def method_that_uses_these_blocks
@ary.map(&:call)
end
end
lib = Library.new
for n in %w{foo bar quz}
lib.method_with_block { n }
end
puts lib.method_that_uses_these_blocks
Prints
quz
quz
quz
Using %w{foo bar quz}.each { |n| ... }
prints
foo
bar
quz
Why?
In a for
loop the variable n
is defined once and only and then that one definition is use for all iterations. Hence each blocks refer to the same n
which has a value of quz
by the time the loop ends. Bug!
In an each
loop a fresh variable n
is defined for each iteration, for example above the variable n
is defined three separate times. Hence each block refer to a separate n
with the correct values.
padde's solution is right, but risen up another problem i.e.
As said by Adam (the questioner) that it is showing empty popup. Here is the complete and working solution
<html>
<head>
<script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.0.5"></script>
<link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.0.5" media="screen" />
</head>
<body>
<a href="#divForm" id="btnForm">Load Form</a>
<div id="divForm" style="display:none">
<form action="tbd">
File: <input type="file" /><br /><br />
<input type="submit" />
</form>
</div>
<script type="text/javascript">
$(function() {
$("#btnForm").fancybox({
'onStart': function() { $("#divForm").css("display","block"); },
'onClosed': function() { $("#divForm").css("display","none"); }
});
});
</script>
</body>
</html>
A typical custom exception I'd define is something like this:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
public CustomException(String message, Throwable throwable) {
super(message, throwable);
}
}
I even create a template using Eclipse so I don't have to write all the stuff over and over again.
Here is a little sub that may just interest some people who need to specify the browser. (but its not as good as a 12" pizza sub!) :P
Private Sub NavigateWebURL(ByVal URL As String, Optional browser As String = "default")
If Not (browser = "default") Then
Try
'// try set browser if there was an error (browser not installed)
Process.Start(browser, URL)
Catch ex As Exception
'// use default browser
Process.Start(URL)
End Try
Else
'// use default browser
Process.Start(URL)
End If
End Sub
Call: will open www.google.com in Firefox if it is installed on that PC.
NavigateWebURL("http://www.google.com", "Firefox") '// safari Firefox chrome etc
Call: will open www.google.com in default browser.
NavigateWebURL("http://www.google.com", "default")
OR
NavigateWebURL("http://www.google.com")
Requires Newtonsoft Json.Net
A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:
public List<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
{
JObject attributesAsJObject = dynamicToGetPropertiesFor;
Dictionary<string, object> values = attributesAsJObject.ToObject<Dictionary<string, object>>();
List<string> toReturn = new List<string>();
foreach (string key in values.Keys)
{
toReturn.Add(key);
}
return toReturn;
}
Then you simply foreach like this:
foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
{
dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
// And
dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
}
Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.
You could do something like this:
$("#txtArea").on("keypress",function(e) {_x000D_
var key = e.keyCode;_x000D_
_x000D_
// If the user has pressed enter_x000D_
if (key == 13) {_x000D_
document.getElementById("txtArea").value =document.getElementById("txtArea").value + "\n";_x000D_
return false;_x000D_
}_x000D_
else {_x000D_
return true;_x000D_
}_x000D_
});
_x000D_
<textarea id="txtArea"></textarea>
_x000D_
If you want to hide on initial opening and you are populating the dropdown via ajax call, add the following to the ajax block in your select2 declaration:
beforeSend: function ()
{
$('.select2-search--dropdown').addClass('hidden');
}
To then show it again (and focus) after your ajax request is successful:
success: function() {
$('.select2-search--dropdown').removeClass('select2-search--hide'); // show search bar then focus
$('.select2-search__field')[0].focus();
}
You can easily find and remove bin and obj folders in Far Manager.
In search setting dialog:
After the search is done, switch view to "Panel".
Hope it helps someone.
@vimal answer did not provide solution for me. It seems the orientation is not the current orientation, but from previous orientation. To fix it, I use [[UIDevice currentDevice] orientation]
- (void)orientationChanged:(NSNotification *)notification{
[self adjustViewsForOrientation:[[UIDevice currentDevice] orientation]];
}
Then
- (void) adjustViewsForOrientation:(UIDeviceOrientation) orientation { ... }
With this code I get the current orientation position.
Add produces = "application/json"
in @RequestMapping
For the first rule,
Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.
For the second,
Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.
For the third,
Same as the second, except your formula is =".8*" rather than .9.
I like the -=[4]
way mentioned in other answers to delete the elements whose value is 4.
But there is this way:
[2,4,6,3,8,6].delete_if { |i| i == 6 }
=> [2, 4, 3, 8]
mentioned somewhere in "Basic Array Operations", after it mentions the map
function.
Can't you just try to replace the body content with the document.body handler?
if your page is this:
<html>
<body>
blablabla
<script type="text/javascript">
document.body.innerHTML="hi!";
</script>
</body>
</html>
Just use the document.body to replace the body.
This works for me. All the content of the BODY tag is replaced by the innerHTML you specify. If you need to even change the html tag and all childs you should check out which tags of the 'document.' are capable of doing so.
An example with javascript scripting inside it:
<html>
<body>
blablabla
<script type="text/javascript">
var changeme = "<button onClick=\"document.bgColor = \'#000000\'\">click</button>";
document.body.innerHTML=changeme;
</script>
</body>
This way you can do javascript scripting inside the new content. Don't forget to escape all double and single quotes though, or it won't work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.
Bare in mind that server side scripting like php doesn't work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.
Here is an example of a simple service, that uses localStorage to persist data:
import { Injectable } from '@angular/core';
@Injectable()
export class PersistanceService {
constructor() {}
set(key: string, data: any): void {
try {
localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
console.error('Error saving to localStorage', e);
}
}
get(key: string) {
try {
return JSON.parse(localStorage.getItem(key));
} catch (e) {
console.error('Error getting data from localStorage', e);
return null;
}
}
}
To use this services, provide it in some module in your app like normal, for example in core module. Then use like this:
import { Injectable } from '@angular/core';
@Injectable()
export class SomeOtherService {
constructor(private persister: PersistanceService) {}
someMethod() {
const myData = {foo: 'bar'};
persister.set('SOME_KEY', myData);
}
someOtherMethod() {
const myData = persister.get('SOME_KEY');
}
}
Method __str__ should return string, not print.
def __str__(self):
return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)
@Jonathan Leffler: Thank you. Your solution works.
A complete working example:
/** compile-time dispatch
$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
*/
#include <stdio.h>
#define QUOTE(name) #name
#define STR(macro) QUOTE(macro)
#ifndef TEST_FUN
# define TEST_FUN some_func
#endif
#define TEST_FUN_NAME STR(TEST_FUN)
void some_func(void)
{
printf("some_func() called\n");
}
void another_func(void)
{
printf("do something else\n");
}
int main(void)
{
TEST_FUN();
printf("TEST_FUN_NAME=%s\n", TEST_FUN_NAME);
return 0;
}
Example:
$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
do something else
TEST_FUN_NAME=another_func
You could try this if you only need the code to run when you have a debugger attached to the process.
if (Debugger.IsAttached)
{
// do some stuff here
}
You need to create new rails application first. Run
rails new mebay
cd mebay
bundle install
rails generate model ...
And try to find Rails 3 tutorial, there are a lot of changes since 2.1 Guides (http://guides.rubyonrails.org/getting_started.html) are good start point.
In your css file add following.
ul{
list-style-type: none;
}
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
This topic shows up on the first page of my google result, so here's a little useful tip for new comers.
You could also dump the sql and gzip it in one line:
mysqldump -u [username] -p[password] [database_name] | gzip > [filename.sql.gz]
I had a similar problem. I had HTML files and videos in the assets-folder of my app.
Therefore the videos were located inside of the APK. Because the APK is really a ZIP-file, the WebView was not able to read the video-files.
Copying all HTML- and video-files onto the SD-Card worked for me.
An inner class has access to all members of the outer class, but it does not have an implicit reference to a parent class instance (unlike some weirdness with Java). So if you pass a reference to the outer class to the inner class, it can reference anything in the outer class instance.
Sample 9 patch image with shadow
After a lots of research I found an easy method.
Create a 9 patch image and apply it as button or any other view's background.
You can create a 9 patch image with shadow using this website.
Put the 9 patch image in your drawable directory and apply it as the background for the button.
mButton.setBackground(ContextCompat.getDrawable(mContext, R.drawable.your_9_patch_image);
Your example is not an override. Overrides technically occur in a subclass, but in this example the contructor method is replaced in the original class.
Given the following dataframe df
and the function complex_function
,
import pandas as pd
def complex_function(x, y=0):
if x > 5 and x > y:
return 1
else:
return 2
df = pd.DataFrame(data={'col1': [1, 4, 6, 2, 7], 'col2': [6, 7, 1, 2, 8]})
col1 col2
0 1 6
1 4 7
2 6 1
3 2 2
4 7 8
there are several solutions to use apply() on only one column. In the following I will explain them in detail.
The straightforward solution is the one from @Fabio Lamanna:
df['col1'] = df['col1'].apply(complex_function)
Output:
col1 col2
0 2 6
1 2 7
2 1 1
3 2 2
4 1 8
Only the first column is modified, the second column is unchanged. The solution is beautiful. It is just one line of code and it reads almost like english: "Take 'col1' and apply the function complex_function to it."
However, if you need data from another column, e.g. 'col2', it's not working. If you want to pass the values of 'col2' to variable y
of the complex_function
, you need something else.
Alternatively, you could use the whole dataframe as described in this or this SO post:
df['col1'] = df.apply(lambda x: complex_function(x['col1']), axis=1)
or if you prefer (like me) a solution without a lambda function:
def apply_complex_function(x): return complex_function(x['col1'])
df['col1'] = df.apply(apply_complex_function, axis=1)
There is a lot going on in this solution that needs to be explained. The apply() function works on pd.Series and pd.DataFrame. But you cannot use df['col1'] = df.apply(complex_function).loc[:, 'col1']
, because it would throw a ValueError
.
Hence, you need to give the information which column to use. To complicate things, the apply() function does only accept callables. To solve this, you need to define a (lambda) function with the column x['col1']
as argument; i.e. we wrap the column information in another function.
Unfortunately, the default value of the axis parameter is zero (axis=0
), which means it will try executing column-wise and not row-wise. This wasn't a problem in the first solution, because we gave apply() a pd.Series. But now the input is a dataframe and we must be explicit (axis=1
). (I marvel how often I forget this.)
Whether you prefer the version with the lambda function or without is subjective. In my opinion the line of code is complicated enough to read even without a lambda function thrown in. You only need the (lambda) function as a wrapper. It is just boiler code. A reader should not be bothered with it.
Now, you can modify this solution easily to take the second column into account:
def apply_complex_function(x): return complex_function(x['col1'], x['col2'])
df['col1'] = df.apply(apply_complex_function, axis=1)
Output:
col1 col2
0 2 6
1 2 7
2 1 1
3 2 2
4 2 8
At index 4 the value has changed from 1 to 2, because the first condition 7 > 5
is true but the second condition 7 > 8
is false.
Note that you only needed to change the first line of code (i.e. the function) and not the second line.
Never put the column information into your function.
def bad_idea(x):
return x['col1'] ** 2
By doing this, you make a general function dependent on a column name! This is a bad idea, because the next time you want to use this function, you cannot. Worse: Maybe you rename a column in a different dataframe just to make it work with your existing function. (Been there, done that. It is a slippery slope!)
Although the OP specifically asked for a solution with apply(), alternative solutions were suggested. For example, the answer of @George Petrov suggested to use map(), the answer of @Thibaut Dubernet proposed assign().
I fully agree that apply() is seldom the best solution, because apply() is not vectorized. It is an element-wise operation with expensive function calling and overhead from pd.Series.
One reason to use apply() is that you want to use an existing function and performance is not an issue. Or your function is so complex that no vectorized version exists.
Another reason to use apply() is in combination with groupby(). Please note that DataFrame.apply() and GroupBy.apply() are different functions.
So it does make sense to consider some alternatives:
map()
only works on pd.Series, but accepts dict and pd.Series as input. Using map() with a function is almost interchangeable with using apply(). It can be faster than apply(). See this SO post for more details. df['col1'] = df['col1'].map(complex_function)
applymap()
is almost identical for dataframes. It does not support pd.Series and it will always return a dataframe. However, it can be faster. The documentation states: "In the current implementation applymap calls func twice on the first column/row to decide whether it can take a fast or slow code path.". But if performance really counts you should seek an alternative route. df['col1'] = df.applymap(complex_function).loc[:, 'col1']
assign()
is not a feasible replacement for apply(). It has a similar behaviour in only the most basic use cases. It does not work with the complex_function
. You still need apply() as you can see in the example below. The main use case for assign() is method chaining, because it gives back the dataframe without changing the original dataframe. df['col1'] = df.assign(col1=df.col1.apply(complex_function))
I only mention it here because it was suggested by other answers, e.g. @durjoy. The list is not exhaustive:
.loc
. My example complex_function
could be refactored in this way.raw=True
parameter. Theoretically, this should improve the performance of apply() if you are just applying a NumPy reduction function, because the overhead of pd.Series is removed. Of course, your function has to accept an ndarray. You have to refactor your function to NumPy. By doing this, you will have a huge performance boost.This worked for me with phpmyadmin under Ubuntu 16.04:
I edited /etc/phpmyadmin/config.inc.php and changed the following 2 lines:
$cfg['Servers'][$i]['controluser'] = 'root';
$cfg['Servers'][$i]['controlpass'] = 'thepasswordgiventoroot';
We passed Json object by HttpPost method, and parse it in dynamic object. it works fine. this is sample code:
webapi:
[HttpPost]
public string DoJson2(dynamic data)
{
//whole:
var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString());
//or
var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());
var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());
string appName = data.AppName;
int appInstanceID = data.AppInstanceID;
string processGUID = data.ProcessGUID;
int userID = data.UserID;
string userName = data.UserName;
var performer = JsonConvert.DeserializeObject< NextActivityPerformers >(data.NextActivityPerformers.ToString());
...
}
The complex object type could be object, array and dictionary.
ajaxPost:
...
Content-Type: application/json,
data: {"AppName":"SamplePrice",
"AppInstanceID":"100",
"ProcessGUID":"072af8c3-482a-4b1c??-890b-685ce2fcc75d",
"UserID":"20",
"UserName":"Jack",
"NextActivityPerformers":{
"39??c71004-d822-4c15-9ff2-94ca1068d745":[{
"UserID":10,
"UserName":"Smith"
}]
}}
...
I have Nginx and With below Nginx Config:
server {
listen 80;
server_name xxxxxx;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://x.x.x.x:8000;
}
}
@tirtha-r solution worked for me
#!flask/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/', methods=['GET'])
def get_tasks():
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
return jsonify({'ip': request.environ['REMOTE_ADDR']}), 200
else:
return jsonify({'ip': request.environ['HTTP_X_FORWARDED_FOR']}), 200
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0', port=8000)
My Request and Response:
curl -X GET http://test.api
{
"ip": "Client Ip......"
}
You have to run this mongorestore command via cmd and not on Mongo Shell... Have a look at below command on...
Run this command on cmd (not on Mongo shell)
>path\to\mongorestore.exe -d dbname -c collection_name path\to\same\collection.bson
Here path\to\mongorestore.exe
is path of mongorestore.exe
inside bin folder of mongodb. dbname is name of databse. collection_name
is name of collection.bson. path\to\same\collection.bson
is the path up to that collection.
Now from mongo shell you can verify that database is created or not (If it does not exist, database with same name will be created with collection).
With Python older than 2.7/3.1, that's pretty much how you do it.
For newer versions, see importlib.import_module
for Python 2 and and Python 3.
You can use exec
if you want to as well.
Or using __import__
you can import a list of modules by doing this:
>>> moduleNames = ['sys', 'os', 're', 'unittest']
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)
Ripped straight from Dive Into Python.
Creating a new attribute class is a good suggestion. In my case, I wanted to specify 'default(DateTime)' or 'DateTime.MinValue' so that the Newtonsoft.Json serializer would ignore DateTime members without real values.
[JsonProperty( DefaultValueHandling = DefaultValueHandling.Ignore )]
[DefaultDateTime]
public DateTime EndTime;
public class DefaultDateTimeAttribute : DefaultValueAttribute
{
public DefaultDateTimeAttribute()
: base( default( DateTime ) ) { }
public DefaultDateTimeAttribute( string dateTime )
: base( DateTime.Parse( dateTime ) ) { }
}
Without the DefaultValue attribute, the JSON serializer would output "1/1/0001 12:00:00 AM" even though the DefaultValueHandling.Ignore option was set.
Follow this tutorial Tensorflow GPU I did it and it works perfect.
Attention! - install version 9.0! newer version is not supported by Tensorflow-gpu
Steps:
pip install tensorflow-gpu
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
Just to share my finding. I still got the same error even if the query was targeting the correct class name. Later on I realised that I was importing the Entity class from the wrong package.
The problem was solved after I change the import line from:
import org.hibernate.annotations.Entity;
to
import javax.persistence.Entity;
In case you want to remove DS_Store files to every folder and subfolder:
find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch
Ignore them by:
echo ".DS_Store" >> ~/.gitignore_global
echo "._.DS_Store" >> ~/.gitignore_global
echo "**/.DS_Store" >> ~/.gitignore_global
echo "**/._.DS_Store" >> ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global
jQuery should be able to find even hidden elements. It also has the :visible
and :hidden
selectors to find both visible and hidden elements.
Does this help? Not sure without more info.
You have to remove the semicolon in the css rule string:
$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
You are looking for dynamic_cast<B*>(pointer)
You can simply use:
ps -o args= -f -p ProcessPid
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
you can try this:
<div onselectstart="return false">your text</div>
dict(zip(*numpy.unique(y, return_counts=True)))
Just copied Seppo Enarvi's comment here which deserves to be a proper answer
I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.
select CONVERT(bigint,'60') as seconds
and it returns
60
Just using
$().popover({container: 'body'})
could be not enough when displaying popover over a BootstrapDialog modal, which also uses body as container and has a higher z-index.
I come with this fix which uses internals of Bootstrap3 (may not work with 2.x / 4.x) but most of modern Bootstrap installations are 3.x.
self.$anchor.on('shown.bs.popover', function(ev) {
var tipCSS = self.$anchor.data('tipCSS');
if (tipCSS !== undefined) {
self.$anchor.data('bs.popover').$tip.css(tipCSS);
}
// ...
});
Such way different popovers may have different z-index, some are under BootstrapDialog modal, while another ones are over it.
Multiple attributes can be connected with an and
:
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
(use find_or_initialize_by
if you don't want to save the record right away)
Edit: The above method is deprecated in Rails 4. The new way to do it will be:
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create
and
GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize
Edit 2: Not all of these were factored out of rails just the attribute specific ones.
https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md
Example
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
became
GroupMember.find_or_create_by(member_id: 4, group_id: 7)
If you need just logical value (as it almost always is), the following one-liner will help you:
boolean ifIntsEqual = !((Math.max(a,b) - Math.min(a, b)) > 0);
And it works even in Java 1.5+, maybe even in 1.1 (i don't have one). Please tell us, if you can test it in 1.5-.
This one will do too:
boolean ifIntsEqual = !((Math.abs(a-b)) > 0);
The answer below uses git log
:
I mentioned a similar approach in 2009 with "Unable to show a Git tree in terminal":
git log --graph --pretty=oneline --abbrev-commit
But the full one I have been using is in "How to display the tag name and branch name using git log --graph" (2011):
git config --global alias.lgb "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --abbrev-commit --date=relative --branches"
git lgb
Original answer (2010)
git show-branch --list
comes close of what you are looking for (with the topo order)
--topo-order
By default, the branches and their commits are shown in reverse chronological order.
This option makes them appear in topological order (i.e., descendant commits are shown before their parents).
But the tool git wtf can help too. Example:
$ git wtf
Local branch: master
[ ] NOT in sync with remote (needs push)
- Add before-search hook, for shortcuts for custom search queries. [4430d1b] (edwardzyang@...; 7 days ago)
Remote branch: origin/master ([email protected]:sup/mainline.git)
[x] in sync with local
Feature branches:
{ } origin/release-0.8.1 is NOT merged in (1 commit ahead)
- bump to 0.8.1 [dab43fb] (wmorgan-sup@...; 2 days ago)
[ ] labels-before-subj is NOT merged in (1 commit ahead)
- put labels before subject in thread index view [790b64d] (marka@...; 4 weeks ago)
{x} origin/enclosed-message-display-tweaks merged in
(x) experiment merged in (only locally)
NOTE: working directory contains modified files
git-wtf
shows you:
- How your branch relates to the remote repo, if it's a tracking branch.
- How your branch relates to non-feature ("version") branches, if it's a feature branch.
- How your branch relates to the feature branches, if it's a version branch
If you want to use your dataframe object only once, use:
df['BoolCol'].loc[lambda x: x==True].index
The easiest way is to invert the value of the keys and use heapq. For example, turn 1000.0 into -1000.0 and 5.0 into -5.0.
In my case, my Android Studio version was 3.6.1 and i have modified the classpath like below;
classpath 'com.android.tools.build:gradle:3.6.1'
and that error was gone.
Dir has also shorter syntax to get an array of all files from directory:
Dir['dir/to/files/*'].each do |fname|
# do something with fname
end
In Node.js, __dirname
is always the directory in which the currently executing script resides (see this). So if you typed __dirname
into /d1/d2/myscript.js
, the value would be /d1/d2
.
By contrast, .
gives you the directory from which you ran the node
command in your terminal window (i.e. your working directory) when you use libraries like path
and fs
. Technically, it starts out as your working directory but can be changed using process.chdir()
.
The exception is when you use .
with require()
. The path inside require
is always relative to the file containing the call to require
.
Let's say your directory structure is
/dir1
/dir2
pathtest.js
and pathtest.js
contains
var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));
and you do
cd /dir1/dir2
node pathtest.js
you get
. = /dir1/dir2
__dirname = /dir1/dir2
Your working directory is /dir1/dir2
so that's what .
resolves to. Since pathtest.js
is located in /dir1/dir2
that's what __dirname
resolves to as well.
However, if you run the script from /dir1
cd /dir1
node dir2/pathtest.js
you get
. = /dir1
__dirname = /dir1/dir2
In that case, your working directory was /dir1
so that's what .
resolved to, but __dirname
still resolves to /dir1/dir2
.
.
inside require
...If inside dir2/pathtest.js
you have a require
call into include a file inside dir1
you would always do
require('../thefile')
because the path inside require
is always relative to the file in which you are calling it. It has nothing to do with your working directory.
Accepted answer fails to mention how to delete the .swp file.
Hit "D" when the prompt comes up and it will remove it.
In my case, after I hit D it left the latest saved version intact and deleted the .swp which got created because I exited VIM incorrectly
One hot encoding with pandas is very easy:
def one_hot(df, cols):
"""
@param df pandas DataFrame
@param cols a list of columns to encode
@return a DataFrame with one-hot encoding
"""
for each in cols:
dummies = pd.get_dummies(df[each], prefix=each, drop_first=False)
df = pd.concat([df, dummies], axis=1)
return df
EDIT:
Another way to one_hot using sklearn's LabelBinarizer
:
from sklearn.preprocessing import LabelBinarizer
label_binarizer = LabelBinarizer()
label_binarizer.fit(all_your_labels_list) # need to be global or remembered to use it later
def one_hot_encode(x):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
return label_binarizer.transform(x)
Edit the file xampp/mysql/bin/my.ini
Add
skip-grant-tables
under [mysqld]
It is also possible to include bitmaps. I think you also can use transformations on that.
Here is a good eplanation: ASP.NET MVC – Multiple buttons in the same form
In 2 words:
you may analize value of submitted button in yout action
or
make separate actions with your version of ActionMethodSelectorAttribute
(which I personaly prefer and suggest).
If you have a container and two sub containers, you can do like this
jQuery
$("#previousbutton").click(function() {
$("#form_sub_container1").show();
$("#form_sub_container2").hide(); })
$("#nextbutton").click(function() {
$("#form_container").find(":hidden").show().next();
$("#form_sub_container1").hide();
})
HTML
<div id="form_container">
<div id="form_sub_container1" style="display: block;">
</div>
<div id="form_sub_container2" style="display: none;">
</div>
</div>
If you want to make transparent background is gray, pls try:
.transparent{
background:rgba(1,1,1,0.5);
}
Try adding:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js">
and:
angular.module('MyApp', ['ngRoute','ngResource']);
function TwitterCtrl($scope,$resource){
}
You should call angular.module
only once with all dependencies because with your current code, you're creating a new MyApp
module overwriting the previous one.
From angular documentation:
Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.
console.log( String.fromCharCode(event.charCode) );
no need to map character i guess.
You should use @RequestParam
on those resources with method = RequestMethod.GET
In order to post parameters, you must send them as the request body. A body like JSON or another data representation would depending on your implementation (I mean, consume and produce MediaType
).
Typically, multipart/form-data is used to upload files.
Simple way is that you have "Collections" in Java. You just need to call it and use "reverse()" method of it.
Example usage:
ArrayList<Integer> yourArrayList = new ArrayList<>();
yourArrayList.add(1);
yourArrayList.add(2);
yourArrayList.add(3);
//yourArrayList is: 1,2,3
Collections.reverse(yourArrayList);
// Now, yourArrayList is: 3,2,1
For more question: @canerkaseler
Component
import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
...
@ViewChild('input1', {static: false}) inputEl: ElementRef;
ngAfterViewInit() {
setTimeout(() => this.inputEl.nativeElement.focus());
}
HTML
<input type="text" #input1>
Adding to the @htafoya answer. The code snippet will be
const getTimeEpoch = () => {
return new Date().getTime().toString();
}
The JVM resizes the heap adaptively, meaning it will attempt to find the best heap size for your application. -Xms and -Xmx simply specifies the range in which the JVM can operate and resize the heap. If -Xms and -Xmx are the same value, then the JVM's heap size will stay constant at that value.
It's typically best to just set -Xmx and let the JVM find the best heap size, unless there's a specific reason why you need to give the JVM a big heap at JVM launch.
As far as when the JVM actually requests the memory from the OS, I believe it depends on the platform and implementation of the JVM. I imagine that it wouldn't request the memory until your app actually needs it. -Xmx and -Xms just reserves the memory.
Disable SELinux
$ sudo setenforce 0
In spring batch I did below
private int getFilesCount() throws IOException {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("file:" + projectFilesFolder + "/**/input/splitFolder/*.csv");
return resources.length;
}
The BEST way to use the AppData directory, IS to use Environment.ExpandEnvironmentVariable
method.
Reasons:
Examples:
string path;
path = @"%AppData%\stuff";
path = @"%aPpdAtA%\HelloWorld";
path = @"%progRAMfiLES%\Adobe;%appdata%\FileZilla"; // collection of paths
path = Environment.ExpandEnvironmentVariables(path);
Console.WriteLine(path);
%ALLUSERSPROFILE% C:\ProgramData
%APPDATA% C:\Users\Username\AppData\Roaming
%COMMONPROGRAMFILES% C:\Program Files\Common Files
%COMMONPROGRAMFILES(x86)% C:\Program Files (x86)\Common Files
%COMSPEC% C:\Windows\System32\cmd.exe
%HOMEDRIVE% C:
%HOMEPATH% C:\Users\Username
%LOCALAPPDATA% C:\Users\Username\AppData\Local
%PROGRAMDATA% C:\ProgramData
%PROGRAMFILES% C:\Program Files
%PROGRAMFILES(X86)% C:\Program Files (x86) (only in 64-bit version)
%PUBLIC% C:\Users\Public
%SystemDrive% C:
%SystemRoot% C:\Windows
%TEMP% and %TMP% C:\Users\Username\AppData\Local\Temp
%USERPROFILE% C:\Users\Username
%WINDIR% C:\Windows
Because someone asked for the Data.Table version of this, and because the given data.frame solution does not work with data.table, I am providing the solution below.
Basically, use the :=
operator --> DT[x == 0, x := NA]
library("data.table")
status = as.data.table(occupationalStatus)
head(status, 10)
origin destination N
1: 1 1 50
2: 2 1 16
3: 3 1 12
4: 4 1 11
5: 5 1 2
6: 6 1 12
7: 7 1 0
8: 8 1 0
9: 1 2 19
10: 2 2 40
status[N == 0, N := NA]
head(status, 10)
origin destination N
1: 1 1 50
2: 2 1 16
3: 3 1 12
4: 4 1 11
5: 5 1 2
6: 6 1 12
7: 7 1 NA
8: 8 1 NA
9: 1 2 19
10: 2 2 40
Here is my http client in php to make post queries with cookies included:
function http_login_client($url, $params = "", $cookies_send = "" ){
// Vars
$cookies = array();
$headers = getallheaders();
// Perform a http post request to $ur1 using $params
$ch = curl_init($url);
$options = array( CURLOPT_POST => 1,
CURLINFO_HEADER_OUT => true,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 1,
CURLOPT_COOKIE => $cookies_send,
CURLOPT_USERAGENT => $headers['User-Agent']
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
/// DEBUG info echo $response; var_dump (curl_getinfo($ch)); ///
// Parse response and read cookies
preg_match_all('/^Set-Cookie: (.*?)=(.*?);/m', $response, $matches);
// Build an array with cookies
foreach( $matches[1] as $index => $cookie )
$cookies[$cookie] = $matches[2][$index];
return $cookies;
} // end http_login_client
111028 16:57:43 [ERROR] Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root!
Have you set a root password for your mysql installation? This is different to your sudo root password. Try /usr/local/mysql/bin/mysql_secure_installation
If you need to handle multiple currencies, various number formats etc. I can recommend autoNumeric. Works a treat. Have been using it successfully for several years now.
If your aim is to redirect all pages to a single maintenance page (as the title could suggest also this), then use:
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php$
RewriteCond %{REMOTE_HOST} !^000\.000\.000\.000
RewriteRule $ /maintenance.php [R=302,L]
Where 000 000 000 000 should be replaced by your ip adress.
Source:
http://www.techiecorner.com/97/redirect-to-maintenance-page-during-upgrade-using-htaccess/
In my case, I was moving a SProc between servers and the profile name in my TSQL code did not match the profile name on the new server.
Updating TSQL profile name == New server profile name fixed the error for me.
The push()
method adds new items to the end of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
// The result of fruits will be:
Banana, Orange, Apple, Mango, Kiwi
The exact answer to your question is already answered, but let's look at some other ways to add items to an array.
The unshift()
method adds new items to the beginning of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
// The result of fruits will be:
Lemon, Pineapple, Banana, Orange, Apple, Mango
And lastly, the concat()
method is used to join two or more arrays. Example:
var fruits = ["Banana", "Orange"];
var moreFruits = ["Apple", "Mango", "Lemon"];
var allFruits = fruits.concat(moreFruits);
// The values of the children array will be:
Banana, Orange, Apple, Mango, Lemon
The recommended solution git branch -f branch-pointer-to-move new-pointer
in TortoiseGit:
this is the best way to solve this
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Or, just add your binary path into the PATH. At the end of the bashrc:
...
export PATH=$PATH:/home/user/.local/bin/
save the file and run:
source .bashrc
and the command will work.
Let me seperate up everything and solve approach each problem in isolation:
Authentication
For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.
Auth server load
If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.
Transmission Security
If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.
url = username:[email protected]/api/call/nonce
If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:
nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call
It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).
Secure secret storage
It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.
If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.
(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.
The Microsoft certification material addresses this same question. In the .NET world, the overhead for the StringBuilder object makes a simple concatenation of 2 String objects more efficient. I would assume a similar answer for Java strings.
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
Well, for one thing your epression can be simplified:
$("#pDetails").attr("style")
since there should only be one element for any given ID and the ID selector will be much faster than the attribute id selector you're using.
If you just want to return the display value or something, use css():
$("#pDetails").css("display")
If you want to search for elements that have display none, that's a lot harder to do reliably. This is a rough example that won't be 100%:
$("[style*='display: none']")
but if you just want to find things that are hidden, use this:
$(":hidden")
If you want to always prune
when you fetch
, I can suggest to use Aliases.
Just type git config -e
to open your editor and change the configuration for a specific project and add a section like
[alias]
pfetch = fetch --prune
the when you fetch with git pfetch
the prune will be done automatically.
Andy E is correct that there is no HTML-based way to do this*; but if you are willing to use Flash, you can do it. The following works reliably on systems that have Flash installed. If your app needs to work on iPhone, then of course you'll need a fallback HTML-based solution.
* (Update 4/22/2013: HTML does now support this, in HTML5. See the other answers.)
Flash uploading also has other advantages -- Flash gives you the ability to show a progress bar as the upload of a large file progresses. (I'm pretty sure that's how Gmail does it, by using Flash behind the scenes, although I may be wrong about that.)
Here is a sample Flex 4 app that allows the user to pick a file, and then displays it:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="init()">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
<mx:Image id="myImage" x="9" y="44"/>
<fx:Script>
<![CDATA[
private var fr:FileReference = new FileReference();
// Called when the app starts.
private function init():void
{
// Set up event handlers.
fr.addEventListener(Event.SELECT, onSelect);
fr.addEventListener(Event.COMPLETE, onComplete);
}
// Called when the user clicks "Choose file..."
private function showFilePicker():void
{
fr.browse();
}
// Called when fr.browse() dispatches Event.SELECT to indicate
// that the user has picked a file.
private function onSelect(e:Event):void
{
fr.load(); // start reading the file
}
// Called when fr.load() dispatches Event.COMPLETE to indicate
// that the file has finished loading.
private function onComplete(e:Event):void
{
myImage.data = fr.data; // load the file's data into the Image
}
]]>
</fx:Script>
</s:Application>
I guess this may be an issue about limited contexts, e.g. WYIWYG editors on a web system used by not-programmers users, that limits the possibilities of follow the standards. Sometimes (like TinyMCE), it's a lib that puts your content/code inside a textarea
tag, that is rendered by the editor as a big div
tag. And sometimes, it may be an old version of these editors.
I'm supposing that:
stylesheets
. Actually, it would be impractical for the admins (or webdevs), considering the number of requests in that sense that they would have.In some cases, without use style
rules, it may be a very poor design experience. So, yes, these users need customization. Okay, but what would be the solutions, in this scenario? Considering the different ways to insert CSS in a html
page, I suppose these solutions:
Ask to your system adm for including some CSS rules at the system's stylesheets
. This will be an external or internal CSS solution. As already said, it might be not possible.
<link>
on <body>
Use external style sheet on the body
tag, i.e., use of the link
tag inside the area you have access (that will be, on the site, inside the body
tag and not in the head
tag). Some sources says this is okay, but "not a good practice", like MDN:
A
<link>
element can occur either in the<head>
or<body>
element, depending on whether it has a link type that is body-ok. For example, thestylesheet
link type is body-ok, and therefore<link rel="stylesheet">
is permitted in the body. However, this isn't a good practice to follow; it makes more sense to separate your<link>
elements from your body content, putting them in the<head>
.
Some others, restrict it to the <head>
section, like w3schools:
Note: This element goes only in the head section, but it can appear any number of times.
I tested it here (desktop environment, on a browser) and it works for me.
Create a file foo.html
:
<!DOCTYPE html>
<html>
<head></head>
<body>
<link href="bar.css" type="text/css" rel="stylesheet">
<h1 class="test1">Hello</h1>
<h1 class="test2">World</h1>
</body>
</html>
And then a CSS file, at the same directory, called bar.css
:
.test1 {
color: green;
};
Well, this will just looks possible if you have how upload an CSS file somewhere at the institution system. Maybe this would be the case.
<style>
on <body>
Use internet style sheet on the body
tag, i.e., use of the style
tag inside the area you have access (that will be, on the site, inside the body
tag and not in the head
tag). This is what Charles Salvia's and Sz's answers here are about. Choosing this option, consider their concerns.
Alert
These ones are related to modifying the <head>
element of the page. Maybe this will not be allowed by the institution's system administrators. So, it's recommended to ask them permission first.
Okay, supposing permission granted, the strategy is access the <head>
. How? JavaScript methods.
<link>
on <head>
This is another version of the 2nd option. Use external style sheet on the <head>
tag, i.e., use of the <link>
element outside the area you have access (that will be, on the site, not inside the body
tag and yes inside the head
tag). This solution complies with the recommendations of MDN and w3schools, as cited above, on 2nd option solution. A new Link
object will be created.
To solve the matter through JS, there are many ways but at the following codelines I demonstrate one simple.
I tested it here (desktop environment, on a browser) and it works for me.
Create a file f.html
:
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1 class="test1">Hello</h1>
<h1 class="test2">World</h1>
<script>
// JS code here
</script>
</body>
</html>
Inside the script
tag:
var newLink = document.createElement("link");
newLink.href = "bar.css";
newLink.rel = "stylesheet";
newLink.type = "text/css";
document.getElementsByTagName("head")[0].appendChild(newLink);
And then at the CSS file, at the same directory, called bar.css
(as at the 2nd option):
.test1 {
color: green;
};
As I already said: this will just looks possible if you have how upload an CSS file somewhere at the institution system.
<style>
on <head>
Use new internal style sheet on the <head>
tag, i.e., use of a new <style>
element outside the area you have access (that will be, on the site, not inside the body
tag and yes inside the head
tag). A new Style
object will be created.
This is solved through JS. One simple way is demonstrated following.
I tested it here (desktop environment, on a browser) and it works for me.
Create a file foobar.html
:
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1 class="test1">Hello</h1>
<h1 class="test2">World</h1>
<script>
// JS code here
</script>
</body>
</html>
Inside the script
tag:
var newStyle = document.createElement("style");
newStyle.innerHTML =
"h1.test1 {"+
"color: green;"+
"}";
document.getElementsByTagName("head")[0].appendChild(newStyle);
<style>
on <head>
Use an existing internal style sheet on the <head>
tag, i.e., use of a <style>
element outside the area you have access (that will be, on the site, not inside the body
tag and yes inside the head
tag), if some exists. A new Style
object will be created or a CSSStyleSheet
object will be used (in the code of the solution adopted here).
This is at some point of view risky.
First, because it may not exists some <style>
object. Depending of the way you implement this solution, you may get undefined
return (the system may use external style sheet).
Second, because you will be editing the system design author's work (authorship issues).
Third, because it may not be allowed at your institution's IT politics of safety.
So, do ask permission to do this (as at in other JS solutions).
Supposing, again, permission was granted:
You will need to consider some restrictions of the method available to this way: insertRule()
. The solution proposed uses the default scenario, and a operation at the first stylesheet
, if some exists.
I tested it here (desktop environment, on a browser) and it works for me.
Create a file foo_bar.html
:
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1 class="test1">Hello</h1>
<h1 class="test2">World</h1>
<script>
// JS code here
</script>
</body>
</html>
Inside the script
tag:
function demoLoop(){ // remove this line
var elmnt = document.getElementsByTagName("style");
if (elmnt.length === 0) {
// there isn't style objects, so it's more interesting create one
var newStyle = document.createElement("style");
newStyle.innerHTML =
"h1.test1 {" +
"color: green;" +
"}";
document.getElementsByTagName("head")[0].appendChild(newStyle);
} else {
// Using CSSStyleSheet interface
var firstCSS = document.styleSheets[0];
firstCSS.insertRule("h1.test2{color:blue;}"); // at this way (without index specified), will be like an Array unshift() method
}
} // remove this too
demoLoop(); // remove this too
demoLoop(); // remove this too
Another approach to this solution it's using CSSStyleDeclaration
object (docs at w3schools and MDN). But it may not be interesting, considering the risk to override existing rules on the system's CSS.
Use inline CSS. This solve the problem, although depending of the page size (in code lines), the maintenance (by the author itself or other assigned person) of code can be very difficult.
But depending of the context of your role at the institution, or its web system security policies, this might be the unique available solution to you.
Create a file _foobar.html
:
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1 style="color: green;">Hello</h1>
<h1 style="color: blue;">World</h1>
</body>
</html>
How is a browser supposed to render css which is non contiguous?
- Is it supposed to generate some data structure using all the css styles on a page and use that for rendering?
- Or does it render using style information in the order it sees?
(quote adapted)
For a more accurate answer, I suggest Google these articles:
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
Either might be fine, but I don't think there is a definite answer.
None
is better than comparing with ""
, since ""
might be a valid value,""
is probably better, because its actually a string, and you can call string methods on it. If you went with None
, these would lead to exceptions.""
can help with that.If you have a loop, say:
def myfunc (self, mystr = ""):
for other in self.strs:
mystr = self.otherfunc (mystr, other)
then a potential future optimizer would know that str
is always a string. If you used None
, then it might not be a string until the first iteration, which would require loop unrolling to get the same effects. While this isn't a hypothetical (it comes up a lot in my PHP compiler) you should certainly never write your code to take this into account. I just thought it might be interesting :)
After uninstalling too much on my Win7-64bit machine I was stuck here too. I didn't want to reinstall the OS and none of the tricks worked expect for this registry hack below. Most of this trick I found in an old pchelpforum port but I had to adapt it to my 64-bit installation:
(For a 32-bit repair, probably skip the Wow6432Node path)
Now right click in the empty window on the right and add this data (there will probably be at least a Default string value located here, just leave it):
New->Binary Value
Name: InstalledVersion
Type: REG_BINARY
Data: 00 00 00 09 00 00 00 00
New->DWORD (32-bit) Value
Name: InstallMDX
Type: REG_DWORD
Data: 0x00000001
New->String Value
Name: SDKVersion
Type: REG_SZ
Data: 9.26.1590.0
New->String Value
Name: Version
Type: REG_SZ
Data: 4.09.00.0904
Reinstall using latest DXSDK installer. Runtime only option may work too but I didn't test it.
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
With marquee
tag.
HTML
<marquee behavior="scroll" bgcolor="yellow" loop="-1" width="30%">
<i>
<font color="blue">
Today's date is :
<strong>
<span id="time"></span>
</strong>
</font>
</i>
</marquee>
JS
var today = new Date();
document.getElementById('time').innerHTML=today;
Without marquee
tag and with CSS
.
HTML
<p class="marquee">
<span id="dtText"></span>
</p>
CSS
.marquee {
width: 350px;
margin: 0 auto;
background:yellow;
white-space: nowrap;
overflow: hidden;
box-sizing: border-box;
color:blue;
font-size:18px;
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee 15s linear infinite;
}
.marquee span:hover {
animation-play-state: paused
}
@keyframes marquee {
0% { transform: translate(0, 0); }
100% { transform: translate(-100%, 0); }
}
JS
var today = new Date();
document.getElementById('dtText').innerHTML=today;
One of my favorite uses for function pointers is as cheap and easy iterators -
#include <stdio.h>
#define MAX_COLORS 256
typedef struct {
char* name;
int red;
int green;
int blue;
} Color;
Color Colors[MAX_COLORS];
void eachColor (void (*fp)(Color *c)) {
int i;
for (i=0; i<MAX_COLORS; i++)
(*fp)(&Colors[i]);
}
void printColor(Color* c) {
if (c->name)
printf("%s = %i,%i,%i\n", c->name, c->red, c->green, c->blue);
}
int main() {
Colors[0].name="red";
Colors[0].red=255;
Colors[1].name="blue";
Colors[1].blue=255;
Colors[2].name="black";
eachColor(printColor);
}
Copy the image CTRL + C then in Eclipse select drawable folder, right click -> Paste
We already have tons of options to get mean by group, adding one more from mosaic
package.
mosaic::mean(speed~dive, data = df)
#dive1 dive2
#0.579 0.440
This returns a named numeric vector, if needed a dataframe we can wrap it in stack
stack(mosaic::mean(speed~dive, data = df))
# values ind
#1 0.579 dive1
#2 0.440 dive2
data
set.seed(123)
df <- data.frame(dive=factor(sample(c("dive1","dive2"),10,replace=TRUE)),
speed=runif(10))
Just a little improvement to the solution that seems to be posted everywhere now:
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:
solution 1: call alpha's alphaMethod1()
from beta's alphaMethod1()
class Beta extends Alpha
{
public void alphaMethod1()
{
super.alphaMethod1();
}
}
or from any other method of Beta like:
class Beta extends Alpha
{
public void foo()
{
super.alphaMethod1();
}
}
class Test extends Beta
{
public static void main(String[] args)
{
Beta beta = new Beta();
beta.foo();
}
}
solution 2: create alpha's object and call alpha's alphaMethod1()
class Test extends Beta
{
public static void main(String[] args)
{
Alpha alpha = new Alpha();
alpha.alphaMethod1();
}
}
input
fields can be styled as you wish. So instead of zoom, you could have
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
}
EDIT:
You would have to add extra rules like this:
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
cursor: pointer;
-webkit-appearance: none;
appearance: none;
}
Check this fiddle http://jsfiddle.net/p36tqqyq/1/
To open docs automatically in Chrome without them being saved;
Go to the the three vertical dots on your top far right corner in Chrome.
Scroll down to Settings and click.
Scroll down to Show advance settings...
Scroll down to Downloads under Download location: click the Change button and chose tmp folder. Then just close the screen.
Click on any attachments and a small box to the left will appear, it should automatically open if you click on it.
When the bottom left box appears it will contain an arrow; click on it and choose the option "Always open files of this type". Going forward it will open the file instantly instead of the small box appearing to the left and you having to click on it to open. You will have to do it just once for various files such PDF, Excel 2010, Excel 2013 Word, ect.
SELECT a.userid,a.values1,b.mm
FROM table_name a,(SELECT userid,Max(date1)AS mm FROM table_name GROUP BY userid) b
WHERE a.userid=b.userid AND a.DATE1=b.mm;
I was having trouble with mobile touchscreen button styling. This will fix your hover-stick / active button problems.
body, html {
width: 600px;
}
p {
font-size: 20px;
}
button {
border: none;
width: 200px;
height: 60px;
border-radius: 30px;
background: #00aeff;
font-size: 20px;
}
button:active {
background: black;
color: white;
}
.delayed {
transition: all 0.2s;
transition-delay: 300ms;
}
.delayed:active {
transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>
<button>Normal button</button>
<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>
<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures. With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely. This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>
<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a
and b
:
import json
a = json.loads("""
{
"errors": [
{"error": "invalid", "field": "email"},
{"error": "required", "field": "name"}
],
"success": false
}
""")
b = json.loads("""
{
"success": false,
"errors": [
{"error": "required", "field": "name"},
{"error": "invalid", "field": "email"}
]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False
... but that doesn't work, because in each case, the "errors"
item of the top-level dict is a list with the same elements in a different order, and sorted()
doesn't try to sort anything except the "top" level of an iterable.
To fix that, we can define an ordered
function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value)
pairs so that they're orderable):
def ordered(obj):
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj
If we apply this function to a
and b
, the results compare equal:
>>> ordered(a) == ordered(b)
True
You may use this header for this regard: https://github.com/theypsilon/concat
using namespace concat;
assert(concat(1,2,3,4,5) == "12345");
Under the hood you will be using a std::ostringstream.
I think you should do
for index, row in result:
If you wanna access by name.
The documentation reiterates your findings here: https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service
If my memory serves, $stateParams
was introduced later than the original $state.params
, and seems to be a simple helper injector to avoid continuously writing $state.params
.
I doubt there are any best practice guidelines, but context wins out for me. If you simply want access to the params received into the url, then use $stateParams
. If you want to know something more complex about the state itself, use $state
.
I don't have enough reputation to comment so I will add this to the other answers.
Jon Skeet answers excellently, with a beautiful example. Matt B has a point: not all superclasses have supers. Your code would break if you called a super of a super that had no super.
Object oriented programming (which Java is) is all about objects, not functions. If you want task oriented programming, choose C++ or something else. If your object doesn't fit in it's super class, then you need to add it to the "grandparent class", create a new class, or find another super it does fit into.
Personally, I have found this limitation to be one of Java's greatest strengths. Code is somewhat rigid compared to other languages I've used, but I always know what to expect. This helps with the "simple and familiar" goal of Java. In my mind, calling super.super is not simple or familiar. Perhaps the developers felt the same?
U can format any string containing non numeric characters also to your desired format use my util class to format
public static void main(String[] args){
String num = "ab12345*&67890";
System.out.println(PhoneNumberUtil.formateToPhoneNumber(num,"(XXX)-XXX-XXXX",10));
}
u can specify any foramt such as XXX-XXX-XXXX and length of the phone number , if input length is greater than specified length then string will be trimmed.
Get my class from here: https://github.com/gajeralalji/PhoneNumberUtil/blob/master/PhoneNumberUtil.java
Here's a way I do it.
With a conditional:
<Label
{...{
text: label,
type,
...(tooltip && { tooltip }),
isRequired: required
}}
/>
I still prefer using the regular way of passing props down, because it is more readable (in my opinion) in the case of not have any conditionals.
Without a conditional:
<Label text={label} type={type} tooltip={tooltip} isRequired={required} />
class Node:
"""
Class Node
"""
def __init__(self, value):
self.left = None
self.data = value
self.right = None
class Tree:
"""
Class tree will provide a tree as well as utility functions.
"""
def createNode(self, data):
"""
Utility function to create a node.
"""
return Node(data)
def insert(self, node , data):
"""
Insert function will insert a node into tree.
Duplicate keys are not allowed.
"""
#if tree is empty , return a root node
if node is None:
return self.createNode(data)
# if data is smaller than parent , insert it into left side
if data < node.data:
node.left = self.insert(node.left, data)
elif data > node.data:
node.right = self.insert(node.right, data)
return node
def search(self, node, data):
"""
Search function will search a node into tree.
"""
# if root is None or root is the search data.
if node is None or node.data == data:
return node
if node.data < data:
return self.search(node.right, data)
else:
return self.search(node.left, data)
def deleteNode(self,node,data):
"""
Delete function will delete a node into tree.
Not complete , may need some more scenarion that we can handle
Now it is handling only leaf.
"""
# Check if tree is empty.
if node is None:
return None
# searching key into BST.
if data < node.data:
node.left = self.deleteNode(node.left, data)
elif data > node.data:
node.right = self.deleteNode(node.right, data)
else: # reach to the node that need to delete from BST.
if node.left is None and node.right is None:
del node
if node.left == None:
temp = node.right
del node
return temp
elif node.right == None:
temp = node.left
del node
return temp
return node
def traverseInorder(self, root):
"""
traverse function will print all the node in the tree.
"""
if root is not None:
self.traverseInorder(root.left)
print(root.data)
self.traverseInorder(root.right)
def traversePreorder(self, root):
"""
traverse function will print all the node in the tree.
"""
if root is not None:
print(root.data)
self.traversePreorder(root.left)
self.traversePreorder(root.right)
def traversePostorder(self, root):
"""
traverse function will print all the node in the tree.
"""
if root is not None:
self.traversePostorder(root.left)
self.traversePostorder(root.right)
print(root.data)
def main():
root = None
tree = Tree()
root = tree.insert(root, 10)
print(root)
tree.insert(root, 20)
tree.insert(root, 30)
tree.insert(root, 40)
tree.insert(root, 70)
tree.insert(root, 60)
tree.insert(root, 80)
print("Traverse Inorder")
tree.traverseInorder(root)
print("Traverse Preorder")
tree.traversePreorder(root)
print("Traverse Postorder")
tree.traversePostorder(root)
if __name__ == "__main__":
main()
public class Book
{
public int number;
public String title;
public String language;
public int price;
// Add constructor, get, set, as needed.
}
then declare your array as:
Book[] books = new Book[3];
EDIT: In response to O.P.'s confusion, Book should be an object, not an array. Each book should be created on it's own (via a properly designed constructor) and then added to the array. In fact, I wouldn't use an array, but an ArrayList. In other words, you are trying to force data into containers that aren't suitable for the task at hand.
I would venture that 50% of programming is choosing the right data structure for your data. Algorithms naturally follow if there is a good choice of structure.
When properly done, you get your UI class to look like: Edit: Generics added to the following code snippet.
...
ArrayList<Book> myLibrary = new ArrayList<Book>();
myLibrary.add(new Book(1, "Thinking In Java", "English", 4999));
myLibrary.add(new Book(2, "Hacking for Fun and Profit", "English", 1099);
etc.
now you can use the Collections interface and do something like:
int total = 0;
for (Book b : myLibrary)
{
total += b.price;
System.out.println(b); // Assuming a valid toString in the Book class
}
System.out.println("The total value of your library is " + total);
For SSIS you could go with:
RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE())
Expression builder screen:
You can use Kotlin-coroutines
class YoutActivity : AppCompatActivity, CoroutineScope {
override fun onCreate(...) {
launch { yourHeavyMethod() }
}
suspend fun yourHeavyMethod() {
with(Dispatchers.IO){ yourNetworkCall() }
...
...
}
}
You can follow this guide.
If you have <deployment retail="true"/>
in your .NET Framework's machine.config, you won't see detailed error messages. Make sure that setting is false, or not present.
control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).
if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up
for instance, hit Control-shift-L then execute this
CREATE OR REPLACE FUNCTION TEST123() IS
BEGIN
VAR := 2;
end TEST123;
and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "
(You can also see this in "View--Log")
One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)
Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:
$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );
then when you get your cookie next time:
$cookie = json_decode( $_COOKIE[ "cookiename" ] );
you can simply extract the expiry time, which was inserted as data inside the cookie itself..
$expiry = $cookie->expiry;
and additionally the data which will come out as a usable object :)
$data = $cookie->data;
$value1 = $cookie->data->value1;
etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!
For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.
Module ArrayExtension
<Extension()> _
Public Sub Add(Of T)(ByRef arr As T(), item As T)
If arr IsNot Nothing Then
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = item
Else
ReDim arr(0)
arr(0) = item
End If
End Sub
End Module
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
This steps are used in spring boot with self signed ssl certificate implementation
if SSL turns off then HTTPS call will be worked as expected.
https://localhost:8443/test/hello
These are the steps we have to follow,
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650
after key generation has done then copy that file in to the resource foder in your project
server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
now verify the url: https://localhost:8443/test/hello
node-sass is not being installed and it can be one of many reasons
You have not installed it
npm install node-sass --save-dev
You are having a permissions error
sudo npm install --save-dev --unsafe-perm node-sass
You had a memory issue because it tried to make it (build from c code in your platform),this applies to some platforms and node versions
node --max_old_space_size=8000 $(which npm) install node-sass --save-dev
Your node and npm versions are not compatible,which most probably generated a failure in the build process,
In this case use n or nvm to make sure you have the same version in the new and original environment, the one where it did work, as this is usually by using different versions in different environments
Use the CREATE SCHEMA syntax or, in SSMS, drill down through Databases -> YourDatabaseName -> Security -> Schemas. Right-click on the Schemas folder and select "New Schema..."
You can try my answer https://github.com/SCENEE/FloatingPanel. It provides a container view controller to display a "bottom sheet" interface.
It's easy to use and you don't mind any gesture recognizer handling! Also you can track a scroll view's(or the sibling view) in a bottom sheet if needed.
This is a simple example. Please note that you need to prepare a view controller to display your content in a bottom sheet.
import UIKit
import FloatingPanel
class ViewController: UIViewController {
var fpc: FloatingPanelController!
override func viewDidLoad() {
super.viewDidLoad()
fpc = FloatingPanelController()
// Add "bottom sheet" in self.view.
fpc.add(toParent: self)
// Add a view controller to display your contents in "bottom sheet".
let contentVC = ContentViewController()
fpc.set(contentViewController: contentVC)
// Track a scroll view in "bottom sheet" content if needed.
fpc.track(scrollView: contentVC.tableView)
}
...
}
Here is another example code to display a bottom sheet to search a location like Apple Maps.
I had the same problem but I was confused with @Vladislav's answer and couldn't seem to find the solution from that. Of course, my problem may not be exactly the same as I encountered the problem when trying to upgrade XAMPP, but it also gave the same Error 1067 message.
With further search I found this:
The answer from that is straightforward, that is, to completely clean up the folder, which doesn't always happen. As in regards to XAMPP, I guess I backed up the necessary files first (data folder from mysql folder and the htdocs folder). Uninstall XAMPP. Check the xampp folder for any content that remains and delete everything. You may want to reboot afterwards, just in case. Then reinstall XAMPP. Copy the backed-up folders back to their respective places, and hopefully, mySql will work again in XAMPP.
This should solve the issue.
Looking forward to Web Animations in 2020.
async function moveToPosition(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
transform: `translateY(${el.getBoundingClientRect().top}px)`
},
], {
duration: durationInMs,
easing: 'ease-in',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeIn(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
opacity: '0.5',
offset: 0.5
},
{
opacity: '1',
offset: 1
}
], {
duration: durationInMs,
easing: 'linear',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeInSections() {
for (const section of document.getElementsByTagName('section')) {
await fadeIn(section, 200);
}
}
window.addEventListener('load', async() => {
await moveToPosition(document.getElementById('headerContent'), 500);
await fadeInSections();
await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
height: 100vh;
}
header {
height: 20%;
}
.text-center {
text-align: center;
}
.leading-none {
line-height: 1;
}
.leading-3 {
line-height: .75rem;
}
.leading-2 {
line-height: .25rem;
}
.bg-black {
background-color: rgba(0, 0, 0, 1);
}
.bg-gray-50 {
background-color: rgba(249, 250, 251, 1);
}
.pt-12 {
padding-top: 3rem;
}
.pt-2 {
padding-top: 0.5rem;
}
.text-lightGray {
color: lightGray;
}
.container {
display: flex;
/* or inline-flex */
justify-content: space-between;
}
.container section {
padding: 0.5rem;
}
.opacity-0 {
opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Web site created using create-snowpack-app" />
<link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>
<body>
<header class="bg-gray-50">
<div id="headerContent">
<h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
<p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
</div>
</header>
<div class="container">
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 1</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 2</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 3</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
</div>
<footer class="opacity-0">
<h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
<p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
</footer>
</body>
</html>
_x000D_
I've just came across the same problem and found the chrome extension Open IE.
That's the only one what works for me (Chrome V46 & V52). The only disadvantefge is, that you need to install an additional program, means you need admin rights.
To convert int to char use:
int a=8;
char c=a+'0';
printf("%c",c); //prints 8
To Convert char to int use:
char c='5';
int a=c-'0';
printf("%d",a); //prints 5
Everyone else has already given you the reason you're getting an error, but here's the best way to do what you want to do:
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
You may also have to use it in onPause
or onDestroy
of Activity
Life Cycle:
//you may call the cancel() method but if it is not handled in doInBackground() method
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
loginTask.cancel(true);
where loginTask
is object of your AsyncTask
Thank you.
You could deploy a custom BeanPostProcessor in your application context to do it. Or if you don't mind implementing a Spring interface in your bean, you could use the InitializingBean interface or the "init-method" directive (same link).