I'm not sure if you need source code. There is a free online JavaScript formatter at http://www.blackbeltcoder.com/Resources/JSFormatter.aspx.
Empty is a subset of any string.
Think of them as what is between every two characters.
Kind of the way there are an infinite number of points on any sized line...
(Hmm... I wonder what I would get if I used calculus to concatenate an infinite number of empty strings)
Note that "".equals("") only though.
You can use the google docs OCR reader.
You are looking for display:
document.getElementById("endTimeLabel").style.display = 'none';
document.getElementById("endTimeLabel").style.display = 'block';
Edit: You could also easily reuse your validation function.
HTML:
<span id="startDateLabel">Start date/time: </span>
<input id="startDateStr" name="startDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="startDateCalendarTrigger">...</button>
<input id="startDateTime" type="text" size="8" name="startTime" value="12:00 AM" onchange="validateHHMM(this.value, 'startTimeLabel');"/>
<label id="startTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label><br />
<span id="endDateLabel">End date/time: </span>
<input id="endDateStr" name="endDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="endDateCalendarTrigger">...</button>
<input id="endDateTime" type="text" size="8" name="endTime" value="12:00 AM" onchange="validateHHMM(this.value, 'endTimeLabel');"/>
<label id="endTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label>
Javascript:
function validateHHMM(value, message) {
var isValid = /^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/.test(value);
if (isValid) {
document.getElementById(message).style.display = "none";
}else {
document.getElementById(message).style.display= "inline";
}
return isValid;
}
The game in question was definitely Robowar for the Mac. My son had a lot of fun with it and went on to program real robots.
As mentioned earlier by Proud, there is a wiki page for it: http://en.wikipedia.org/wiki/RoboWar
Although there has not been a lot of activity surrounding the game over the last few years, there was a tournament held recently, and there is a yahoo email group.
If it's a static method, you can call it by using the class name in place of an object.
There is no "standard place" for a sqlite database. The file's location is specified to the library, and may be in your home directory, in the invoking program's folder, or any other place.
If it helps, sqlite databases are, by convention, named with a .db
file extension.
This is an old question I know, but this is in the top five for several related Google searches. Here's the CSS-only solution without changing the images to background images:
width: auto;
height: auto;
max-width: MaxSize;
max-height: MaxSize;
"MaxSize" is a placeholder for whatever max-width
and max-height
you want to use, in pixels or percentage. auto
will increase (or decrease) the width and height to occupy the space you specify with MaxSize. It will override any defaults for images you or the viewer's browser might have for images. I've found it's especially important on Android's Firefox. Pixels or percentages work for max size. With both the height and width set to auto
, the aspect ratio of the original image will be retained.
If you want to fill the space entirely and don't mind the image being larger than its original size, change the two max-width
s to min-width: 100%
- this will make them completely occupy their space and maintain aspect ratio. You can see an example of this with a Twitter profile's background image.
To do it for your whole collection you can also use a loop (based on Niels example):
db.status.find().forEach(function(doc){
doc._id=doc.UserId; db.status_new.insert(doc);
});
db.status_new.renameCollection("status", true);
In this case UserId was the new ID I wanted to use
get()
returned more than one topic -- it returned 2!
The above error indicatess that you have more than one record in the DB related to the specific parameter you passed while querying using get()
such as
Model.objects.get(field_name=some_param)
To avoid this kind of error in the future, you always need to do query as per your schema design. In your case you designed a table with a many-to-many relationship so obviously there will be multiple records for that field and that is the reason you are getting the above error.
So instead of using get()
you should use filter()
which will return multiple records. Such as
Model.objects.filter(field_name=some_param)
Please read about how to make queries in django here.
public String hasNums(String str) {
char[] nums = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] toChar = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
toChar[i] = str.charAt(i);
for (int j = 0; j < nums.length; j++) {
if (toChar[i] == nums[j]) { return str; }
}
}
return "None";
}
Use this :
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.
One is __str__
, the other is __repr__
__str__
will return a human readable string.
__repr__
will return an internal representation.
__repr__
can be invoked on an object by calling repr(obj)
or by using backticks `obj`
.
When printing lists as well as other container classes, the contained elements will be printed using __repr__
.
How to use an IF statement in the MySQL "select list":
select if (1>2, 2, 3); //returns 3
select if(1<2,'yes','no'); //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes'); //returns no
How to use an IF statement in the MySQL where clause search condition list:
create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')
select * from penguins where 3 = id
-->3 skipper
select * from penguins where (if (true, 2, 3)) = id
-->2 kowalski
How to use an IF statement in the MySQL "having clause search conditions":
select * from penguins
where 1=1
having (if (true, 2, 3)) = id
-->1 rico
Use an IF statement with a column used in the select list to make a decision:
select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1
If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.
I would strongly recommend not using the default file loading as it is horrendously slow. You should look into the numpy functions and the IOpro functions (e.g. numpy.loadtxt()).
http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html
https://store.continuum.io/cshop/iopro/
Then you can break your pairwise operation into chunks:
import numpy as np
import math
lines_total = n
similarity = np.zeros(n,n)
lines_per_chunk = m
n_chunks = math.ceil(float(n)/m)
for i in xrange(n_chunks):
for j in xrange(n_chunks):
chunk_i = (function of your choice to read lines i*lines_per_chunk to (i+1)*lines_per_chunk)
chunk_j = (function of your choice to read lines j*lines_per_chunk to (j+1)*lines_per_chunk)
similarity[i*lines_per_chunk:(i+1)*lines_per_chunk,
j*lines_per_chunk:(j+1)*lines_per_chunk] = fast_operation(chunk_i, chunk_j)
It's almost always much faster to load data in chunks and then do matrix operations on it than to do it element by element!!
You can also use:
your_dataframe.insert(loc=0, value=np.nan, column="")
where loc
is your empty row index.
In PostGIS Geometry is preferred over Geography (round earth model) because the computations are much simpler therefore faster. It also has MANY more available functions but is less accurate over very long distances.
Import your CSV long and lat fields to DECIMAL(10,6)
columns. 6 digits is 10cm precision, should be plenty for most use cases. Then cast your imported data to the correct SRID
The wrong way!
/* try what seems the obvious solution */
DROP TABLE IF EXISTS public.test_geom_bad;
-- Big Ben, London
SELECT ST_SetSRID(ST_MakePoint(-0.116773, 51.510357),4326) AS geom
INTO public.test_geom_bad;
The CORRECT way
/* add the necessary CAST to make it work */
DROP TABLE IF EXISTS public.test_geom_correct;
SELECT ST_SetSRID(ST_MakePoint(-0.116773, 51.510357),4326)::geometry(Geometry, 4326) AS geom
INTO public.test_geom_correct;
Verify SRID is not zero!
/* now observe the incorrect SRID 0 */
SELECT * FROM public.geometry_columns
WHERE f_table_name IN ('test_geom_bad','test_geom_correct');
Validate the order of your long lat parameter using a WKT viewer and
SELECT ST_AsEWKT(geom) FROM public.test_geom_correct
Then index it for best performance
CREATE INDEX idx_target_table_geom_gist
ON target_table USING gist(geom);
Try something like this:
foreach (ListItem listItem in YrChkBox.Items)
{
if (listItem.Selected)
{
//do some work
}
else
{
//do something else
}
}
Just construct a new Date
object without any arguments; this will assign the current date and time to the new object.
import java.util.Date;
Date d = new Date();
In the words of the Javadocs for the zero-argument constructor:
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
Make sure you're using java.util.Date
and not java.sql.Date
-- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)
In case you're working with a regular old System.Collections.IEnumerable
instead of IEnumerable<T>
you can use enumerable.Cast<object>().ToList()
I solved:
Just turn off USB debugging and re-enable debugging it immediately
Yet another solution.
Add ErrorControllers or static page to with 404 error information.
Modify your web.config (in case of controller).
<system.web>
<customErrors mode="On" >
<error statusCode="404" redirect="~/Errors/Error404" />
</customErrors>
</system.web>
Or in case of static page
<system.web>
<customErrors mode="On" >
<error statusCode="404" redirect="~/Static404.html" />
</customErrors>
</system.web>
This will handle both missed routes and missed actions.
Here's a quick solution for this. Say, you have a data frame X with three columns A, B and C:
> X<-data.frame(A=c(1,2),B=c(3,4),C=c(5,6))
> X
A B C
1 1 3 5
2 2 4 6
If I want to remove a column, say B, just use grep on colnames to get the column index, which you can then use to omit the column.
> X<-X[,-grep("B",colnames(X))]
Your new X data frame would look like the following (this time without the B column):
> X
A C
1 1 5
2 2 6
The beauty of grep is that you can specify multiple columns that match the regular expression. If I had X with five columns (A,B,C,D,E):
> X<-data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,8),E=c(9,10))
> X
A B C D E
1 1 3 5 7 9
2 2 4 6 8 10
Take out columns B and D:
> X<-X[,-grep("B|D",colnames(X))]
> X
A C E
1 1 5 9
2 2 6 10
EDIT: Considering the grepl suggestion of Matthew Lundberg in the comments below:
> X<-data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,8),E=c(9,10))
> X
A B C D E
1 1 3 5 7 9
2 2 4 6 8 10
> X<-X[,!grepl("B|D",colnames(X))]
> X
A C E
1 1 5 9
2 2 6 10
If I try to drop a column that's non-existent,nothing should happen:
> X<-X[,!grepl("G",colnames(X))]
> X
A C E
1 1 5 9
2 2 6 10
My KISS approach to skip some folders is chaining Get-ChildItem
calls. This excludes root level folders but not deeper level folders if that is what you want.
Get-ChildItem -Exclude folder1,folder2 | Get-ChildItem -Recurse | ...
What I like from this approach is that it is simple and easy to remember. If you don't want to mix folders and files in the first search a filter would be needed.
bash
4.2 introduces the lastpipe
option, which allows your code to work as written, by executing the last command in a pipeline in the current shell, rather than a subshell.
shopt -s lastpipe
echo "hello world" | read test; echo test=$test
Single line, no modules necessary, uses current logged user:
(New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")).FindOne().GetDirectoryEntry().memberOf
Kudos to this vbs/powershell article: http://technet.microsoft.com/en-us/library/ff730963.aspx
$html = file_get_contents("http://www.somesite.com/");
$dom = new DOMDocument();
$dom->loadHTML(htmlspecialchars($html));
echo $dom;
try this
you could also change from the .get()
method to the .getJSON()
method, jQuery will then parse the string returned as data
to a javascript object and/or array that you can then reference like any other javascript object/array.
using your code above, if you changed .get
to .getJSON
, you should get an alert of [object Object]
for each element in the array. If you changed the alert to alert(item.name)
you will get the names.
with your VARCHAR, you may also need to specify the length, or its usually good to
What about grabbing the text, making a sting of it, then putting it into the query witrh
String TableName = "ComplicatedTableNameHere";
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
String editTextString1 = editText1.getText().toString();
BROKEN DOWN
String TableName = "ComplicatedTableNameHere";
//sets the table name as a string so you can refer to TableName instead of writing out your table name everytime
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere);
//gets the text from your edit text fieldfield
//editText1 = your edit text name
//EditTextIDhere = the id of your text field
String editTextString1 = editText1.getText().toString();
//sets the edit text as a string
//editText1 is the name of the Edit text from the (EditText) we defined above
//editTextString1 = the string name you will refer to in future
then use
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (Column_Name, Column_Name2, Column_Name3, Column_Name4)"
+ " VALUES ( "+EditTextString1+", 'Column_Value2','Column_Value3','Column_Value4');");
Hope this helps some what...
NOTE each string is within
'"+stringname+"'
its the 'and' that enable the multi line element of the srting, without it you just get the first line, not even sure if you get the whole line, it may just be the first word
From verify
documentation:
If a certificate is found which is its own issuer it is assumed to be the root CA.
In other words, root CA needs to self signed for verify to work. This is why your second command didn't work. Try this instead:
openssl verify -CAfile RootCert.pem -untrusted Intermediate.pem UserCert.pem
It will verify your entire chain in a single command.
I had this error message having started up a second Tomcat server on a Linux server.
$CATALINA_PID was set but the specified file does not exist. Is Tomcat running? Stop aborted.
When starting up the 2nd Tomcat I had set CATALINA_PID as asked but my mistake was to set it to a directory (I assumed Tomcat would write a default file name in there with the pid).
The fix was simply to change my CATALINA_PID to add a file name to the end of it (I chose catalina.pid from the above examples). Next I went to the directory and did a simple:
touch catalina.pid
creating an empty file of the correct name. Then when I did my shutdown.sh I got the message back saying:
PID file is empty and has been ignored.
Tomcat stopped.
I didn't have the option to kill Tomcat as the JVM was in use so I was glad I found this.
Notice that if the file's parent folder doesn't exist you'll get the same error:
IOError: [Errno 2] No such file or directory:
Below is another solution which handles this case:
(*) I used sys.stdout
and print
instead of f.write
just to show another use case
# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print_to_log_file(folder_path, "Some File" ,"Some Content")
Where the internal print_to_log_file
just take care of the file level:
# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):
#1) Save a reference to the original standard output
original_stdout = sys.stdout
#2) Choose the mode
write_append_mode = 'a' #Append mode
file_path = folder_path + file_name
if (if not os.path.exists(file_path) ):
write_append_mode = 'w' # Write mode
#3) Perform action on file
with open(file_path, write_append_mode) as f:
sys.stdout = f # Change the standard output to the file we created.
print(file_path, content_to_write)
sys.stdout = original_stdout # Reset the standard output to its original value
Consider the following states:
'w' --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a' --> Append to file
'a+' --> Append to file, Create it if doesn't exist
In your case I would use a different approach and just use 'a'
and 'a+'
.
The main problem to all these valid solutions is that you are trying to move up the scroll when it isn't drawn on screen yet.
You need to wait until scroll view is on screen, then move it to up with any of these solutions. This is better solution than a postdelay, because you don't mind about the delay.
// Wait until my scrollView is ready
scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Ready, move up
scrollView.fullScroll(View.FOCUS_UP);
}
});
Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300
Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.
Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.
PURE JS (works also when arrays and subarrays has more than 2 elements with arbitrary order). If strings contains ,
use as join('-')
parametr character (can be utf) which is not used in strings
array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join()
var array1 = [['a', 'b'], ['b', 'c']];_x000D_
var array2 = [['b', 'c'], ['b', 'a']];_x000D_
_x000D_
var r = array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join();_x000D_
_x000D_
console.log(r);
_x000D_
I too had to face the same problem. This worked for me. Right click and run as admin than run usual command to install. But first run update command to update the pip
python -m pip install --upgrade pip
I would make a very simple VBScript file and call it using CScript to parse the command line parameters.
Something like the following saved in MessageBox.vbs
:
Set objArgs = WScript.Arguments
messageText = objArgs(0)
MsgBox messageText
Which you would call like:
cscript MessageBox.vbs "This will be shown in a popup."
MsgBox
reference if you are interested in going this route.
Inspired by the insightful answers on this page, I created a mixed approach, which I consider the simplest and more flexible one. What do you think?
First, I define the usage in a variable, which allows me to reuse it in different contexts. The format is very simple, almost WYSIWYG, without the need to add any control characters. This seems reasonably portable to me (I ran it on MacOS and Ubuntu)
__usage="
Usage: $(basename $0) [OPTIONS]
Options:
-l, --level <n> Something something something level
-n, --nnnnn <levels> Something something something n
-h, --help Something something something help
-v, --version Something something something version
"
Then I can simply use it as
echo "$__usage"
or even better, when parsing parameters, I can just echo it there in a one-liner:
levelN=${2:?"--level: n is required!""${__usage}"}
I've been using keyup on a number field, but today I noticed in chrome the input has up/down buttons to increase/decrease the value which aren't recognized by keyup.
My solution is to use keyup and change together:
(keyup)="unitsChanged[i] = true" (change)="unitsChanged[i] = true"
Initial tests indicate this works fine, will post back if any bugs found after further testing.
The OnChange
event is a good choice. But if a user select the same image, the event will not be triggered because the current value is the same as the previous.
The image is the same with a width changed, for example, and it should be uploaded to the server.
To prevent this problem you could to use the following code:
$(document).ready(function(){
$("input[type=file]").click(function(){
$(this).val("");
});
$("input[type=file]").change(function(){
alert($(this).val());
});
});
Disabling pyright worked perfectly for me on VS.
This gives me the best result:
Intent intent;
if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
} else {
String[] mimeTypes =
{"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
"application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
"application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
"text/plain",
"application/pdf",
"application/zip", "application/vnd.android.package-archive"};
intent = new Intent(Intent.ACTION_GET_CONTENT); // or ACTION_OPEN_DOCUMENT
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
}
Instead of doing all these greps and stuff, I'd advise you to use ps capabilities of changing output format.
ps -o cmd= -p 12345
You get the cmmand line of a process with the pid specified and nothing else.
This is POSIX-conformant and may be thus considered portable.
You could also use zip
import matplotlib.pyplot as plt
l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
x, y = zip(*l)
plt.plot(x, y)
you can use grep incase you are not keen in the sequence of the pattern.
grep -l "pattern1" filepattern*.* | xargs grep "pattern2"
example
grep -l "vector" *.cpp | xargs grep "map"
grep -l
will find all the files which matches the first pattern, and xargs will grep for the second pattern. Hope this helps.
I added the spring folder to the build path and, after clean&build, it worked.
On Visual Studio 2015 just go to: help/about Microsoft Visual Studio Then you will see something like this:
Microsoft Visual Studio Enterprise 2015 Version 14.0.24720.00 Update 1 Microsoft .NET Framework Version 4.6.01055
...
TypeScript 1.7.6.0 TypeScript for Microsoft Visual Studio
....
In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service
to https://my-service
helped.
First create a Project With PdfCreation in Android Studio
Then Follow below steps:
1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/PDF");
System.out.print(myDir.toString());
myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} // Open Document for Writting into document
document.open(); // User Define Method
addMetaData(document);
try {
addTitlePage(document);
} catch (DocumentException e) {
e.printStackTrace();
} // Close Document after writting all content
document.close();
5. public void addMetaData(Document document)
{
document.addTitle("RESUME");
document.addSubject("Person Info");
document.addKeywords("Personal, Education, Skills");
document.addAuthor("TAG");
document.addCreator("TAG");
}
public void addTitlePage(Document document) throws DocumentException
{ // Font Style for Document
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
| Font.UNDERLINE, BaseColor.GRAY);
Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
prHead.setFont(titleFont); // Add item into Paragraph
prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
myTable.setWidthPercentage(100.0f); // Create New Cell into Table
PdfPCell myCell = new PdfPCell(new Paragraph(""));
myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
myTable.addCell(myCell);
prHead.setFont(catFont);
prHead.add("\nName1 Name2\n");
prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
document.add(prHead);
document.add(myTable);
document.add(myTable); // Now Start another New Paragraph
Paragraph prPersinalInfo = new Paragraph();
prPersinalInfo.setFont(smallBold);
prPersinalInfo.add("Address 1\n");
prPersinalInfo.add("Address 2\n");
prPersinalInfo.add("City: SanFran. State: CA\n");
prPersinalInfo.add("Country: USA Zip Code: 000001\n");
prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: [email protected] \n");
prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
document.add(prPersinalInfo);
document.add(myTable);
document.add(myTable);
Paragraph prProfile = new Paragraph();
prProfile.setFont(smallBold);
prProfile.add("\n \n Profile : \n ");
prProfile.setFont(normal);
prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
prProfile.setFont(smallBold);
document.add(prProfile); // Create new Page in PDF
document.newPage();
}
Here you go: Here you go: Create a System Restore Point. Log on under an admin account. Delete the folder C:\SomeUser. Move the folder c:\Users\SomeUser so that it becomes c:\SomeUser. Open the registry editor. Navigate to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList. Search for "ProfileImagePath" until you find the one that points at c:\Users\SomeUser. Modify it so that it points at c:\SomeUser. Use System Restore in case things go wrong.
I forget where I first saw it mentioned but you can actually embed your labels in a container elsewhere as long as you have the for=
attribute set. So, let's check out a sample on SO:
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
background-color: #262626;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
.radio-button {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
#filter {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.filter-label {_x000D_
display: inline-block;_x000D_
border: 4px solid green;_x000D_
padding: 10px 20px;_x000D_
font-size: 1.4em;_x000D_
text-align: center;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
main {_x000D_
clear: left;_x000D_
}_x000D_
_x000D_
.content {_x000D_
padding: 3% 10%;_x000D_
display: none;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
font-size: 2em;_x000D_
}_x000D_
_x000D_
.date {_x000D_
padding: 5px 30px;_x000D_
font-style: italic;_x000D_
}_x000D_
_x000D_
.filter-label:hover {_x000D_
background-color: #505050;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~#filter .featured,_x000D_
#personal-radio:checked~#filter .personal,_x000D_
#tech-radio:checked~#filter .tech {_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~main .featured {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#personal-radio:checked~main .personal {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#tech-radio:checked~main .tech {_x000D_
display: block;_x000D_
}
_x000D_
<input type="radio" id="featured-radio" class="radio-button" name="content-filter" checked="checked">_x000D_
<input type="radio" id="personal-radio" class="radio-button" name="content-filter" value="Personal">_x000D_
<input type="radio" id="tech-radio" class="radio-button" name="content-filter" value="Tech">_x000D_
_x000D_
<header id="filter">_x000D_
<label for="featured-radio" class="filter-label featured" id="feature-label">Featured</label>_x000D_
<label for="personal-radio" class="filter-label personal" id="personal-label">Personal</label>_x000D_
<label for="tech-radio" class="filter-label tech" id="tech-label">Tech</label>_x000D_
</header>_x000D_
_x000D_
<main>_x000D_
<article class="content featured tech">_x000D_
<header>_x000D_
<h1>Cool Stuff</h1>_x000D_
<h3 class="date">Today</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
I'm showing cool stuff in this article!_x000D_
</p>_x000D_
</article>_x000D_
_x000D_
<article class="content personal">_x000D_
<header>_x000D_
<h1>Not As Cool</h1>_x000D_
<h3 class="date">Tuesday</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
This stuff isn't nearly as cool for some reason :(;_x000D_
</p>_x000D_
</article>_x000D_
_x000D_
<article class="content tech">_x000D_
<header>_x000D_
<h1>Cool Tech Article</h1>_x000D_
<h3 class="date">Last Monday</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
This article has awesome stuff all over it!_x000D_
</p>_x000D_
</article>_x000D_
_x000D_
<article class="content featured personal">_x000D_
<header>_x000D_
<h1>Cool Personal Article</h1>_x000D_
<h3 class="date">Two Fridays Ago</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
This article talks about how I got a job at a cool startup because I rock!_x000D_
</p>_x000D_
</article>_x000D_
</main>
_x000D_
Whew. That was a lot for a "sample" but I feel it really drives home the effect and point: we can certainly select a label for a checked input control without it being a sibling. The secret lies in keeping the input
tags a child to only what they need to be (in this case - only the body
element).
Since the label
element doesn't actually utilize the :checked
pseudo selector, it doesn't matter that the labels are stored in the header
. It does have the added benefit that since the header
is a sibling element we can use the ~
generic sibling selector to move from the input[type=radio]:checked
DOM element to the header
container and then use descendant/child selectors to access the label
s themselves, allowing the ability to style them when their respective radio boxes/checkboxes are selected.
Not only can we style the labels, but also style other content that may be descendants of a sibling container relative to all of the input
s. And now for the moment you've all been waiting for, the JSFIDDLE! Go there, play with it, make it work for you, find out why it works, break it, do what you do!
Hopefully that all makes sense and fully answers the question and possibly any follow ups that may crop up.
private List<String[]> addresses = new ArrayList<String[]>();
this will work defenitely...
$('#saveBtn').off('click').on('click',function(){
saveQuestion(id)
});
I work primarily with Windows development machines and servers.
I just wanted to point out (at least for NET.Core 2.0 and above) the only thing needed is to execute dotnet --info
in a command prompt to get information about the latest version installed. If .NET Core is installed you will get some response.
On my development machine (Windows 10) the result is as follows. SDK is 2.1.2 and runtime is 2.0.3.
.NET Command Line Tools (2.1.2)
Product Information:
Version: 2.1.2
Commit SHA-1 hash: 5695315371
Runtime Environment:
OS Name: Windows
OS Version: 10.0.15063
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\2.1.2\
Microsoft .NET Core Shared Framework Host
Version : 2.0.3
Build : a9190d4a75f4a982ae4b4fa8d1a24526566c69df
On one of my servers running Windows Server 2016 with Windows Server Hosting pack (no SDK) result is as follows. No SDK, runtime is 2.0.3.
Microsoft .NET Core Shared Framework Host
Version : 2.0.3
Build : a9190d4a75f4a982ae4b4fa8d1a24526566c69df
Cheers !
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
CSS file
.selectDD {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
JS file
$(document).ready(function () {
$("#selectDropdownID").next().children().eq(0).addClass("selectDD");
});
Font awesome use SVG icons. So, you can resize it for your requirment.
just use CSS class for that,
.large-icon{
font-size:10em;
//or
font-size:200%;
//or
font-size:50px;
}
All these work:
#include <iostream>
using namespace std;
//Good, because manual memory management isn't needed and this uses
//less heap memory (or no heap memory) so this is safer if
//used in a low memory situation
void f() { throw string("foo"); }
//Valid, but avoid manual memory management if there's no reason to use it
void g() { throw new string("foo"); }
//Best. Just a pointer to a string literal, so no allocation is needed,
//saving on cleanup, and removing a chance for an allocation to fail.
void h() { throw "foo"; }
int main() {
try { f(); } catch (string s) { cout << s << endl; }
try { g(); } catch (string* s) { cout << *s << endl; delete s; }
try { h(); } catch (const char* s) { cout << s << endl; }
return 0;
}
You should prefer h to f to g. Note that in the least preferable option you need to free the memory explicitly.
Sure, a very similar question was asked before. Set the controller for ajax requests:
public ActionResult Show()
{
if (Request.IsAjaxRequest())
{
return PartialView("Your_partial_view", new Model());
}
else
{
return View();
}
}
Set the action link as wanted:
@Ajax.ActionLink("Show",
"Show",
null,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
OnComplete = "your_js_function();" })
Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.
Even you don't need to measure the length of string. A ! operator can solve everything for you. Remember always: !(empty string) = true !(some string) = false
So you could write:
<input ng-model="somefield">
<span ng-show="!somefield">Sorry, the field is empty!</span>
<span ng-hide="!somefield">Thanks. Successfully validated!</span>
This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g
I'm using Argos reporting system as a front end and Oracle in back. I just encountered this error and it was caused by a string with a double quote at the start and a single quote at the end. Replacing the double quote with a single solved the issue.
Do like jQuery does! (the essence)
function parseJSON(data) {
return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))();
}
// testing
obj = parseJSON('{"name":"John"}');
alert(obj.name);
This way you don't need any external library and it still works on old browsers.
I really like working with Eclipse and Java though (new to Java), because it throws errors in the editor if you are missing an EH handler. That makes things a LOT harder to forget to handle an exception...
Plus, with the IDE tools, it adds the try / catch block or another catch block automatically.
As my understanding, the 'Apartment' is used to protect the COM objects from multi-threading issues.
If a COM object is not thread-safe, it should declare it as a STA object. Then only the thread who creates it can access it. The creation thread should declare itself as a STA thread. Under the hood, the thread stores the STA information in its TLS(Thread Local Storage). We call this behavior as that the thread enters a STA apartment. When other threads want to access this COM object, it should marshal the access to the creation thread. Basically, the creation thread uses messages mechanism to process the in-bound calls.
If a COM object is thread-safe, it should declare it as a MTA object. The MTA object can be accessed by multi-threads.
Try
mount -o remount,rw /system
If no error message is printed, it works.
Or, you should do the following.
First, make sure the fs type.
mount
Issue this command to find it out.
Then
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
Note that the fs(yaffs2) and device(/dev/block/mtdblock3) are depend on your system.
The following example the fastest (not parallelized) way list files and sub-folders in a directory tree handling exceptions. It would be faster to use Directory.EnumerateDirectories using SearchOption.AllDirectories to enumerate all directories, but this method will fail if hits a UnauthorizedAccessException or PathTooLongException.
Uses the generic Stack collection type, which is a last in first out (LIFO) stack and does not use recursion. From https://msdn.microsoft.com/en-us/library/bb513869.aspx, allows you to enumerate all sub-directories and files and deal effectively with those exceptions.
public class StackBasedIteration
{
static void Main(string[] args)
{
// Specify the starting folder on the command line, or in
// Visual Studio in the Project > Properties > Debug pane.
TraverseTree(args[0]);
Console.WriteLine("Press any key");
Console.ReadKey();
}
public static void TraverseTree(string root)
{
// Data structure to hold names of subfolders to be
// examined for files.
Stack<string> dirs = new Stack<string>(20);
if (!System.IO.Directory.Exists(root))
{
throw new ArgumentException();
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.EnumerateDirectories(currentDir); //TopDirectoryOnly
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
string[] files = null;
try
{
files = System.IO.Directory.EnumerateFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
foreach (string file in files)
{
try
{
// Perform whatever action is required in your scenario.
System.IO.FileInfo fi = new System.IO.FileInfo(file);
Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
Console.WriteLine(e.Message);
continue;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
foreach (string str in subDirs)
dirs.Push(str);
}
}
}
I just had this issue as well on a server I own, and the root cause was APC. I commented out the "apc.so" extension in the php.ini file, reloaded Apache, and the sites came right back up.
Cython is definitely the way to go, unless you anticipate writing Java wrappers, in which case SWIG may be preferable.
I recommend using the runcython
command line utility, it makes the process of using Cython extremely easy. If you need to pass structured data to C++, take a look at Google's protobuf library, it's very convenient.
Here is a minimal examples I made that uses both tools:
https://github.com/nicodjimenez/python2cpp
Hope it can be a useful starting point.
*Changes/Notes to make this work for Xcode 3.2.1 and iPhone SDK 3.1.2
Manual Deployment over WiFi
2) Be sure to restart Xcode after modifying the Info.plist
3) The "uicache" command is not found, using killall -HUP SpringBoard worked fine for me.
Other then that, I can confirm this works fine.
Mac users, using PwnageTool 3.1.4 worked great for Jailbreaking (DL via torrent).
function dropdownlist(listindex)
{
document.getElementById("ddlCity").options.length = 0;
switch (listindex)
{
case "Karnataka":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("Dharawad", "Dharawad");
document.getElementById("ddlCity").options[2] = new Option("Haveri", "Haveri");
document.getElementById("ddlCity").options[3] = new Option("Belgum", "Belgum");
document.getElementById("ddlCity").options[4] = new Option("Bijapur", "Bijapur");
break;
case "Tamilnadu":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("dgdf", "dgdf");
document.getElementById("ddlCity").options[2] = new Option("gffd", "gffd");
break;
}
}
* State: --Select-- Karnataka Tamilnadu Andra pradesh Telngana
<div>
<p>
<label id="lblCt">
<span class="red">*</span>
City:</label>
<select id="ddlCity">
<!-- <option>--Select--</option>
<option value="1">Dharawad</option>
<option value="2">Belgum</option>
<option value="3">Bagalkot</option>
<option value="4">Haveri</option>
<option>Hydrabadh</option>
<option>Vijat vada</option>-->
</select>
<label id="lblCity"></label>
</p>
</div>
I had the same question a couple of weeks ago and was evaluating both JSLint and JSHint.
Contrary to the answers in this question, my conclusion was not:
By all means use JSLint.
Or:
If you're looking for a very high standard for yourself or team, JSLint.
As you can configure almost the same rules in JSHint as in JSLint. So I would argue that there's not much difference in the rules you could achieve.
So the reasons to choose one over another are more political than technical.
We've finally decided to go with JSHint because of the following reasons:
In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).
Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396
Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396
Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):
In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.
Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.
I know the OP is asking for a mysql
answer but since I found the other answers not working for me,
order by
So to save time for others like me, just index the row after retrieving them from database
example in PHP:
$users = UserRepository::loadAllUsersAndSortByScore();
foreach($users as $index=>&$user){
$user['rank'] = $index+1;
}
example in PHP using offset and limit for paging:
$limit = 20; //page size
$offset = 3; //page number
$users = UserRepository::loadAllUsersAndSortByScore();
foreach($users as $index=>&$user){
$user['rank'] = $index+1+($limit*($offset-1));
}
Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here
http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/
for a list of invalid characters that you may want to check for.
Update
Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).
Dim WS As Worksheet
Dim i As Long
With ThisWorkbook
Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With
For i = 1 To 1000
DoEvents
Next i
WS.Name = txtSheetName.Value
Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
Some of the suggested methods are basing on system objects (for example on the 'sys.objects'). They are assuming these system objects contain enough records to generate our numbers.
I would not base on anything which does not belong to my application and over which I do not have full control. For example: the content of these sys tables may change, the tables may not be valid anymore in new version of SQL etc.
As a solution, we can create our own table with records. We then use that one instead these system related objects (table with all numbers should be fine if we know the range in advance otherwise we could go for the one to do the cross join on).
The CTE based solution is working fine but it has limits related to the nested loops.
Just in case someone else comes across this, to clarify the answer `n is grave accent n, not single tick n
Check for missing folders that are required by the server, in my case it was UPLOADS folder in programData which was deleted by empty folder cleaner utility that I used earlier.
How did I find out:
run the server config file my.ini(in my case it was in programData) as the defaults-file param for mysqld (don't forget to use --console option to view error log on screen) 'mysqld --defaults-file="C:\ProgramData\MySQL\MySQL Server 8.0\my.ini" --console'
Error:
mysqld: Can't read dir of 'C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\' (OS errno 2 - No such file or directory)
Solution:
Once I manually created the Uploads folder the server started successfully.
You can use:
input[type=text]
{
/*Styles*/
}
Define your common style attributes inside this. and for extra style you can add a class then.
Your problem is simple:
names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
This code first declares a global variable called names
. Then, you start a for loop. The for loop declares a local variable that just happens to be called names
too; the fact that a variable had previously been defined with names
is entirely irrelevant. Any use of names
inside the for loop will refer to the local one, not the global one.
The for loop says that the inner part of the loop will be called with names = 1
, then names = 2
, and finally names = 3
. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.
What you actually wanted was something like this:
names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
print (names[nameCount])
end
The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).
Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.
However, this has a flaw. What happens if you remove one of the elements from the list?
names = {'John', 'Joe'}
for nameCount = 1, 3 do
print (names[nameCount])
end
Now, we get John Joe nil
, because attempting to access values from a table that don't exist results in nil
. To prevent this, we need to count from 1 to the length of the table:
names = {'John', 'Joe'}
for nameCount = 1, #names do
print (names[nameCount])
end
The #
is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names
gets, this will always work.
However, there is a more convenient way to iterate through an array of items:
names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
print (name)
end
ipairs
is a Lua standard function that iterates over a list. This style of for
loop, the iterator for loop, uses this kind of iterator function. The i
value is the index of the entry in the array. The name
value is the value at that index. So it basically does a lot of grunt work for you.
Steps
Search IIS In Visual Studio 2015
Chose (Use the 64 bit of version of IIS Express for web site and project )
SELECT DATABASEPROPERTYEX('DBName', 'Collation') SQLCollation;
Where DBName is your database name.
Yes, T-SQL can feel extremely primitive at times, and it is things like these that often times push me to doing a lot of my logic in my language of choice (such as C#).
However, when you absolutely need to do some of these things in SQL for performance reasons, then your best bet is to create functions to house these "algorithms."
Take a look at this article. He offers up quite a few handy SQL functions along these lines that I think will help you.
http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx
About the .dex File :
One of the most remarkable features of the Dalvik Virtual Machine
(the workhorse under the Android system) is that it does not use Java bytecode. Instead, a homegrown format called DEX was introduced and not even the bytecode instructions are the same as Java bytecode instructions.
Compiled Android application code file.
Android programs are compiled into .dex
(Dalvik Executable) files, which are in turn zipped into a single .apk
file on the device. .dex
files can be created by automatically translating compiled applications written in the Java programming language.
Dex file format:
1. File Header
2. String Table
3. Class List
4. Field Table
5. Method Table
6. Class Definition Table
7. Field List
8. Method List
9. Code Header
10. Local Variable List
Android has documentation on the Dalvik Executable Format
(.dex files). You can find out more over at the official docs: Dex File Format
.dex
files are similar to java class files, but they were run under the Dalkvik Virtual Machine (DVM) on older Android versions, and compiled at install time on the device to native code with ART on newer Android versions.
You can decompile
.dex using the dexdump
tool which is provided in android-sdk.
There are also some Reverse Engineering Techniques to make a jar file
or java class file
from a .dex
file.
This works fine
public class DateDemo {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm");
String date = "16-08-2018 12:10";
LocalDate localDate = LocalDate.parse(date, formatter);
System.out.println("VALUE="+localDate);
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
LocalDateTime parse = LocalDateTime.parse(date, formatter1);
System.out.println("VALUE1="+parse);
}
}
output:
VALUE=2018-08-16
VALUE1=2018-08-16T12:10
Try LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0). Best of all it's free!
Steps with version 4.35.1:
click 'Add Connection'
Click Next with 'Build data context automatically' and 'Default(LINQ to SQL)' selected.
Under 'Provider' choose 'SQL CE 4.0'.
Under 'Database' with 'Attach database file' selected, choose 'Browse' to select your .sdf file.
Click 'OK'.
Voila! It should show the tables in .sdf and be able to query it via right clicking the table or writing LINQ code in your favorite .NET language or even SQL. How cool is that?
alternatively you can retrieve DOM properties
with .prop
here is sample code for select box
if( ctrl.prop('type') == 'select-one' ) { // for single select }
if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }
for textbox
if( ctrl.prop('type') == 'text' ) { // for text box }
I've used Spring.NET in the past and had great success with it. I never noticed any substantial overhead with it, though the project we used it on was fairly heavy on its own. It only took a little time reading through the documentation to get it set up.
You need to go to the /.idea/compiler.xml
and change target
to required jdk
level.
I had the same issue with Python3.
My code was writing into io.BytesIO()
.
Replacing with io.StringIO()
solved.
"^((0091)|(\+91)|0?)[789]{1}\d{9}$";
Is also a valid expression. You can precede it with either 0091,+91
or 0
and is optional.
For more details with code sample, refer to my blog.
C:
cd {press tab}
If you want to know how to read a file, within a directory, and do something with it, here you go. This also shows you how to run a command through the power shell
. This is in TypeScript
! I had trouble with this, so I hope this helps someone one day. Feel free to down vote me if you think its THAT unhelpful. What this did for me was webpack
all of my .ts
files in each of my directories within a certain folder to get ready for deployment. Hope you can put it to use!
import * as fs from 'fs';
let path = require('path');
let pathDir = '/path/to/myFolder';
const execSync = require('child_process').execSync;
let readInsideSrc = (error: any, files: any, fromPath: any) => {
if (error) {
console.error('Could not list the directory.', error);
process.exit(1);
}
files.forEach((file: any, index: any) => {
if (file.endsWith('.ts')) {
//set the path and read the webpack.config.js file as text, replace path
let config = fs.readFileSync('myFile.js', 'utf8');
let fileName = file.replace('.ts', '');
let replacedConfig = config.replace(/__placeholder/g, fileName);
//write the changes to the file
fs.writeFileSync('myFile.js', replacedConfig);
//run the commands wanted
const output = execSync('npm run scriptName', { encoding: 'utf-8' });
console.log('OUTPUT:\n', output);
//rewrite the original file back
fs.writeFileSync('myFile.js', config);
}
});
};
// loop through all files in 'path'
let passToTest = (error: any, files: any) => {
if (error) {
console.error('Could not list the directory.', error);
process.exit(1);
}
files.forEach(function (file: any, index: any) {
let fromPath = path.join(pathDir, file);
fs.stat(fromPath, function (error2: any, stat: any) {
if (error2) {
console.error('Error stating file.', error2);
return;
}
if (stat.isDirectory()) {
fs.readdir(fromPath, (error3: any, files1: any) => {
readInsideSrc(error3, files1, fromPath);
});
} else if (stat.isFile()) {
//do nothing yet
}
});
});
};
//run the bootstrap
fs.readdir(pathDir, passToTest);
This error also appears if the partition on which tmpdir
resides fills up (due to an alter table or other
If you would like to use a more functional approach to iterating over a string (perhaps to transform it somehow), you can split the string into characters, apply a function to each one, then join the resulting list of characters back into a string.
A string is inherently a list of characters, hence 'map' will iterate over the string - as second argument - applying the function - the first argument - to each one.
For example, here I use a simple lambda approach since all I want to do is a trivial modification to the character: here, to increment each character value:
>>> ''.join(map(lambda x: chr(ord(x)+1), "HAL"))
'IBM'
or more generally:
>>> ''.join(map(my_function, my_string))
where my_function takes a char value and returns a char value.
With lodash, you can create new object like this _.set:
obj = _.set({}, key, val);
Or you can set to existing object like this:
var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }
You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:
_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }
If you're using a Unix like OS (Linux, OSX, etc) then you can use a combination of find
and egrep
to search for require statements containing your package name:
find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'name-of-package' {} \;
If you search for the entire require('name-of-package')
statement, remember to use the correct type of quotation marks:
find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'require("name-of-package")' {} \;
or
find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni "require('name-of-package')" {} \;
The downside is that it's not fully automatic, i.e. it doesn't extract package names from package.json
and check them. You need to do this for each package yourself. Since package.json
is just JSON this could be remedied by writing a small script that uses child_process.exec
to run this command for each dependency. And make it a module. And add it to the NPM repo...
I needed to figure out the system host IP address for the emulator "Nox App Player". Here is how I figured out it was 172.17.100.2
.
ip link show
command to show all network interfaces. Of particular interest was the eth1 interfaceifconfig eth1
command, shows net as 172.17.100.15/255.255.255.0
172.17.100.1
, got a hit on `172.17.100.2'. Not sure if a firewall would interfere but it didn't in my caseMaybe this can help someone else figure it out for other emulators.
You can try the Class Based View called RedirectView
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'macmonster.views.home'),
#url(r'^macmon_home$', 'macmonster.views.home'),
url(r'^macmon_output/$', 'macmonster.views.output'),
url(r'^macmon_about/$', 'macmonster.views.about'),
url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)
Notice how as url
in the <url_to_home_view>
you need to actually specify the url.
permanent=False
will return HTTP 302, while permanent=True
will return HTTP 301.
Alternatively you can use django.shortcuts.redirect
Update for Django 2+ versions
With Django 2+, url()
is deprecated and replaced by re_path()
. Usage is exactly the same as url()
with regular expressions. For replacements without the need of regular expression, use path()
.
from django.urls import re_path
re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
Here is a working example in both Javascript and jQuery:
http://jsfiddle.net/GuLYN/312/
//In jQuery
$("#calculate").click(function() {
var num = parseFloat($("#textbox").val());
var new_num = $("#textbox").val(num.toFixed(2));
});
// In javascript
document.getElementById('calculate').onclick = function() {
var num = parseFloat(document.getElementById('textbox').value);
var new_num = num.toFixed(2);
document.getElementById('textbox').value = new_num;
};
?
Here it is a solution using map function:
>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]
And a solution using list comprehensions:
>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]
Use CryptoJS
Here's the code: https://github.com/odedhb/AES-encrypt
And here's an online working example: https://odedhb.github.io/AES-encrypt/
Check to see if you have previously disabled caching in Chrome when the developer console is open - the setting is under the console, settings icon > General tab: Disable cache (while DevTools is open)
To expand on joemailer's answer, if you want to have the pattern-matching ability to match any subset of remote machines (just as the ansible
command does), but still want to make it very difficult to accidentally run the playbook on all machines, this is what I've come up with:
Same playbook as the in other answer:
# file: user.yml (playbook)
---
- hosts: '{{ target }}'
user: ...
Let's have the following hosts:
imac-10.local
imac-11.local
imac-22.local
Now, to run the command on all devices, you have to explicty set the target variable to "all"
ansible-playbook user.yml --extra-vars "target=all"
And to limit it down to a specific pattern, you can set target=pattern_here
or, alternatively, you can leave target=all
and append the --limit
argument, eg:
--limit imac-1*
ie.
ansible-playbook user.yml --extra-vars "target=all" --limit imac-1* --list-hosts
which results in:
playbook: user.yml
play #1 (office): host count=2
imac-10.local
imac-11.local
Kotlin:
var ver: String = packageManager.getPackageInfo(packageName, 0).versionName
It looks like you are interesting in performing an operation everything for a given year, if this is indeed the case, I would recommend to use the YEAR() function like this:
SELECT * FROM `table` WHERE YEAR(date_column) = '2012';
The same goes for DAY() and MONTH(). They are also available for MySQL/MariaDB variants and was introduced in SQL Server 2008 (so not for specific 2000).
After going over some of the answers here an in another thread, here's what I ended up with:
I created a function named showAlert()
that would dynamically add an alert, with an optional type
and closeDealy
. So that you can, for example, add an alert of type danger
(i.e., Bootstrap's alert-danger) that will close automatically after 5 seconds like so:
showAlert("Warning message", "danger", 5000);
To achieve that, add the following Javascript function:
function showAlert(message, type, closeDelay) {
if ($("#alerts-container").length == 0) {
// alerts-container does not exist, add it
$("body")
.append( $('<div id="alerts-container" style="position: fixed;
width: 50%; left: 25%; top: 10%;">') );
}
// default to alert-info; other options include success, warning, danger
type = type || "info";
// create the alert div
var alert = $('<div class="alert alert-' + type + ' fade in">')
.append(
$('<button type="button" class="close" data-dismiss="alert">')
.append("×")
)
.append(message);
// add the alert div to top of alerts-container, use append() to add to bottom
$("#alerts-container").prepend(alert);
// if closeDelay was passed - set a timeout to close the alert
if (closeDelay)
window.setTimeout(function() { alert.alert("close") }, closeDelay);
}
The key idea is you form a set of the rows you want to remove, and keep the complement of that set.
In R, the complement of a set is given by the '-' operator.
So, assuming the data.frame
is called myData
:
myData[-c(2, 4, 6), ] # notice the -
Of course, don't forget to "reassign" myData
if you wanted to drop those rows entirely---otherwise, R just prints the results.
myData <- myData[-c(2, 4, 6), ]
while (listBox1.Items.Count > 0){
listBox1.Items.Remove(0);
}
How about using sort
?
dir /b /s | sort
Here's an example I tested with:
dir /s /b /o:gn
d:\root0
d:\root0\root1
d:\root0\root1\folderA
d:\root0\root1\folderB
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt
dir /s /b | sort
d:\root0
d:\root0\root1
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt
To just get directories, use the /A:D
parameter:
dir /a:d /s /b | sort
Use tr:first-child
to take the first tr
:
.category_table tr:first-child td {
vertical-align: top;
}
If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level td
s in the first top-level tr
get the styles:
.category_table > tbody > tr:first-child > td {
vertical-align: top;
}
Another option, this DOESN'T support comments, very useful with AmaterasERD DDL export for Apache Derby:
public void executeSqlScript(Connection conn, File inputFile) {
// Delimiter
String delimiter = ";";
// Create scanner
Scanner scanner;
try {
scanner = new Scanner(inputFile).useDelimiter(delimiter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
// Loop through the SQL file statements
Statement currentStatement = null;
while(scanner.hasNext()) {
// Get statement
String rawStatement = scanner.next() + delimiter;
try {
// Execute statement
currentStatement = conn.createStatement();
currentStatement.execute(rawStatement);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
if (currentStatement != null) {
try {
currentStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
currentStatement = null;
}
}
scanner.close();
}
Just download and install openSSH for windows. It is open source, and it makes your cmd ssh ready. A quick google search will give you a tutorial on how to install it, should you need it.
After it is installed you can just go ahead and generate your public key if you want to put in on a server. You generate it by running:
ssh-keygen -t rsa
After that you can just can just press enter, it will automatically assign a name for the key (example: id_rsa.pub)
It looks like a container with the name qgis-desktop-2-4
already exists in the system. You can check the output of the below command to confirm if it indeed exists:
$ docker ps -a
The last column in the above command's output is for names.
If the container exists, remove it using:
$ docker rm qgis-desktop-2-4
Or forcefully using,
$ docker rm -f qgis-desktop-2-4
And then try creating a new container.
Members with a constructor will have their default constructor called for initialisation.
You cannot depend on the contents of the other types.
My understanding is driver.close();
will close the current browser,
and driver.quit();
will terminate all the browser that.
I prefer using a separate file for ie rules, as described earlier.
<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->
And inside it you can set up rules for different versions of ie using this:
.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
There are a couple of ways.
>>> x = np.random.random((3, 2)) - 0.5
>>> x
array([[-0.00590765, 0.18932873],
[-0.32396051, 0.25586596],
[ 0.22358098, 0.02217555]])
>>> np.maximum(x, 0)
array([[ 0. , 0.18932873],
[ 0. , 0.25586596],
[ 0.22358098, 0.02217555]])
>>> x * (x > 0)
array([[-0. , 0.18932873],
[-0. , 0.25586596],
[ 0.22358098, 0.02217555]])
>>> (abs(x) + x) / 2
array([[ 0. , 0.18932873],
[ 0. , 0.25586596],
[ 0.22358098, 0.02217555]])
If timing the results with the following code:
import numpy as np
x = np.random.random((5000, 5000)) - 0.5
print("max method:")
%timeit -n10 np.maximum(x, 0)
print("multiplication method:")
%timeit -n10 x * (x > 0)
print("abs method:")
%timeit -n10 (abs(x) + x) / 2
We get:
max method:
10 loops, best of 3: 239 ms per loop
multiplication method:
10 loops, best of 3: 145 ms per loop
abs method:
10 loops, best of 3: 288 ms per loop
So the multiplication seems to be the fastest.
URL url = new URL("https://www.google.com");
//if you are using
URLConnection conn =url.openConnection();
//change it to
HttpURLConnection conn =(HttpURLConnection )url.openConnection();
You can generate Application Encryption Key using this command:
php artisan key:generate
Then, create a cache file for faster configuration loading using this command:
php artisan config:cache
Or, serve the application on the PHP development server using this command:
php artisan serve
That's it!
You can add the files which give error to .eslintignore file in your project.Like for all the .vue files just add /*.vue
I encountered this error, and the fix appears to be turning off SNI, which Python 2.7 does not support:
Got a solution that runs. Don't know if it is optimal though. What I do is to split the string according to http://blogs.oracle.com/aramamoo/2010/05/how_to_split_comma_separated_string_and_pass_to_in_clause_of_select_statement.html
Using:
select regexp_substr(' 1, 2 , 3 ','[^,]+', 1, level) from dual
connect by regexp_substr('1 , 2 , 3 ', '[^,]+', 1, level) is not null;
So my final code looks like this ($bp_gr1'
are strings like 1,2,3
):
UPDATE TAB1
SET BUDGPOST_GR1 =
CASE
WHEN ( BUDGPOST IN (SELECT REGEXP_SUBSTR ( '$BP_GR1',
'[^,]+',
1,
LEVEL )
FROM DUAL
CONNECT BY REGEXP_SUBSTR ( '$BP_GR1',
'[^,]+',
1,
LEVEL )
IS NOT NULL) )
THEN
'BP_GR1'
WHEN ( BUDGPOST IN (SELECT REGEXP_SUBSTR ( ' $BP_GR2',
'[^,]+',
1,
LEVEL )
FROM DUAL
CONNECT BY REGEXP_SUBSTR ( '$BP_GR2',
'[^,]+',
1,
LEVEL )
IS NOT NULL) )
THEN
'BP_GR2'
WHEN ( BUDGPOST IN (SELECT REGEXP_SUBSTR ( ' $BP_GR3',
'[^,]+',
1,
LEVEL )
FROM DUAL
CONNECT BY REGEXP_SUBSTR ( '$BP_GR3',
'[^,]+',
1,
LEVEL )
IS NOT NULL) )
THEN
'BP_GR3'
WHEN ( BUDGPOST IN (SELECT REGEXP_SUBSTR ( '$BP_GR4',
'[^,]+',
1,
LEVEL )
FROM DUAL
CONNECT BY REGEXP_SUBSTR ( '$BP_GR4',
'[^,]+',
1,
LEVEL )
IS NOT NULL) )
THEN
'BP_GR4'
ELSE
'SAKNAR BUDGETGRUPP'
END;
Is there a way to make it run faster?
I've extended vokimon's answer a bit, making it a bit more convenient for changing other properties as well.
function customIcon (opts) {
return Object.assign({
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
fillColor: '#34495e',
fillOpacity: 1,
strokeColor: '#000',
strokeWeight: 2,
scale: 1,
}, opts);
}
Usage:
marker.setIcon(customIcon({
fillColor: '#fff',
strokeColor: '#000'
}));
Or when defining a new marker:
const marker = new google.maps.Marker({
position: {
lat: ...,
lng: ...
},
icon: customIcon({
fillColor: '#2ecc71'
}),
map: map
});
For traditional extending you can simply write superclass as constructor function, and then apply this constructor for your inherited class.
function AbstractClass() {
this.superclass_method = function(message) {
// do something
};
}
function Child() {
AbstractClass.apply(this);
// Now Child will have superclass_method()
}
Example on angularjs:
http://plnkr.co/edit/eFixlsgF3nJ1LeWUJKsd?p=preview
app.service('noisyThing',
['notify',function(notify){
this._constructor = function() {
this.scream = function(message) {
message = message + " by " + this.get_mouth();
notify(message);
console.log(message);
};
this.get_mouth = function(){
return 'abstract mouth';
}
}
}])
.service('cat',
['noisyThing', function(noisyThing){
noisyThing._constructor.apply(this)
this.meow = function() {
this.scream('meooooow');
}
this.get_mouth = function(){
return 'fluffy mouth';
}
}])
.service('bird',
['noisyThing', function(noisyThing){
noisyThing._constructor.apply(this)
this.twit = function() {
this.scream('fuuuuuuck');
}
}])
Complete guide : https://developer.android.com/studio/build/application-id.html
As per Android official Blogs : https://android-developers.googleblog.com/2011/06/things-that-cannot-change.html
We can say that:
If the manifest package name has changed, the new application will be installed alongside the old application, so they both co-exist on the user’s device at the same time.
If the signing certificate changes, trying to install the new application on to the device will fail until the old version is uninstalled.
As per Google App Update check list : https://support.google.com/googleplay/android-developer/answer/113476?hl=en
Update your apps
Prepare your APK
When you're ready to make changes to your APK, make sure to update your app’s version code as well so that existing users will receive your update.
Use the following checklist to make sure your new APK is ready to update your existing users:
To verify that your APK is using the same certification as the previous version, you can run the following command on both APKs and compare the results:
$ jarsigner -verify -verbose -certs my_application.apk
If the results are identical, you’re using the same key and are ready to continue. If the results are different, you will need to re-sign the APK with the correct key.
Learn more about signing your applications
Upload your APK Once your APK is ready, you can create a new release.
You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
DEPID
,DEPNAME
FROM
DEPRMNT
WHERE
dp.DEPADDRESS = 'TOKYO'
) ss
ON (
ss.DEPID = cs.CUSID
AND ss.DEPNAME = cs.CUSTNAME
)
WHERE
cs.CUSID != ''
It's simple:
array = []
will set array
to be an empty list. (They're called lists in Python, by the way, not arrays)
If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.
Compare Names containing apostrophe in DB through Java code
String sql="select lastname from employee where FirstName like '%"+firstName.trim().toLowerCase().replaceAll("'", "''")+"%'"
statement = conn.createStatement();
rs=statement.executeQuery(Sql);
iterate the results.
TLS 1.1 and TLS 1.2 are supported since OpenSSL 1.0.1
Forcing TLS 1.1 and 1.2 are only supported since curl 7.34.0
You should consider an upgrade.
Just my take on this, there are two methods that are easy to understand of all the given options. So my main criteria is have very readable code, not exceptionally fast code. To keep code understandable, i prefer to given possibilities:
The fact that "var <= var2.keys()" executes faster in my testing below, i prefer this one.
import timeit
timeit.timeit('var <= var2.keys()', setup='var={"managed_ip", "hostname", "fqdn"}; var2= {"zone": "test-domain1.var23.com", "hostname": "bakje", "api_client_ip": "127.0.0.1", "request_data": "", "request_method": "GET", "request_url": "hvar2p://127.0.0.1:5000/test-domain1.var23.com/bakje", "utc_datetime": "04-Apr-2019 07:01:10", "fqdn": "bakje.test-domain1.var23.com"}; var={"managed_ip", "hostname", "fqdn"}')
0.1745898080000643
timeit.timeit('var.issubset(var2)', setup='var={"managed_ip", "hostname", "fqdn"}; var2= {"zone": "test-domain1.var23.com", "hostname": "bakje", "api_client_ip": "127.0.0.1", "request_data": "", "request_method": "GET", "request_url": "hvar2p://127.0.0.1:5000/test-domain1.var23.com/bakje", "utc_datetime": "04-Apr-2019 07:01:10", "fqdn": "bakje.test-domain1.var23.com"}; var={"managed_ip", "hostname", "fqdn"};')
0.2644960229999924
Because they didn't want to introduce a new keyword to the language. Each one steals an identifier and causes backwards compatibility problems, so it's usually a last resort.
class Thing {
public int value;
public Thing (int x) {
value = x;
}
equals (Thing x) {
if (x.value == value) return true;
return false;
}
}
You must write:
class Thing {
public int value;
public Thing (int x) {
value = x;
}
public boolean equals (Object o) {
Thing x = (Thing) o;
if (x.value == value) return true;
return false;
}
}
Now it works ;)
For those using an actual URL and not a variable:
$('myObject').css('background-image', 'url(../../example/url.html)');
The Expressions can help here:
private static Dictionary<Type, Delegate> lambdasMap = new Dictionary<Type, Delegate>();
private object GetTypedNull(Type type)
{
Delegate func;
if (!lambdasMap.TryGetValue(type, out func))
{
var body = Expression.Default(type);
var lambda = Expression.Lambda(body);
func = lambda.Compile();
lambdasMap[type] = func;
}
return func.DynamicInvoke();
}
I did not test this snippet, but i think it should produce "typed" nulls for reference types..
Here's how to determine a local user:
public bool IsLocalUser()
{
return windowsIdentity.AuthenticationType == "NTLM";
}
You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.
Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:
Why the NTLM Plug-in is Needed
NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.
Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.
By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.
How the Plug-in Works
The Verifier plug detects the following errors:
The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).
The target name in the call to InitializeSecurityContext is NULL.
The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.
The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).
The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.
NTLM Stops
5000 – Application Has Explicitly Selected NTLM Package
Severity – Error
The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.
How to Fix this Error
The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.
APIs(parameter) Used by Application Incorrect Value Correct Value ===================================== =============== ======================== AcquireCredentialsHandle (pszPackage) “NTLM” NEGOSSP_NAME “Negotiate”
My answer builds on that from Kevin Wong, here as a one-liner using CollectionUtils
from spring and a Java 8 lambda expression.
CollectionUtils.filter(list, p -> ((Person) p).getAge() > 16);
This is as concise and readable as any alternative I have seen (without using aspect-based libraries)
Spring CollectionUtils is available from spring version 4.0.2.RELEASE, and remember you need JDK 1.8 and language level 8+.
ArrayList<String> keyList = new ArrayList<String>();
mKeyRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String temp = childDataSnapshot.getKey();
keyList.add(temp);
i = keyList.size();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
This code is working fine to add all firebase key into arraylist, you can do it with firebase values, of other static values.
Take a look at this similar question. Tool to discover same class..
I think the most relevant obstacle is if you have a custom classloader ( loading from a db or ldap )
This answer works in SQL Server 2005, 2008, 2012.
At times the value has MANY single quotes. Rather than add a single quote next to each single quote as described above with 'John''s'
. And there are examples using the REPLACE
function to handle many single quotes in a value.
Try the following. This is an update statement but you can use it in an INSERT
statement as well.
SET QUOTED_IDENTIFIER OFF
DECLARE @s VARCHAR(1000)
SET @s = "SiteId:'1'; Rvc:'6'; Chk:'1832'; TrEmp:'150'; WsId:'81'; TtlDue:'-9.40'; TtlDsc:'0'; TtlSvc:'0'; TtlTax:'-0.88'; TtlPay:'0'; TipAmt:'0.00'; SvcSeq:'09'; ReTx:'N'; TraceId:'160110124347N091832';"
UPDATE TransactionPaymentPrompt
set PromptData = @s
from TransactionPaymentPrompt tpp with (nolock)
where tpp.TransactionID = '106627343'
Case matters
I manually added a submodule :k3b-geohelper
to the
settings.gradle
file
include ':app', ':k3b-geohelper'
and everthing works fine on my mswindows build system
When i pushed the update to github the fdroid build system failed with
Cannot evaluate module k3b-geohelper : Configuration with name 'default' not found
The final solution was that the submodule folder was named k3b-geoHelper
not k3b-geohelper
.
Under MSWindows case doesn-t matter but on linux system it does
For anyone trying to
...in 2019, it's worth noting some of the code referenced here no longer exists (officially). Google discontinued support for the "MarkerWithLabel" project a long time ago. It was originally hosted on Google code here, now it's unofficially hosted on Github here.
But there is another project Google maintained until 2016, called "MapLabel"s. That approach is different (and arguably better). You create a separate map label object with the same origin as the marker instead of adding a mapLabel option to the marker itself. You can make a marker with label with multiple characters using js-marker-label.
Before the command clickAndWait
add the following code so the script will wait until the specific link to be visible:
<tr>
<td>waitForVisible</td>
<td>link=do something</td>
<td></td>
</tr>
The practice of using the wait commands instead of pause is most of the times more efficient and more stable.
Below Code Returns the path until your project root
import sys
print(sys.path[1])
I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :
String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String
this method :
str.getClass().getSimpleName();
value:String
now example:
Object o = 1;
o.getClass().getSimpleName();
value:Integer
Create a "module" object and declare variables in there. Unlike class-objects that have to be instantiated each time, the module objects are always available. Therefore, a public variable, function, or property in a "module" will be available to all the other objects in the VBA project, macro, Excel formula, or even within a MS Access JET-SQL query def.
Visual Studio 2008: (3,30 GB) http://download.microsoft.com/download/8/1/d/81d3f35e-fa03-485b-953b-ff952e402520/VS2008ProEdition90dayTrialENUX1435622.iso
To upgrade from trial version to Pro version, check: http://msdn.microsoft.com/en-us/library/ms246600%28VS.80%29.aspx
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
Not sure if its a true language, but I hate Makefiles.
Makefiles have meaningful differences between space and TAB, so even if two lines appear identical, they do not run the same.
Make also relies on a complex set of implicit rules for many languages, which are difficult to learn, but then are frequently overridden by the make file.
A Makefile system is typically spread over many, many files, across many directories. With virtually no scoping or abstraction, a change to a make file several directories away can prevent my source from building. Yet the error message is invariably a compliation error, not a meaningful error about make, or the makefiles.
Any environment I've worked in that uses makefiles successfully has a full-time Make expert. And all this to shave a few minutes off compilation??
Simple command to check keras version:
(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)
>>> import keras
Using TensorFlow backend.
>>> keras.__version__
'2.2.4'
Instant.now().getEpochSecond() // The number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
As others stated, a 32-bit integer cannot hold a number big enough for the number of seconds from the epoch (beginning of 1970 in UTC) and now. You need 64-bit integer (a long
primitive or Long
object).
The other answers are using old legacy date-time classes. They have been supplanted by the java.time classes.
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant now = instant.now() ;
You can interrogate for the number of milliseconds since the epoch. Beware this means a loss of data, truncating nanoseconds to milliseconds.
long millisecondsSinceEpoch = now.toEpochMilli() ;
If you want a count of nanoseconds since epoch, you will need to do a bit of math as the class oddly lacks a toEpochNano
method. Note the L
appended to the billion to provoke the calculation as 64-bit long integers.
long nanosecondsSinceEpoch = ( instant.getEpochSecond() * 1_000_000_000L ) + instant.getNano() ;
But the end of the Question asks for a 10-digit number. I suspect that means a count of whole seconds since the epoch of 1970-01-01T00:00:00. This is commonly referred to as Unix Time or Posix Time.
We can interrogate the Instant
for this number. Again, this means a loss of data with the truncation of any fraction-of-second this object may hold.
long secondsSinceEpoch = now.getEpochSecond() ; // The number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I had the same problem. The solution was to update IntelliJ to the newest version.
Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";
// use the built in Json deserializer to convert the string to a list of Person objects
var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);
foreach (var person in people)
{
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
WINDOWS
(Alt+F12 or View->Tool Windows->Terminal).
Then type "move file_path/google-services.json app/"
without double quotes.
eg
move C:\Users\siva\Downloads\google-services.json app/
LINUX
scp file_path/google-services.json app/
eg:
scp '/home/developer/Desktop/google-services.json' 'app/'
SQL Server 2012:
Select TRY_CONVERT(TIME, myDateTimeColumn) from myTable;
Personally, I prefer TRY_CONVERT() to CONVERT(). The main difference: If cast fails, TRY_CONVERT() returns NULL while CONVERT() raises an error.
Haskell's standard list data type forall t. [t]
in implementation closely resembles a canonical C linked list, and shares its essentially properties. Linked lists are very different from arrays. Most notably, access by index is a O(n) linear-, instead of a O(1) constant-time operation.
If you require frequent random access, consider the Data.Array
standard.
!!
is an unsafe partially defined function, provoking a crash for out-of-range indices. Be aware that the standard library contains some such partial functions (head
, last
, etc.). For safety, use an option type Maybe
, or the Safe
module.
Example of a reasonably efficient, robust total (for indices = 0) indexing function:
data Maybe a = Nothing | Just a
lookup :: Int -> [a] -> Maybe a
lookup _ [] = Nothing
lookup 0 (x : _) = Just x
lookup i (_ : xs) = lookup (i - 1) xs
Working with linked lists, often ordinals are convenient:
nth :: Int -> [a] -> Maybe a
nth _ [] = Nothing
nth 1 (x : _) = Just x
nth n (_ : xs) = nth (n - 1) xs
== is what you want, "is" just happens to work on your examples.
from msvcrt import getch
pos = [0, 0]
def fright():
global pos
pos[0] += 1
def fleft():
global pos
pos[0] -= 1
def fup():
global pos
pos[1] += 1
def fdown():
global pos
pos[1] -= 1
while True:
print'Distance from zero: ', pos
key = ord(getch())
if key == 27: #ESC
break
elif key == 13: #Enter
print('selected')
elif key == 32: #Space
print('jump')
elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
key = ord(getch())
if key == 80: #Down arrow
print('down')
fdown
elif key == 72: #Up arrow
print('up')
fup()
elif key == 75: #Left arrow
print('left')
fleft()
elif key == 77: #Right arrow
print('right')
fright()
I know of two ways to do it.
Method 1
The first method (which I prefer) is to use msbuild:
msbuild project.sln /Flags...
Method 2
You can also run:
vcexpress project.sln /build /Flags...
The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.
Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).
So, the end result might be:
os.system("msbuild project.sln /p:Configuration=Debug")
You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).
If you don't mind the dictionary values being tuples, you can use itertuples:
>>> {x[0]: x[1:] for x in df.itertuples(index=False)}
{'p': (1, 3, 2), 'q': (4, 3, 2), 'r': (4, 0, 9)}
Because you set visibility either true or false.
try that
setVisible(0)
to visible true .
and setVisible(4)
to visible false.
if (count($arr) >= 2)
{
// array has at least 2 elements
}
sizeof()
is an alias for count()
. Both work with non-arrays too, but they will only return values greater than 1 if the argument is either an array or a Countable
object, so you're pretty safe with this.
Not pretty, but here is a way to implement an exit()
command in R which works for me.
exit <- function() {
.Internal(.invokeRestart(list(NULL, NULL), NULL))
}
print("this is the last message")
exit()
print("you should not see this")
Only lightly tested, but when I run this, I see this is the last message
and then the script aborts without any error message.
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
execute this query before restoring database:
alter database [YourDBName]
set offline with rollback immediate
and this one after restoring:
alter database [YourDBName]
set online
Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:
<input type="text" class="disable">
.disable{
pointer-events:none;
background:grey;
}
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
I you are using Visual Studio 2012, download and install Update 2 that Microsoft released recently (as of 4/2013).
There are some bug fixes in that update related to the issue.
If you do not want to the text twice as column heading as well as value, use the following stmt!
SELECT 'some text' as '';Example:
mysql>SELECT 'some text' as ''; +-----------+ | | +-----------+ | some text | +-----------+ 1 row in set (0.00 sec)
Here is another example which is working
public class EnregistrementVideoStackActivity extends Activity implements SurfaceHolder.Callback {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
private Button startRecording = null;
File video;
private Camera mCamera;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_surface);
Log.i(null , "Video starting");
startRecording = (Button)findViewById(R.id.buttonstart);
mCamera = Camera.open();
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 1, 0, "StopRecording");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case 0:
try {
startRecording();
} catch (Exception e) {
String message = e.getMessage();
Log.i(null, "Problem Start"+message);
mrec.release();
}
break;
case 1: //GoToAllNotes
mrec.stop();
mrec.release();
mrec = null;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
protected void startRecording() throws IOException
{
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile("/sdcard/zzzz.3gp");
mrec.prepare();
mrec.start();
}
protected void stopRecording() {
mrec.stop();
mrec.release();
mCamera.release();
}
private void releaseMediaRecorder(){
if (mrec != null) {
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
mrec = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null){
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
}
camera_surface.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<SurfaceView
android:id="@+id/surface_camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/buttonstart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/record_start" />
</RelativeLayout>
And of course include these permission in manifest:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
http://sandbox.phpcode.eu/g/corrected-b5fe953c76d4b82f7e63f1cef1bc506e.php
<span id="black_only">Show only black</span><br>
<span id="white_only">Show only white</span><br>
<span id="all">Show all of them</span>
<style>
.black{background-color:black;}
#white{background-color:white;}
</style>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
<tr class="black">
<th>Header Text</th>
<th>Header Text</th>
<th>Header Text</th>
<th>Header Text</th>
<th>Header Text</th>
<th>Header Text</th>
</tr>
</thead>
<tbody>
<tr id="white">
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
</tr>
<tr class="black" style="background-color:black;">
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
<td>Some Text</td>
</tr>
</tbody>
<script>
$(function(){
$("#black_only").click(function(){
$("#white").hide();
$(".black").show();
});
$("#white_only").click(function(){
$(".black").hide();
$("#white").show();
});
$("#all").click(function(){
$("#white").show();
$(".black").show();
});
});
</script>
In the first place, you should note that PDF and HTML and different formats that hardly have anything in common. If TCPDF allows you to provide input data using HTML and CSS it's because it implements a simple parser for these two languages and tries to figure out how to translate that into PDF. So it's logical that TCPDF only supports a little subset of the HTML and CSS specification and, even in supported stuff, it's probably not as perfect as in first class web browsers.
Said that, the question is: what's supported and what's not? The documentation basically skips the issue and let's you enjoy the trial and error method.
Having a look at the source code, we can see there's a protected method called TCPDF::getHtmlDomArray()
that, among other things, parses CSS declarations. I can see stuff like font-family
, list-style-type
or text-indent
but there's no margin
or padding
as far as I can see and, definitively, there's no float
at all.
To sum up: with TCPDF, you can use CSS for some basic formatting. If you need to convert from HTML to PDF, it's the wrong tool. (If that's the case, may I suggest wkhtmltopdf?)
For me following steps worked:
Xcode
.Terminal
.xattr -rc /Users/manabkumarmal/Desktop/Projects/MyProjectHome
You can also use you own computer built-in functions:
tree /a /f >tree.txt
any_name_you_want.BAT
tree.txt
that contains you directory TREE.These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)
a) Part on the developers' website:
Sign in into: https://developer.apple.com/
Member Center
Certificates, Identifiers & Profiles
Certificates>All
Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.
b) XCode part:
After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.
Also the $wshell = New-Object -ComObject wscript.shell;
helped a script that was running in the background, it worked fine with just but adding $wshell
. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")
import time
from datetime import datetime
now = datetime.now()
# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6
(Sorry, it wouldn't let me comment on existing answer)
MoreLinq has a DistinctBy method that you can use:
It will allow you to do:
var results = table1.DistictBy(row => row.Text);
The implementation of the method (short of argument validation) is as follows:
private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
Arrays are better in performance. ArrayList provides additional functionality such as "remove" at the cost of performance.
Warning about using TODAY (or any calcs in a column).
If you set up a filter and have JUST [Today] it it you should be fine.
But the moment you do something like [Today]-1 ... the view will no longer show up when trying to pick it for alerts.
Another microsoft wonder.
I found this solution to be quite handy. It uses the -or
option in find
:
find . -name \*.tex -or -name "*.png" -or -name "*.pdf"
It will find the files with extension tex
, png
, and pdf
.
If you have Login in a seperate folder within your project make sure that where you are using it you do:
using FootballLeagueSystem.[Whatever folder you are using]
headers were not working for me on my shared hosting, reason was i was using my hotmail email address in header. i created a email on my cpanel and i set that same email in the header yeah it worked like a charm!
$header = 'From: ShopFive <[email protected]>' . "\r\n";
I ran into some issues with backslash in my Domain\User string.
I added this to the other escapes from Anentropic's answer
.replace(/\\/g, '\')
Which I found here: How to escape backslash in JavaScript?
You can try this:
git rm -rf <directory_name>
It will force delete the directory.
function _arrayBufferToBase64(uarr) {
var strings = [], chunksize = 0xffff;
var len = uarr.length;
for (var i = 0; i * chunksize < len; i++){
strings.push(String.fromCharCode.apply(null, uarr.subarray(i * chunksize, (i + 1) * chunksize)));
}
return strings.join("");
}
This is better, if you use JSZip for unpack archive from string
--update 2
Please use @Frank's a one line solution:
new Date(SECONDS * 1000).toISOString().substr(11, 8)
It is by far the best solution.
I am working on a tutorial for REST web services at www.udemy.com (REST Java Web Services). The example in the tutorial said that in order to have SSL, we must have a folder called "trust_store" in my eclipse "client" project that should contain a "key store" file (we had a "client" project to call the service, and "service" project that contained the REST web service - 2 projects in the same eclipse workspace, one the client, the other the service). To keep things simple, they said to copy "keystore.jks" from the glassfish app server (glassfish\domains\domain1\config\keystore.jks) we are using and put it into this "trust_store" folder that they had me make in the client project. That seems to make sense: the self-signed certs in the server's key_store would correspond to the certs in the client trust_store. Now, doing this, I was getting the error that the original post mentions. I have googled this and read that the error is due to the "keystore.jks" file on the client not containing a trusted/signed certificate, that the certificate it finds is self-signed.
To keep things clear, let me say that as I understand it, the "keystore.jks" contains self-signed certs, and the "cacerts.jks" file contains CA certs (signed by the CA). The "keystore.jks" is the "keystore" and the "cacerts.jks" is the "trust store". As "Bruno", a commenter, says above, "keystore.jks" is local, and "cacerts.jks" is for remote clients.
So, I said to myself, hey, glassfish also has the "cacerts.jks" file, which is glassfish's trust_store file. cacerts.jsk is supposed to contain CA certificates. And apparently I need my trust_store folder to contain a key store file that has at least one CA certificate. So, I tried putting the "cacerts.jks" file in the "trust_store" folder I had made, on my client project, and changing the VM properties to point to "cacerts.jks" instead of "keystore.jks". That got rid of the error. I guess all it needed was a CA cert to work.
This may not be ideal for production, or even for development beyond just getting something to work. For instance you could probably use "keytool" command to add CA certs to the "keystore.jks" file in the client. But anyway hopefully this at least narrows down the possible scenarios that could be going on here to cause the error.
ALSO: my approach seemed to be useful for the client (server cert added to client trust_store), it looks like the comments above to resolve the original post are useful for the server (client cert added to server trust_store). Cheers.
Eclipse project setup:
Snippet from MyClientProject.java file:
static {
// Setup the trustStore location and password
System.setProperty("javax.net.ssl.trustStore","trust_store/cacerts.jks");
// comment out below line
System.setProperty("javax.net.ssl.trustStore","trust_store/keystore.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
//System.setProperty("javax.net.debug", "all");
// for localhost testing only
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
return hostname.equals("localhost");
}
});
}
As for second question - you can use Fiddler filters to set response X-Frame-Options
header manually to something like ALLOW-FROM *
. But, of course, this trick will work only for you - other users still won't be able to see iframe content(if they not do the same).
Make sure you don't add or uncomment the AllowNoPassword option after the $i++ line.
/* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
The following codes are my Powershell codes to determinate if some cpp or h or ml files are encodeding with ISO-8859-1(Latin-1) or UTF-8 without BOM, if neither then suppose it to be GB18030. I am a Chinese working in France and MSVC saves as Latin-1 on french computer and saves as GB on Chinese computer so this helps me avoid encoding problem when do source file exchanges between my system and my colleagues.
The way is simple, if all characters are between x00-x7E, ASCII, UTF-8 and Latin-1 are all the same, but if I read a non ASCII file by UTF-8, we will find the special character ? show up, so try to read with Latin-1. In Latin-1, between \x7F and \xAF is empty, while GB uses full between x00-xFF so if I got any between the two, it's not Latin-1
The code is written in PowerShell, but uses .net so it's easy to be translated into C# or F#
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
foreach($i in Get-ChildItem .\ -Recurse -include *.cpp,*.h, *.ml) {
$openUTF = New-Object System.IO.StreamReader -ArgumentList ($i, [Text.Encoding]::UTF8)
$contentUTF = $openUTF.ReadToEnd()
[regex]$regex = '?'
$c=$regex.Matches($contentUTF).count
$openUTF.Close()
if ($c -ne 0) {
$openLatin1 = New-Object System.IO.StreamReader -ArgumentList ($i, [Text.Encoding]::GetEncoding('ISO-8859-1'))
$contentLatin1 = $openLatin1.ReadToEnd()
$openLatin1.Close()
[regex]$regex = '[\x7F-\xAF]'
$c=$regex.Matches($contentLatin1).count
if ($c -eq 0) {
[System.IO.File]::WriteAllLines($i, $contentLatin1, $Utf8NoBomEncoding)
$i.FullName
}
else {
$openGB = New-Object System.IO.StreamReader -ArgumentList ($i, [Text.Encoding]::GetEncoding('GB18030'))
$contentGB = $openGB.ReadToEnd()
$openGB.Close()
[System.IO.File]::WriteAllLines($i, $contentGB, $Utf8NoBomEncoding)
$i.FullName
}
}
}
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
Try this: Set your image crop dimensions and use this line in your CSS:
object-fit: cover;
Assuming having a template DataFrame, which one would like to copy with zero values filled here...
If you have no NaNs in your data set, multiplying by zero can be significantly faster:
In [19]: columns = ["col{}".format(i) for i in xrange(3000)]
In [20]: indices = xrange(2000)
In [21]: orig_df = pd.DataFrame(42.0, index=indices, columns=columns)
In [22]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
100 loops, best of 3: 12.6 ms per loop
In [23]: %timeit d = orig_df * 0.0
100 loops, best of 3: 7.17 ms per loop
Improvement depends on DataFrame size, but never found it slower.
And just for the heck of it:
In [24]: %timeit d = orig_df * 0.0 + 1.0
100 loops, best of 3: 13.6 ms per loop
In [25]: %timeit d = pd.eval('orig_df * 0.0 + 1.0')
100 loops, best of 3: 8.36 ms per loop
But:
In [24]: %timeit d = orig_df.copy()
10 loops, best of 3: 24 ms per loop
EDIT!!!
Assuming you have a frame using float64, this will be the fastest by a huge margin! It is also able to generate any value by replacing 0.0 to the desired fill number.
In [23]: %timeit d = pd.eval('orig_df > 1.7976931348623157e+308 + 0.0')
100 loops, best of 3: 3.68 ms per loop
Depending on taste, one can externally define nan, and do a general solution, irrespective of the particular float type:
In [39]: nan = np.nan
In [40]: %timeit d = pd.eval('orig_df > nan + 0.0')
100 loops, best of 3: 4.39 ms per loop
Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver.
Instead, use the jtds jdbc driver. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM.
if it is a link then $(this).unbind("click");
would re-enable the link clicking and the default behavior would be restored.
I have created a demo JS fiddle to demonstrate how this works:
Here is the code of the JS fiddle:
HTML:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a href="http://jquery.com">Default click action is prevented, only on the third click it would be enabled</a>
<div id="log"></div>
Javascript:
<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
event.preventDefault();
$( "<div>" )
.append( "default " + event.type + " prevented "+counter )
.appendTo( "#log" );
if(counter == 2)
{
$( "<div>" )
.append( "now enable click" )
.appendTo( "#log" );
$(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
}
else
{
$( "<div>" )
.append( "still disabled" )
.appendTo( "#log" );
}
counter++;
});
});
</script>
The specificity of String
has mostly been addressed in other answers. To paraphrase: String
has a specific Index
which is not of type Int
because string elements do not have the same size in the general case. Hence, String
does not conform to RandomAccessCollection
and accessing a specific index implies the traversal of the collection, which is not an O(1) operation.
Many answers have proposed workarounds for using ranges, but they can lead to inefficient code as they use String methods (index(from:)
, index(:offsetBy:)
, ...) that are not O(1).
To access string elements like in an array you should use an Array
:
let array = Array("Hello, world!")
let letter = array[5]
This is a trade-off, the array creation is an O(n) operation but array accesses are then O(1). You can convert back to a String when you want with String(array)
.
If you want the output redirected to a file using Kernel#system
, you can do modify descriptors like this:
redirect stdout and stderr to a file(/tmp/log) in append mode:
system('ls -al', :out => ['/tmp/log', 'a'], :err => ['/tmp/log', 'a'])
For a long running command, this will store the output in real time. You can also, store the output using a IO.pipe and redirect it from Kernel#system.
grep
is made for this.
Use grep myword *
And check man grep
.
You have to add a manifest permission entry:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
(of course you should list all other permissions that your app uses).
Then, implement BroadcastReceiver class, it should be simple and fast executable. The best approach is to set an alarm in this receiver to wake up your service (if it's not necessary to keep it running ale the time as Prahast wrote).
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
}
}
Then, add a Receiver class to your manifest file:
<receiver android:enabled="true" android:name=".receivers.BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>