I had this error and solved by this solution.
--> Right click on the project
--> and select "Properties"
--> then set "Output Type" to "Class Library".
Another scenario where this shows up is if you are using the older "Web Site" project type in Visual Studio. For that project type, it is unable to reference .dlls that are outside of it's own directory structure (current folder and down). So in the answer above, let's say your directory structure looks like this:
Where ProjectX and ProjectY are parent/child directories, and ProjectX references A.dll which in turn references B.dll, and B.dll is outside the directory structure, such as in a Nuget package on the root (Packages), then A.dll will be included, but B.dll will not.
Try this small example:
Code:
try {
Path tmpDir = Files.createTempDirectory("tmpDir");
System.out.println(tmpDir.toString());
Files.delete(tmpDir);
} catch (IOException e) {
e.printStackTrace();
}
Imports:
java.io.IOException
java.nio.file.Files
java.nio.file.Path
Console output on Windows machine:
C:\Users\userName\AppData\Local\Temp\tmpDir2908538301081367877
Comment:
Files.createTempDirectory generates unique ID atomatically - 2908538301081367877.
Note:
Read the following for deleting directories recursively:
Delete directories recursively in Java
If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system()
with subprocess.Popen()
:
sts = os.system("mycmd" + " myarg")
...does the same thing as...
sts = Popen("mycmd" + " myarg", shell=True).wait()
The "improved" code looks more complicated, but it's better because once you know subprocess.Popen()
, you don't need anything else. subprocess.Popen()
replaces several other tools (os.system()
is just one of those) that were scattered throughout three other Python modules.
If it helps, think of subprocess.Popen()
as a very flexible os.system()
.
I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time
JAVASCRIPT
$(function () {
/* SET PARAMETERS */
var change_img_time = 5000;
var transition_speed = 100;
var simple_slideshow = $("#exampleSlider"),
listItems = simple_slideshow.children('li'),
listLen = listItems.length,
i = 0,
changeList = function () {
listItems.eq(i).fadeOut(transition_speed, function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(transition_speed);
});
};
listItems.not(':first').hide();
setInterval(changeList, change_img_time);
});
.
HTML
<ul id="exampleSlider">
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>
.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO
.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX
You can also use:
{{ word|striptags('<b>')|raw }}
so that only <b>
tag will be allowed.
In addition to the other answers, you can use this less-known method to grab elements of a certain parent like so,
$('child', 'parent');
In your case, that would be
if ($(event.target, 'div#hello')[0]) console.log(`${event.target.tagName} is an offspring of div#hello`);
Note the use of commas between the child and parent and their separate quotation marks. If they were surrounded by the same quotes
$('child, parent');
you'd have an object containing both objects, regardless of whether they exist in their document trees.
It's quite easy for a fix.
For me, we had more than one inputs in the form. We need to isolate the input / line causing error and simply add the name
attribute. That fixed the issue for me:
Before:
<form class="example-form">
<mat-form-field appearance="outline">
<mat-select placeholder="Select your option" [(ngModel)]="sample.stat"> <!--HERE -->
<mat-option *ngFor="let option of actions" [value]="option">{{option}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter number</mat-label>
<input id="myInput" type="text" placeholder="Enter number" aria-label="Number"
matInput [formControl]="myFormControl" required [(ngModel)]="number"> <!--HERE -->
</mat-form-field>
<mat-checkbox [(ngModel)]="isRight">Check!</mat-checkbox> <!--HERE -->
</form>
After:
i just added the name
attribute for select
and checkbox
and that fixed the issue. As follows:
<mat-select placeholder="Select your option" name="mySelect"
[(ngModel)]="sample.stat"> <!--HERE: Observe the "name" attribute -->
<input id="myInput" type="text" placeholder="Enter number" aria-label="Number"
matInput [formControl]="myFormControl" required [(ngModel)]="number"> <!--HERE -->
<mat-checkbox name="myCheck" [(ngModel)]="isRight">Check!</mat-checkbox> <!--HERE: Observe the "name" attribute -->
As you see added the name
attribute. It is not necessary to be given same as your ngModel
name. Just providing the name
attribute will fix the issue.
A case where regular expressions are justified:
import re
DATA = "Hey, you - what are you doing here!?"
print re.findall(r"[\w']+", DATA)
# Prints ['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
You are doing
Object o = prestListView.getItemAtPosition(position);
String str=(String)o;//As you are using Default String Adapter
The o
that you get back is not a String, but a prestationEco
so you get a CCE when doing the (String)o
In case you want to pass in a block, say, for a glyphicon button, as in the following:
<%= link_to my_url, class: "stuff" do %>
<i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>
Then passing querystrings params could be accomplished through:
<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
<i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>
I agree with the other answers. You cannot rely on the ordering of JSON elements.
However if we need to have an ordered JSON, one solution might be to prepare a LinkedHashMap object with elements and convert it to JSONObject.
@Test
def void testOrdered() {
Map obj = new LinkedHashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Ordered Json : %s", json.toString())
String expectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
assertEquals(expectedJsonString, json.toString())
JSONAssert.assertEquals(JSONSerializer.toJSON(expectedJsonString), json)
}
Normally the order is not preserved as below.
@Test
def void testUnordered() {
Map obj = new HashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Unordered Json : %s", json.toString(3, 3))
String unexpectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
// string representation of json objects are different
assertFalse(unexpectedJsonString.equals(json.toString()))
// json objects are equal
JSONAssert.assertEquals(JSONSerializer.toJSON(unexpectedJsonString), json)
}
You may check my post too: http://www.flyingtomoon.com/2011/04/preserving-order-in-json.html
Use Ctrl+Shift+C (or Cmd+Shift+C on Mac) to open the DevTools in Inspect Element mode, or toggle Inspect Element mode if the DevTools are already open.
I know this question is on Linux, but on windows I had the same issue. Turns out you have to start the command prompt in "Run As Administrator" mode for it to work. Otherwise you get the same: unable to write 'random state' error.
From following this thread down the rabbit hole, I came to this, works on Win10 and Ubuntu 20.04. I wanted more than just killing the script, and to use specific keys, and it had to work in both MS and Linux..
import _thread
import time
import sys
import os
class _Getch:
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
msvcrt_char = msvcrt.getch()
return msvcrt_char.decode("utf-8")
def input_thread(key_press_list):
char = 'x'
while char != 'q': #dont keep doing this after trying to quit, or 'stty sane' wont work
time.sleep(0.05)
getch = _Getch()
char = getch.impl()
pprint("getch: "+ str(char))
key_press_list.append(char)
def quitScript():
pprint("QUITTING...")
time.sleep(0.2) #wait for the thread to die
os.system('stty sane')
sys.exit()
def pprint(string_to_print): #terminal is in raw mode so we need to append \r\n
print(string_to_print, end="\r\n")
def main():
key_press_list = []
_thread.start_new_thread(input_thread, (key_press_list,))
while True:
#do your things here
pprint("tick")
time.sleep(0.5)
if key_press_list == ['q']:
key_press_list.clear()
quitScript()
elif key_press_list == ['j']:
key_press_list.clear()
pprint("knock knock..")
elif key_press_list:
key_press_list.clear()
main()
Another way would be to catch the exeption:
def is_nat(npdatetime):
try:
npdatetime.strftime('%x')
return False
except:
return True
There is actually a clever way to do this that is useful for any list of tuples where the size of each tuple is 2: you can convert your list into a single dictionary.
For example,
test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1
Swift 5. Thanks to Emin Bugra Saral above for the startOfDay
suggestion.
extension Date {
func daysBetween(date: Date) -> Int {
return Date.daysBetween(start: self, end: date)
}
static func daysBetween(start: Date, end: Date) -> Int {
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: start)
let date2 = calendar.startOfDay(for: end)
let a = calendar.dateComponents([.day], from: date1, to: date2)
return a.value(for: .day)!
}
}
Usage:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let start = dateFormatter.date(from: "2017-01-01")!
let end = dateFormatter.date(from: "2018-01-01")!
let diff = Date.daysBetween(start: start, end: end) // 365
// or
let diff = start.daysBetween(date: end) // 365
vim plugin unimpaired.vim [e and ]e
Best way to read large file, line by line is to use python enumerate function
with open(file_name, "rU") as read_file:
for i, row in enumerate(read_file, 1):
#do something
#i in line of that line
#row containts all data of that line
Well in general index is a B-tree
. There are two types of indexes: clustered and nonclustered.
Clustered index creates a physical order of rows (it can be only one and in most cases it is also a primary key - if you create primary key on table you create clustered index on this table also).
Nonclustered index is also a binary tree but it doesn't create a physical order of rows. So the leaf nodes of nonclustered index contain PK (if it exists) or row index.
Indexes are used to increase the speed of search. Because the complexity is of O(log N). Indexes is very large and interesting topic. I can say that creating indexes on large database is some kind of art sometimes.
Try Selenium 2.0b1. It has different core than the first version. It should support popup dialogs according to documentation:
Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggered and action that would open a popup, you can access the alert with the following:
Java
Alert alert = driver.switchTo().alert();
Ruby
driver.switch_to.alert
This will return the currently open alert object. With this object you can now accept, dismiss, read it’s contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the JavaDocs for more information.
Create a css class that applies the row color, and use jQuery to toggle the class on/off:
CSS:
.selected {
background-color: blue;
}
jQuery:
$('#data tr').on('click', function() {
$(this).toggleClass('selected');
});
The first click will add the class (making the background color blue), and the next click will remove the class, reverting it to whatever it was before. Repeat!
In terms of the two CSS classes you already have, I would change the .nonhighlighted
class to apply to all rows of the table by default, then toggle the .highlighted
on and off:
<style type="text/css">
.highlighted {
background: red;
}
#data tr {
background: white;
}
</style>
$('#data tr').on('click', function() {
$(this).toggleClass('highlighted');
});
Apart from above Programmatic approach Using Flower Task status can be easily seen.
Real-time monitoring using Celery Events. Flower is a web based tool for monitoring and administrating Celery clusters.
Official Document: Flower - Celery monitoring tool
Installation:
$ pip install flower
Usage:
http://localhost:5555
SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2 FROM tableOne
LEFT JOIN tableTwo
ON tableTwo.query = query2
It is all about the right tool for the job. Neither is better 100% of the time. Both systems were created by man and have flaws. Sorry, but we suck and making perfect stuff.
I like dynamic typing because it gets out of my way, but yes runtime errors can creep up that I didn't plan for. Where as static typing may fix the aforementioned errors, but drive a novice(in typed languages) programmer crazy trying to cast between a constant char and a string.
git push --dry-run
git diff --stat HEAD remote/branch
For me (also XAMPP on Windows 7), this is what worked:
<Directory "C:\projects\myfolder\htdocs">`
AllowOverride All
Require all granted
Options Indexes FollowSymLinks
</Directory>`
It is this line that would cause the 403:
Order allow,deny
Go to ezwinports, https://sourceforge.net/projects/ezwinports/files/
Download make-4.2.1-without-guile-w32-bin.zip (get the version without guile)
Another use that I've been putting to good purpose is fetching data from multiple sources. In the example below, I'm fetching multiple, independent JSON schema objects used in an existing application for validation between a client and a REST server. In this case, I don't want the browser-side application to start loading data before it has all the schemas loaded. $.when.apply().then() is perfect for this. Thank to Raynos for pointers on using then(fn1, fn2) to monitor for error conditions.
fetch_sources = function (schema_urls) {
var fetch_one = function (url) {
return $.ajax({
url: url,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
return $.map(schema_urls, fetch_one);
}
var promises = fetch_sources(data['schemas']);
$.when.apply(null, promises).then(
function () {
var schemas = $.map(arguments, function (a) {
return a[0]
});
start_application(schemas);
}, function () {
console.log("FAIL", this, arguments);
});
There is now an import functionality on Android ICS 4.0.4.
First you must save your .vcf
file on a storage (USB storage, or SDcard).
Android will scan the selected storage to detect any .vcf
file and will import it on the selected address book.
The functionality is in the option menu of your contact list.
!Note: Be careful while doing this! Android will import EVERYTHING that is a .vcf
in your storage. It's all or nothing, and the consequence can be trashing your address book.
The command I used with Azure DevOps when I encountered the message "updates were rejected because the tip of your current branch is behind" was/is this command:
git pull origin master
(or can start with a new folder and do a Clone) ..
This answer doesn't address the question posed, specifically, Keif has answered this above, but it does answer the question's title/heading text and this will be a common question for Azure DevOps users.
I noted comment: "You'd always want to make sure that you do a pull before pushing" in answer from Keif above !
I have also used Git Gui tool in addition to Git command line tool.
(I wasn't sure how to do the equivalent of the command line command "git pull origin master" within Git Gui so I'm back to command line to do this).
A diagram that shows various git commands for various actions that you might want to undertake is this one:
add this code to Your AppKernel Class:
public function init()
{
date_default_timezone_set('Asia/Tehran');
parent::init();
}
Define the parent with display: table
and the element itself with vertical-align: middle
and display: table-cell
.
You also can use in this form:
<a href="@Url.Action("Information", "Admin", null)"> Admin</a>
You might also consider adding "
.
For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus"
is very good idea.
Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.
Associative Array
var a = new Array(1,2,3);
a['key'] = 'experiment';
Array.isArray(a);
returns true
Keep in mind that a.length
will be undefined, because length
is treated as a key, you should use Object.keys(a).length
to get the length of an Associative Array.
Object
var a = {1:1, 2:2, 3:3,'key':'experiment'};
Array.isArray(a)
returns false
JSON returns an Object ... could return an Associative Array ... but it is not like that
you just need to get the absolute-path of the file, since the file you are looking for doesnt exist in the eclipse's runtime workspace you can use - getProperty() or getLocationURI() methods to get the absolute-path of the file
I ended up with a combination of Roberts and chirags answers:
((EditText)findViewById(R.id.search_field)).setOnEditorActionListener(
new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Identifier of the action. This will be either the identifier you supplied,
// or EditorInfo.IME_NULL if being called due to the enter key being pressed.
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
onSearchAction(v);
return true;
}
// Return true if you have consumed the action, else false.
return false;
}
});
Update: The above code would some times activate the callback twice. Instead I've opted for the following code, which I got from the Google chat clients:
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// If triggered by an enter key, this is the event; otherwise, this is null.
if (event != null) {
// if shift key is down, then we want to insert the '\n' char in the TextView;
// otherwise, the default action is to send the message.
if (!event.isShiftPressed()) {
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
return false;
}
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
With numpy, you can pass a slice for each component of the index - so, your x[0:2,0:2]
example above works.
If you just want to evenly skip columns or rows, you can pass slices with three components (i.e. start, stop, step).
Again, for your example above:
>>> x[1:4:2, 1:4:2]
array([[ 5, 7],
[13, 15]])
Which is basically: slice in the first dimension, with start at index 1, stop when index is equal or greater than 4, and add 2 to the index in each pass. The same for the second dimension. Again: this only works for constant steps.
The syntax you got to do something quite different internally - what x[[1,3]][:,[1,3]]
actually does is create a new array including only rows 1 and 3 from the original array (done with the x[[1,3]]
part), and then re-slice that - creating a third array - including only columns 1 and 3 of the previous array.
You can find default Data and Log locations for the current SQL Server instance by using the following T-SQL:
DECLARE @defaultDataLocation nvarchar(4000)
DECLARE @defaultLogLocation nvarchar(4000)
EXEC master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'DefaultData',
@defaultDataLocation OUTPUT
EXEC master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'DefaultLog',
@defaultLogLocation OUTPUT
SELECT @defaultDataLocation AS 'Default Data Location',
@defaultLogLocation AS 'Default Log Location'
If you get this, the app has installed on your device. You have to tap the icon. It will ask you if you really want to run it. Say “yes
” and then Build & Run again
.
As from iOS 9
, it is required to go to Settings ? General ? Device Management ? Developer App ? Trust`.
On some versions of iOS
, you will have to go to Settings ? General ? Profile instead.
My preferred way is to use circular dependencies*, which node supports
var app = module.exports = express();
as your first order of businessvar app = require('./app')
to access itvar express = require('express');
var app = module.exports = express(); //now app.js can be required to bring app into any file
//some app/middleware, config, setup, etc, including app.use(app.router)
require('./routes'); //module.exports must be defined before this line
var app = require('./app');
app.get('/', function(req, res, next) {
res.render('index');
});
//require in some other route files...each of which requires app independently
require('./user');
require('./blog');
The DateTime.Ticks
property gets the number of ticks that represent the date and time.
10,000 Ticks is a millisecond (10,000,000 ticks per second).
The bit shifting operators do exactly what their name implies. They shift bits. Here's a brief (or not-so-brief) introduction to the different shift operators.
>>
is the arithmetic (or signed) right shift operator.>>>
is the logical (or unsigned) right shift operator.<<
is the left shift operator, and meets the needs of both logical and arithmetic shifts.All of these operators can be applied to integer values (int
, long
, possibly short
and byte
or char
). In some languages, applying the shift operators to any datatype smaller than int
automatically resizes the operand to be an int
.
Note that <<<
is not an operator, because it would be redundant.
Also note that C and C++ do not distinguish between the right shift operators. They provide only the >>
operator, and the right-shifting behavior is implementation defined for signed types. The rest of the answer uses the C# / Java operators.
(In all mainstream C and C++ implementations including GCC and Clang/LLVM, >>
on signed types is arithmetic. Some code assumes this, but it isn't something the standard guarantees. It's not undefined, though; the standard requires implementations to define it one way or another. However, left shifts of negative signed numbers is undefined behaviour (signed integer overflow). So unless you need arithmetic right shift, it's usually a good idea to do your bit-shifting with unsigned types.)
Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit int
would be:
00000000 00000000 00000000 00000110
Shifting this bit pattern to the left one position (6 << 1
) would result in the number 12:
00000000 00000000 00000000 00001100
As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So 6 << 1
is equivalent to 6 * 2
, and 6 << 3
is equivalent to 6 * 8
. A good optimizing compiler will replace multiplications with shifts when possible.
Please note that these are not circular shifts. Shifting this value to the left by one position (3,758,096,384 << 1
):
11100000 00000000 00000000 00000000
results in 3,221,225,472:
11000000 00000000 00000000 00000000
The digit that gets shifted "off the end" is lost. It does not wrap around.
A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12:
00000000 00000000 00000000 00001100
to the right by one position (12 >>> 1
) will get back our original 6:
00000000 00000000 00000000 00000110
So we see that shifting to the right is equivalent to division by powers of 2.
However, a shift cannot reclaim "lost" bits. For example, if we shift this pattern:
00111000 00000000 00000000 00000110
to the left 4 positions (939,524,102 << 4
), we get 2,147,483,744:
10000000 00000000 00000000 01100000
and then shifting back ((939,524,102 << 4) >>> 4
) we get 134,217,734:
00001000 00000000 00000000 00000110
We cannot get back our original value once we have lost bits.
The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the sign bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving.
For example, if we interpret this bit pattern as a negative number:
10000000 00000000 00000000 01100000
we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 >> 4) would give us:
11111000 00000000 00000000 00000110
or the number -134,217,722.
So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2.
You could extend Element to include a method getDirectDesc()
like this:
Element.prototype.getDirectDesc = function() {
const descendants = Array.from(this.querySelectorAll('*'));
const directDescendants = descendants.filter(ele => ele.parentElement === this)
return directDescendants
}
const parent = document.querySelector('.parent')
const directDescendants = parent.getDirectDesc();
document.querySelector('h1').innerHTML = `Found ${directDescendants.length} direct descendants`
_x000D_
<ol class="parent">
<li class="b">child 01</li>
<li class="b">child 02</li>
<li class="b">child 03 <ol>
<li class="c">Not directDescendants 01</li>
<li class="c">Not directDescendants 02</li>
</ol>
</li>
<li class="b">child 04</li>
<li class="b">child 05</li>
</ol>
<h1></h1>
_x000D_
Android complete source code for adding events and reminders with start and end time format.
/** Adds Events and Reminders in Calendar. */
private void addReminderInCalendar() {
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(true) + "events");
ContentResolver cr = getContentResolver();
TimeZone timeZone = TimeZone.getDefault();
/** Inserting an event in calendar. */
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.TITLE, "Sanjeev Reminder 01");
values.put(CalendarContract.Events.DESCRIPTION, "A test Reminder.");
values.put(CalendarContract.Events.ALL_DAY, 0);
// event starts at 11 minutes from now
values.put(CalendarContract.Events.DTSTART, cal.getTimeInMillis() + 11 * 60 * 1000);
// ends 60 minutes from now
values.put(CalendarContract.Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.HAS_ALARM, 1);
Uri event = cr.insert(EVENTS_URI, values);
// Display event id
Toast.makeText(getApplicationContext(), "Event added :: ID :: " + event.getLastPathSegment(), Toast.LENGTH_SHORT).show();
/** Adding reminder for event added. */
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(true) + "reminders");
values = new ContentValues();
values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
values.put(CalendarContract.Reminders.METHOD, Reminders.METHOD_ALERT);
values.put(CalendarContract.Reminders.MINUTES, 10);
cr.insert(REMINDERS_URI, values);
}
/** Returns Calendar Base URI, supports both new and old OS. */
private String getCalendarUriBase(boolean eventUri) {
Uri calendarURI = null;
try {
if (android.os.Build.VERSION.SDK_INT <= 7) {
calendarURI = (eventUri) ? Uri.parse("content://calendar/") : Uri.parse("content://calendar/calendars");
} else {
calendarURI = (eventUri) ? Uri.parse("content://com.android.calendar/") : Uri
.parse("content://com.android.calendar/calendars");
}
} catch (Exception e) {
e.printStackTrace();
}
return calendarURI.toString();
}
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
I always try to factor out complex boolean expressions into meaningful variables (you could probably think of better names based on what these columns are used for):
bool notColumnsABC = (columnname != a && columnname != b && columnname != c);
bool notColumnA2OrBoxIsChecked = ( columnname != A2 || checkbox.checked );
if ( notColumnsABC
&& notColumnA2OrBoxIsChecked )
{
"statement 1"
}
Press Ctrl+C
When you start the server it mentions this in the startup text.
This is a way to do it with the name:
Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
MessageBox.Show("nothing");
else
MessageBox.Show("run");
You can loop all process to get the ID for later manipulation:
Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}
@echo off
:START
rmdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause
echo.
echo.
echo Note the directory is not found
echo.
echo Press any key to make a temporary directory, cls, and test again
pause
Mkdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause
echo.
echo press any key to goto START and remove temporary directory
pause
goto START
To get the right ownership, you can set the group setuid bit on the directory with
chmod g+rwxs dirname
This will ensure that files created in the directory are owned by the group. You should then make sure everyone runs with umask 002 or 007 or something of that nature---this is why Debian and many other linux systems are configured with per-user groups by default.
I don't know of a way to force the permissions you want if the user's umask is too strong.
The overall dimensions of a range are in its Width
and Height
properties.
Dim r As Range
Set r = ActiveSheet.Range("A4:H12")
Debug.Print r.Width
Debug.Print r.Height
Can you use date as a factor?
Yes, but you probably shouldn't.
...or should you use
as.Date
on a date column?
Yes.
Which leads us to this:
library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar(stat = "identity") +
theme_bw() +
labs(x = "Month", y = "Average Visits per User") +
scale_x_date(labels = date_format("%m-%Y"))
in which I've added stat = "identity"
to your geom_bar
call.
In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.
replace
isn't available for XSLT 1.0.
Codesling has a template for string-replace you can use as a substitute for the function:
<xsl:template name="string-replace-all">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="$text = '' or $replace = ''or not($replace)" >
<!-- Prevent this routine from hanging -->
<xsl:value-of select="$text" />
</xsl:when>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)" />
<xsl:value-of select="$by" />
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
invoked as:
<xsl:variable name="newtext">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="$text" />
<xsl:with-param name="replace" select="a" />
<xsl:with-param name="by" select="b" />
</xsl:call-template>
</xsl:variable>
On the other hand, if you literally only need to replace one character with another, you can call translate
which has a similar signature. Something like this should work fine:
<xsl:variable name="newtext" select="translate($text,'a','b')"/>
Also, note, in this example, I changed the variable name to "newtext", in XSLT variables are immutable, so you can't do the equivalent of $foo = $foo
like you had in your original code.
If you don't want to use any java predefined libraries then below is the
simplest way
public class Test {
public static void main(String[] args) {
double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4,
8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2,
3.5, 3, 1.1, 6.5, 5.1, -1.2, -5.1, 2, 5.2, 2.1};
double maxx = decMax[0];
for (int i = 0; i < decMax.length; i++) {
if (maxx < decMax[i]) {
maxx = decMax[i];
}
}
System.out.println(maxx);
}
}
Basic docker-compose.yml
with extra hosts:
version: '3'
services:
api:
build: .
ports:
- "5003:5003"
extra_hosts:
- "your-host.name.com:162.242.195.82" #host and ip
- "your-host--1.name.com your-host--2.name.com:50.31.209.229" #multiple hostnames with same ip
The content in the /etc/hosts
file in the created container:
162.242.195.82 your-host.name.com
50.31.209.229 your-host--1.name.com your-host--2.name.com
You can check the /etc/hosts
file with the following commands:
$ docker-compose -f path/to/file/docker-compose.yml run api bash # 'api' is service name
#then inside container bash
root@f7c436910676:/app# cat /etc/hosts
Executing seq(1, 10, 1)
does what 1:10
does. You can change the last parameter of seq
, i.e. by
, to be the step of whatever size you like.
> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability
> [1] 0 2 4 6 8 10
$.fn.disableScroll = function() {
window.oldScrollPos = $(window).scrollTop();
$(window).on('scroll.scrolldisabler',function ( event ) {
$(window).scrollTop( window.oldScrollPos );
event.preventDefault();
});
};
$.fn.enableScroll = function() {
$(window).off('scroll.scrolldisabler');
};
//disable
$("#selector").disableScroll();
//enable
$("#selector").enableScroll();
Holdover from C.
You can use :
const intersection = array1.filter(element => array2.includes(element));
An easy short hand way would be to use +x It keeps the sign intact as well as the decimal numbers. The other alternative is to use parseFloat(x). Difference between parseFloat(x) and +x is for a blank string +x returns 0 where as parseFloat(x) returns NaN.
MenuItem Import = menu.findItem(R.id.Import);
Import.setVisible(false)
You can try this one it is short :)
SystemClock.sleep(7000);
It will sleep for 7 sec look at documentation
In order to completely set the background to a given color :
1) set first the background color
2) call method "Clear(0,0,this.getWidth(),this.getHeight())" (width and height of the component paint area)
I think it is the basic procedure to set the background... I've had the same problem.
Another usefull hint : if you want to draw BUT NOT in a specific zone (something like a mask or a "hole"), call the setClip() method of the graphics with the "hole" shape (any shape) and then call the Clear() method (background should previously be set to the "hole" color).
You can make more complicated clip zones by calling method clip() (any times you want) AFTER calling method setClip() to have intersections of clipping shapes.
I didn't find any method for unions or inversions of clip zones, only intersections, too bad...
Hope it helps
git pull
is really just a shorthand for git pull <remote> <branchname>
, in most cases it's equivalent to git pull origin master
. You will need to add another remote and pull explicitly from it. This page describes it in detail:
Using standard C++ calling (note that you should use namespace std for cout or add using namespace std;)
#include <iostream>
int main()
{
std::cout<<"Hello World!\n";
return 0;
}
I spent lots of hours on it when I call PHP script to init
and commit
to git.
And I found the work flow should be as:
git init
git config user.name "someone"
git config user.email "[email protected]"
git add *
git commit -m "some init msg"
If you swap [23] and 1, the config will not work at all.
I wish this will do some help.
requests
does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.
Python comes with built-in XML parsers. I recommend you use the ElementTree API:
import requests
from xml.etree import ElementTree
response = requests.get(url)
tree = ElementTree.fromstring(response.content)
or, if the response is particularly large, use an incremental approach:
response = requests.get(url, stream=True)
# if the server sent a Gzip or Deflate compressed response, decompress
# as we read the raw stream:
response.raw.decode_content = True
events = ElementTree.iterparse(response.raw)
for event, elem in events:
# do something with `elem`
The external lxml project builds on the same API to give you more features and power still.
You should check out Softerra's LDAP Browser (the free version of LDAP Administrator), which can be downloaded here :
http://www.ldapbrowser.com/download.htm
I've used this application extensively for all my Active Directory, OpenLDAP, and Novell eDirectory development, and it has been absolutely invaluable.
If you just want to check and see if a username\password combination works, all you need to do is create a "Profile" for the LDAP server, and then enter the credentials during Step 3 of the creation process :
By clicking "Finish", you'll effectively issue a bind to the server using the credentials, auth mechanism, and password you've specified. You'll be prompted if the bind does not work.
Honestly, I feel more comfortable with Alfred blog definitions:
Object: real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and behavior (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.
Class: is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.
Instance: An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.
Given the next example:
public class Person {
private int id;
private String name;
private int age;
public Person (int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
return true;
}
public static void main(String[] args) {
//case 1
Person p1 = new Person(1, "Carlos", 20);
Person p2 = new Person(1, "Carlos", 20);
//case 2
Person p3 = new Person(2, "John", 15);
Person p4 = new Person(3, "Mary", 17);
}
}
For case 1, there are two instances of the class Person, but both instances represent the same object.
For case 2, there are two instances of the class Person, but each instance represent a different object.
So class, object and instance are different things. Object and instance are not synonyms as is suggested in the answer selected as right answer.
Since Java 1.5 you can use the String.format
method. For example, to do the same thing as your example:
String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;
In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:
%% --> %
0 --> 0
%d --> <value of digits>
d --> d
So if digits is equal to 5, the format string becomes %05d
which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format
for more information on the conversion specifiers.
background: url(../images/backgroundImage.jpg) no-repeat center center fixed;
this should help
Python really tries hard to intelligently set sys.path
. How it is
set can get really complicated. The following guide is a watered-down,
somewhat-incomplete, somewhat-wrong, but hopefully-useful guide
for the rank-and-file python programmer of what happens when python
figures out what to use as the initial values of sys.path
,
sys.executable
, sys.exec_prefix
, and sys.prefix
on a normal
python installation.
First, python does its level best to figure out its actual physical
location on the filesystem based on what the operating system tells
it. If the OS just says "python" is running, it finds itself in $PATH.
It resolves any symbolic links. Once it has done this, the path of
the executable that it finds is used as the value for sys.executable
, no ifs,
ands, or buts.
Next, it determines the initial values for sys.exec_prefix
and
sys.prefix
.
If there is a file called pyvenv.cfg
in the same directory as
sys.executable
or one directory up, python looks at it. Different
OSes do different things with this file.
One of the values in this config file that python looks for is
the configuration option home = <DIRECTORY>
. Python will use this directory instead of the directory containing sys.executable
when it dynamically sets the initial value of sys.prefix
later. If the applocal = true
setting appears in the
pyvenv.cfg
file on Windows, but not the home = <DIRECTORY>
setting,
then sys.prefix
will be set to the directory containing sys.executable
.
Next, the PYTHONHOME
environment variable is examined. On Linux and Mac,
sys.prefix
and sys.exec_prefix
are set to the PYTHONHOME
environment variable, if
it exists, superseding any home = <DIRECTORY>
setting in pyvenv.cfg
. On Windows,
sys.prefix
and sys.exec_prefix
is set to the PYTHONHOME
environment variable,
if it exists, unless a home = <DIRECTORY>
setting is present in pyvenv.cfg
,
which is used instead.
Otherwise, these sys.prefix
and sys.exec_prefix
are found by walking backwards
from the location of sys.executable
, or the home
directory given by pyvenv.cfg
if any.
If the file lib/python<version>/dyn-load
is found in that directory
or any of its parent directories, that directory is set to be to be
sys.exec_prefix
on Linux or Mac. If the file
lib/python<version>/os.py
is is found in the directory or any of its
subdirectories, that directory is set to be sys.prefix
on Linux,
Mac, and Windows, with sys.exec_prefix
set to the same value as
sys.prefix
on Windows. This entire step is skipped on Windows if
applocal = true
is set. Either the directory of sys.executable
is
used or, if home
is set in pyvenv.cfg
, that is used instead for
the initial value of sys.prefix
.
If it can't find these "landmark" files or sys.prefix
hasn't been
found yet, then python sets sys.prefix
to a "fallback"
value. Linux and Mac, for example, use pre-compiled defaults as the
values of sys.prefix
and sys.exec_prefix
. Windows waits
until sys.path
is fully figured out to set a fallback value for
sys.prefix
.
Then, (what you've all been waiting for,) python determines the initial values
that are to be contained in sys.path
.
sys.path
.
On Windows, this is always the empty string, which tells python to
use the full path where the script is located instead.sys.path
, unless you're
on Windows and applocal
is set to true in pyvenv.cfg
.<prefix>/lib/python35.zip
on Linux/Mac and
os.path.join(os.dirname(sys.executable), "python.zip")
on Windows, is added to sys.path
.applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;sys.prefix
.sys.exec_prefix
is added. On Windows, the directory
which was used (or would have been used) to search dynamically for sys.prefix
is
added.At this stage on Windows, if no prefix was found, then python will try to
determine it by searching all the directories in sys.path
for the landmark files,
as it tried to do with the directory of sys.executable
previously, until it finds something.
If it doesn't, sys.prefix
is left blank.
Finally, after all this, Python loads the site
module, which adds stuff yet further to sys.path
:
It starts by constructing up to four directories from a head and a tail part. For the head part, it uses
sys.prefix
andsys.exec_prefix
; empty heads are skipped. For the tail part, it uses the empty string and thenlib/site-packages
(on Windows) orlib/pythonX.Y/site-packages
and thenlib/site-python
(on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.
Alternatively, when you want to save individual R objects, I recommend using saveRDS
.
You can save R objects using saveRDS
, then load them into R with a new variable name using readRDS
.
Example:
# Save the city object
saveRDS(city, "city.rds")
# ...
# Load the city object as city
city <- readRDS("city.rds")
# Or with a different name
city2 <- readRDS("city.rds")
But when you want to save many/all your objects in your workspace, use Manetheran's answer.
var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +' value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
});
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);
I tries below steps and it worked: 1. cd ~ 2. cd .aws 3. vi credentials 4. delete aws_access_key_id = aws_secret_access_key = by placing cursor on that line and pressing dd (vi command to delete line).
Delete both the line and check gain.
These instructions apply if you installed using the official Jenkins Mac installer from http://jenkins-ci.org/
Execute uninstall script from terminal:
'/Library/Application Support/Jenkins/Uninstall.command'
or use Finder to navigate into that folder and double-click on Uninstall.command.
Finally delete last configuration bits which might have been forgotten:
sudo rm -rf /var/root/.jenkins ~/.jenkins
If the uninstallation script cannot be found (older Jenkins version), use following commands:
sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins "/Library/Application Support/Jenkins" /Library/Documentation/Jenkins
and if you want to get rid of all the jobs and builds:
sudo rm -rf /Users/Shared/Jenkins
and to delete the jenkins user and group (if you chose to use them):
sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins
These commands are also invoked by the uninstall script in newer Jenkins versions, and should be executed too:
sudo rm -f /etc/newsyslog.d/jenkins.conf
pkgutil --pkgs | grep 'org\.jenkins-ci\.' | xargs -n 1 sudo pkgutil --forget
var save_val = $("form").serializeArray();
$(save_val).each(function( index, element ) {
alert(element.name);
alert(element.val);
});
Implementing a "Keep Me Logged In" feature means you need to define exactly what that will mean to the user. In the simplest case, I would use that to mean the session has a much longer timeout: 2 days (say) instead of 2 hours. To do that, you will need your own session storage, probably in a database, so you can set custom expiry times for the session data. Then you need to make sure you set a cookie that will stick around for a few days (or longer), rather than expire when they close the browser.
I can hear you asking "why 2 days? why not 2 weeks?". This is because using a session in PHP will automatically push the expiry back. This is because a session's expiry in PHP is actually an idle timeout.
Now, having said that, I'd probably implement a harder timeout value that I store in the session itself, and out at 2 weeks or so, and add code to see that and to forcibly invalidate the session. Or at least to log them out. This will mean that the user will be asked to login periodically. Yahoo! does this.
An adaptation of unutbu's answer that I found useful in my own code:
example_dict.setdefaut('key1', {}).get('key2')
It generates a dictionary entry for key1 if it does not have that key already so that you avoid the KeyError. If you want to end up a nested dictionary that includes that key pairing anyway like I did, this seems like the easiest solution.
What if your lists contain duplicates like this:
v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']
Sets do not contain duplicates. So, the following line returns True.
set(v2).issubset(v1)
To count for duplicates, you can use the code:
v1 = sorted(v1)
v2 = sorted(v2)
def is_subseq(v2, v1):
"""Check whether v2 is a subsequence of v1."""
it = iter(v1)
return all(c in it for c in v2)
So, the following line returns False.
is_subseq(v2, v1)
Updated method from same article Avindra mentioned — injects iframe and compare its contentWindow
properties to global window properties.
(function() {_x000D_
var iframe = document.createElement('iframe');_x000D_
iframe.onload = function() {_x000D_
var iframeKeys = Object.keys(iframe.contentWindow);_x000D_
Object.keys(window).forEach(function(key) {_x000D_
if(!(iframeKeys.indexOf(key) > -1)) {_x000D_
console.log(key);_x000D_
}_x000D_
});_x000D_
};_x000D_
iframe.src = 'about:blank';_x000D_
document.body.appendChild(iframe);_x000D_
})();
_x000D_
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
You can migrate to XDocument instead of XmlDocument and then use Linq if you prefer that syntax. Something like:
var q = (from myConfig in xDoc.Elements("MyConfiguration")
select myConfig.Attribute("SuperString").Value)
.First();
Use DecimalFormat
double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
None of the above answers worked for me in ansible 2.3.0.0, but the following does:
when: variable1 | search("value")
In ansible 2.9 this is deprecated in favor of using ~ concatenation for variable replacement:
when: "variable1.find('v=' ~ value) == -1"
http://jinja.pocoo.org/docs/dev/templates/#other-operators
Other options:
when: "inventory_hostname in groups[sync_source]"
Shortest Code
[x for _,x in sorted(zip(Y,X))]
Example:
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Z = [x for _,x in sorted(zip(Y,X))]
print(Z) # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
Generally Speaking
[x for _, x in sorted(zip(Y,X), key=lambda pair: pair[0])]
Explained:
zip
the two list
s.list
based on the zip
using sorted()
.list
.For more information on how to set\use the key
parameter as well as the sorted
function in general, take a look at this.
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
Actually, Double.NaN
is supported in all .NET versions 2.0 and greater.
Also make sure that you have allowed codeigniter to log the type of messages you want in a config file.
i.e $config['log_threshold'] = [log_level ranges 0-4];
At times it is quite handy to get the auto increment primary key (id
) of the row if it exists and 0
if it doesn't.
Here's how this can be done in a single query:
SELECT IFNULL(`id`, COUNT(*)) FROM WHERE ...
You can use the lastval()
function:
Return value most recently obtained with
nextval
for any sequence
So something like this:
INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val) VALUES (lastval());
This will work fine as long as no one calls nextval()
on any other sequence (in the current session) between your INSERTs.
As Denis noted below and I warned about above, using lastval()
can get you into trouble if another sequence is accessed using nextval()
between your INSERTs. This could happen if there was an INSERT trigger on Table1
that manually called nextval()
on a sequence or, more likely, did an INSERT on a table with a SERIAL
or BIGSERIAL
primary key. If you want to be really paranoid (a good thing, they really are you to get you after all), then you could use currval()
but you'd need to know the name of the relevant sequence:
INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val) VALUES (currval('Table1_id_seq'::regclass));
The automatically generated sequence is usually named t_c_seq
where t
is the table name and c
is the column name but you can always find out by going into psql
and saying:
=> \d table_name;
and then looking at the default value for the column in question, for example:
id | integer | not null default nextval('people_id_seq'::regclass)
FYI: lastval()
is, more or less, the PostgreSQL version of MySQL's LAST_INSERT_ID
. I only mention this because a lot of people are more familiar with MySQL than PostgreSQL so linking lastval()
to something familiar might clarify things.
Try this online tool: https://www.wsdl-analyzer.com. It appears to be free and does a lot more than just generate XML for requests and response.
There is also this: https://www.oxygenxml.com/xml_editor/wsdl_soap_analyzer.html, which can be downloaded, but not free.
FileStream fileStream = new FileStream("file.txt", FileMode.Open);
using (StreamReader reader = new StreamReader(fileStream))
{
string line = reader.ReadLine();
}
Using the System.IO.FileStream and System.IO.StreamReader. You can use System.IO.BinaryReader or System.IO.BinaryWriter as well.
Why not using pyvmomi original function SmartConnectNoSSL
.
They added this function on June 14, 2016
and named it ConnectNoSSL
, one day after they changed the name to SmartConnectNoSSL
, use that instead of by passing the warning with unnecessary lines of code in your project?
Provides a standard method for connecting to a specified server without SSL verification. Useful when connecting to servers with self-signed certificates or when you wish to ignore SSL altogether
service_instance = connect.SmartConnectNoSSL(host=args.ip,
user=args.user,
pwd=args.password)
base on @Data-Base answer it will not work until make selection mode FullRow
MyDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
but if you need to make it work in CellSelect Mode
MyDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect;
// for cell selection
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
var hit = MyDataGridView.HitTest(e.X, e.Y);
MyDataGridView.ClearSelection();
// cell selection
MyDataGridView[hit.ColumnIndex,hit.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
int rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
If you are having a problem with NULL values, use the COALESCE function to replace the NULL with the value of your choice. Your query would then look like this:
SELECT (COALESCE(field1, '') + '' + COALESCE(field2, '') + '' + COALESCE(field3,'')) FROM table1
2.0 Compatible Answer: In Tensorflow 2.x (2.1)
, you can get the dimensions (shape) of the tensor as integer values, as shown in the Code below:
Method 1 (using tf.shape
):
import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.shape.as_list()
print(Shape) # [2,3]
Method 2 (using tf.get_shape()
):
import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.get_shape().as_list()
print(Shape) # [2,3]
Using 7-Zip:
Zip: you have a folder foo
, and want to zip it to myzip.zip
"C:\Program Files\7-Zip\7z.exe" a -r myzip.zip -w foo -mem=AES256
Unzip: you want to unzip it (myzip.zip
) to current directory (./
)
"C:\Program Files\7-Zip\7z.exe" x myzip.zip -o./ -y -r
Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field
to get the file,
In controller,
@person = Person.new(person_params)
Here person_params
return whitelisted params[:person]
(define yourself)
Save file as,
dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless File.directory? dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")
Note, Add this path in .gitignore
& if you want to use this file again add this path asset_path
an of application by application.rb
Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets
note: Storing files like this will increase the size of the application, better to store in the database using paperclip
.
I was able to get this work. I added the following to my custom CSS:
.wpcf7-form textarea{
width: 100% !important;
height:50px;
}
For those that works with the mysql connector you can use this code as a start. (Thanks to @Daniel Velkov)
Used refs:
import pandas as pd
import mysql.connector
# Setup MySQL connection
db = mysql.connector.connect(
host="<IP>", # your host, usually localhost
user="<USER>", # your username
password="<PASS>", # your password
database="<DATABASE>" # name of the data base
)
# You must create a Cursor object. It will let you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM <TABLE>")
# Put it all to a data frame
sql_data = pd.DataFrame(cur.fetchall())
sql_data.columns = cur.column_names
# Close the session
db.close()
# Show the data
print(sql_data.head())
If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
If you only need string values in the array, the following will work:
function hasDuplicates(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
We use a "hash table" valuesSoFar
whose keys are the values we've seen in the array so far. We do a lookup using in
to see if that value has been spotted already; if so, we bail out of the loop and return true
.
If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).
function hasDuplicates(array) {
var valuesSoFar = [];
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (valuesSoFar.indexOf(value) !== -1) {
return true;
}
valuesSoFar.push(value);
}
return false;
}
The difference is simply that we use an array instead of a hash table for valuesSoFar
, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in
, instead getting an O(n) lookup time of indexOf
.
ENOENT
means it's not there.
Just update your code to:
File.open(File.dirname(__FILE__) + '/text.txt').each {|line| puts line}
This error is cause by security clutches between the web application and your java. To resolve it, look into your java setting under control panel. Move the security level to a medium.
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.
You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode
Edit: in case something happens to kill the msdn link, here is the content:
Specifying Document Compatibility Modes
You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.
<html> <head> <!-- Enable IE9 Standards mode --> <meta http-equiv="X-UA-Compatible" content="IE=9" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.
The following example specifies EmulateIE7 mode.
<html> <head> <!-- Mimic Internet Explorer 7 --> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.
Try the following decorators:
@app.route('/email/',methods=['POST', 'OPTIONS']) #Added 'Options'
@crossdomain(origin='*') #Added
def hello_world():
name=request.form['name']
email=request.form['email']
phone=request.form['phone']
description=request.form['description']
mandrill.send_email(
from_email=email,
from_name=name,
to=[{'email': app.config['QOLD_SUPPORT_EMAIL']}],
text="Phone="+phone+"\n\n"+description
)
return '200 OK'
if __name__ == '__main__':
app.run()
This decorator would be created as follows:
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
You can also check out this package Flask-CORS
Ok, let me give the details of code, how to use other module's component.
For example, I have M2 module, M2 module have comp23 component and comp2 component, Now I want to use comp23 and comp2 in app.module, here is how:
this is app.module.ts, see my comment,
// import this module's ALL component, but not other module's component, only this module
import { AppComponent } from './app.component';
import { Comp1Component } from './comp1/comp1.component';
// import all other module,
import { SwModule } from './sw/sw.module';
import { Sw1Module } from './sw1/sw1.module';
import { M2Module } from './m2/m2.module';
import { CustomerDashboardModule } from './customer-dashboard/customer-dashboard.module';
@NgModule({
// declare only this module's all component, not other module component.
declarations: [
AppComponent,
Comp1Component,
],
// imports all other module only.
imports: [
BrowserModule,
SwModule,
Sw1Module,
M2Module,
CustomerDashboardModule // add the feature module here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
this is m2 module:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// must import this module's all component file
import { Comp2Component } from './comp2/comp2.component';
import { Comp23Component } from './comp23/comp23.component';
@NgModule({
// import all other module here.
imports: [
CommonModule
],
// declare only this module's child component.
declarations: [Comp2Component, Comp23Component],
// for other module to use these component, must exports
exports: [Comp2Component, Comp23Component]
})
export class M2Module { }
My commend in code explain what you need to do here.
now in app.component.html, you can use
<app-comp23></app-comp23>
follow angular doc sample import modul
Just use readLines
on your file:
R> res <- readLines(system.file("DESCRIPTION", package="MASS"))
R> length(res)
[1] 27
R> res
[1] "Package: MASS"
[2] "Priority: recommended"
[3] "Version: 7.3-18"
[4] "Date: 2012-05-28"
[5] "Revision: $Rev: 3167 $"
[6] "Depends: R (>= 2.14.0), grDevices, graphics, stats, utils"
[7] "Suggests: lattice, nlme, nnet, survival"
[8] "Authors@R: c(person(\"Brian\", \"Ripley\", role = c(\"aut\", \"cre\", \"cph\"),"
[9] " email = \"[email protected]\"), person(\"Kurt\", \"Hornik\", role"
[10] " = \"trl\", comment = \"partial port ca 1998\"), person(\"Albrecht\","
[11] " \"Gebhardt\", role = \"trl\", comment = \"partial port ca 1998\"),"
[12] " person(\"David\", \"Firth\", role = \"ctb\"))"
[13] "Description: Functions and datasets to support Venables and Ripley,"
[14] " 'Modern Applied Statistics with S' (4th edition, 2002)."
[15] "Title: Support Functions and Datasets for Venables and Ripley's MASS"
[16] "License: GPL-2 | GPL-3"
[17] "URL: http://www.stats.ox.ac.uk/pub/MASS4/"
[18] "LazyData: yes"
[19] "Packaged: 2012-05-28 08:47:38 UTC; ripley"
[20] "Author: Brian Ripley [aut, cre, cph], Kurt Hornik [trl] (partial port"
[21] " ca 1998), Albrecht Gebhardt [trl] (partial port ca 1998), David"
[22] " Firth [ctb]"
[23] "Maintainer: Brian Ripley <[email protected]>"
[24] "Repository: CRAN"
[25] "Date/Publication: 2012-05-28 08:53:03"
[26] "Built: R 2.15.1; x86_64-pc-mingw32; 2012-06-22 14:16:09 UTC; windows"
[27] "Archs: i386, x64"
R>
There is an entire manual devoted to this...
When setting Environmental Variables in Windows, I have gone wrong on many, many occasions. I thought I should share a few of my past mistakes here hoping that it might help someone. (These apply to all Environmental Variables, not just when setting Python Path)
Watch out for these possible mistakes:
;C:\Python27
WITHOUT any spaces. (It is common to try C:\SomeOther; C:\Python27
That space (?) after the semicolon is not okay.)echo $PATH
but only backward slashes have worked for me.C:\Python27
NOT C:\Python27\
Hope this helps someone.
It is possible to do everything you want. Aaron's answer was not quite complete.
His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.
The following code snippet grabs the first line of a file and inserts it into the table @Lines:
declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);
declare @Lines table (
line varchar(8000)
);
declare @sql varchar(8000) = '
create table #tmp (
line varchar(8000)
);
bulk insert #tmp
from '''+@filename+'''
with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');
select * from #tmp';
insert into @Lines
exec(@sql);
select * from @lines
What I would do is do this:
<button type="submit" style="background-color:rgba(255,255,255,0.0); border:none;" id="resultButton" onclick="showResults();"><img src="images/search.png" /></button>
I used background-color:rgba(255,255,255,0.0); So that the original background color of a button goes away. The same with the border:none; it will take the original border away.
Since we all love one liners code
Newtonsoft is faster than java script serializer. ... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
if we have class then use below.
Mycustomclassname oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<Mycustomclassname>(jsonString);
no class then use dynamic
var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);
$('inputFile').parent().parent().children('td > label').hide();
can help you navigate two levels up ( to TD, to TR ) moving two levels back down ( all TD's in that TR and their LABEL tags ), applying the hide() function there.
if you want to stay at the TR level and hide them:
$('inputFile').parent().parent().hide();
… is sufficient.
you can navigate very easily through the elements using the jquery selectors.
parent is documented here: http://api.jquery.com/parent/
hide is documented here: http://api.jquery.com/hide/
From http://www.dotnetperls.com:
7z a secure.7z * -pSECRET
Where:
7z : name and path of 7-Zip executable
a : add to archive
secure.7z : name of destination archive
* : add all files from current directory to destination archive
-pSECRET : specify the password "SECRET"
To open :
7z x secure.7z
Then provide the SECRET password
Note: If the password contains spaces or special characters, then enclose it with single quotes
7z a secure.7z * -p"pa$$word @|"
This can be achieved by putting padding between the columns using CSS. You can either add padding to the left of all columns except the first, or add padding to the right of all columns except the last. You should avoid adding padding to the right of the last column or to the left of the first as this will insert redundant white space. You should also avoid being too prescriptive with classes to specify which columns should have the additional padding as this will make maintenance harder if you later add a new column.
The 'lobotomised owl selector' allows you to select all siblings, regardless of if they are a th
, td
or something else.
tr > * + * {
padding-left: 4em;
}
_x000D_
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
_x000D_
if( [txtMobile.text length] == 0 )
{
[Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}
IE7/8/9 seem to behave differently depending on whether the page has focus or not.
If you click on the page and CTRL+F5 then "Cache-Control: no-cache" is included in the request headers. If you click in the Location/Address bar then press CTRL+F5 it isn't.
.... but how do we find the equivalent class in the second List to pass to the method below;
This is your actual problem; you must have at least one immutable property, a id or something like that, to identify corresponding objects in both lists. If you do not have such a property you, cannot solve the problem without errors. You can just try to guess corresponding objects by searching for minimal or logical changes.
If you have such an property, the solution becomes really simple.
Enumerable.Join(
listA, listB,
a => a.Id, b => b.Id,
(a, b) => CompareTwoClass_ReturnDifferences(a, b))
thanks to you both danbruc and Noldorin for your feedback. both Lists will be the same length and in the same order. so the method above is close, but can you modify this method to pass the enum.Current to the method i posted above?
Now I am confused ... what is the problem with that? Why not just the following?
for (Int32 i = 0; i < Math.Min(listA.Count, listB.Count); i++)
{
yield return CompareTwoClass_ReturnDifferences(listA[i], listB[i]);
}
The Math.Min() call may even be left out if equal length is guaranted.
Noldorin's implementation is of course smarter because of the delegate and the use of enumerators instead of using ICollection.
There is a simple way.
You create an iframe which have for source something like "http://your-domain.com/index.php?url=http://the-site-you-want-to-get.com/unicorn
Then, you just get this url with $_GET
and display the contents with file_get_contents($_GET['url']);
You will obtain an iframe which has a domain same than yours, then you will be able to use the $("iframe").contents().find("body")
to manipulate the content.
Try this
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");
There are a couple of options there. The sample code is in Java, but a port to other languages should be straightforward.
WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = (WebElement) ((JavascriptExecutor) driver).executeScript(
"return arguments[0].parentNode;", myElement);
WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = myElement.findElement(By.xpath("./.."));
WebElement
Note: As you can see, for the JavaScript version you'll need the driver
. If you don't have direct access to it, you can retrieve it from the WebElement
using:
WebDriver driver = ((WrapsDriver) myElement).getWrappedDriver();
Write an extension method to express the Right(n);
function. The function should deal with null or empty strings returning an empty string, strings shorter than the max length returning the original string and strings longer than the max length returning the max length of rightmost characters.
public static string Right(this string sValue, int iMaxLength)
{
//Check if the value is valid
if (string.IsNullOrEmpty(sValue))
{
//Set valid empty string as string could be null
sValue = string.Empty;
}
else if (sValue.Length > iMaxLength)
{
//Make the string no longer than the max length
sValue = sValue.Substring(sValue.Length - iMaxLength, iMaxLength);
}
//Return the string
return sValue;
}
ES6 version that return the first #text node content
const extract = (node) => {
const text = [...node.childNodes].find(child => child.nodeType === Node.TEXT_NODE);
return text && text.textContent.trim();
}
Why do you need a cursor at all? Your entire segment of code can be replaced by this, which will run a lot faster on large numbers of rows.
UPDATE tarinvoice set confirmtocntctkey = PrimaryCntctKey
FROM tarinvoice INNER JOIN tarcustomer ON tarinvoice.custkey = tarcustomer.custkey
WHERE confirmtocntctkey is null and tranno like '%115876'
I found a good short method that seems to work well...
Dim x, y As Integer
x = 3: y = 5
ActiveSheet.Cells(y, x).Select
ActiveCell.Value = "Tada"
In this example we are selecting 3 columns over and 5 rows down, then putting "Tada" in the cell.
If you wanna add autoplay function to it. Simply replace
this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
with
this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',
also you can do the same with vimeo
this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
with
this.href = this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1') + '&autoplay=1',
Same as the answer by Dmitry Yudakov, but without an intermediate file, using process substitution:
svn commit --targets <(echo "MyFile1.txt\nMyFile2.txt\n")
If you are to replace a fixed string or some pattern, I would also like to add the bash builtin pattern string replacement variable substitution construct. Instead of describing it myself, I am quoting the section from the bash manual:
${parameter/pattern/string}
The pattern is expanded to produce a pattern just as in pathname expansion. parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with
/
, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with#
, it must match at the beginning of the expanded value of parameter. If pattern begins with%
, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the/
following pattern may be omitted. If parameter is@
or*
, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with@
or*
, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
The problem with your code is in the line:
for(i in length(namevector))
You need to ask yourself: what is length(namevector)
? It's one number. So essentially you're saying:
for(i in 11)
df[,i] <- NA
Or more simply:
df[,11] <- NA
That's why you're getting an error. What you want is:
for(i in namevector)
df[,i] <- NA
Or more simply:
df[,namevector] <- NA
Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.
Copy/Paste Code below:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date
End Sub
Good luck...
This is for version 1.4.4
<div data-role="header" >
<h1>CHANGE HOUSE ANIMATION</h1>
<a href="#" data-rel="back" class="ui-btn-left ui-btn ui-icon-back ui-btn-icon-notext ui-shadow ui-corner-all" data-role="button" role="button">Back</a>
</div>
You can use this for objects:
@Pipe({
name: 'sort',
})
export class SortPipe implements PipeTransform {
transform(array: any[], field: string): any[] {
return array.sort((a, b) => a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0);
}
}
I had the same problem. Solved it by using a javascript library called FileSaver
Just call
saveAs(file, 'filename');
Full http post request:
$http.post('apiUrl', myObject, { responseType: 'arraybuffer' })
.success(function(data) {
var file = new Blob([data], { type: 'application/pdf' });
saveAs(file, 'filename.pdf');
});
Solution with docker-compose:
For accessing to host-based service, you can use network_mode
parameter
https://docs.docker.com/compose/compose-file/#network_mode
version: '3'
services:
jenkins:
network_mode: host
EDIT 2020-04-27: recommended for use only in local development environment.
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
It means that the callback function you passed to this.dataStore.data.find
should return a boolean and have 3 parameters, two of which can be optional:
However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:
this.dataStore.data.find((element, index, obj) => {
// ...
return true; // or false
});
or:
this.dataStore.data.find(element => {
// ...
return true; // or false
});
Reason why it's this way: the function you pass to the find
method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find
method can determine which value to find.
In practice, this means that the predicate is called for each item in data
, and the first item in data
for which your predicate returns true
is the value returned by find
.
words = [w.replace('[br]', '<br />') for w in words]
These are called List Comprehensions.
Define the width as 960px, or whatever you prefer, and you're good to go!
#main {
margin: 0 auto !important;
float: none !important;
text-align: center;
width: 960px;
}
(I couldn't figure this out until I fixed the width, nothing else worked.)
I am going to Necro this topic.
Starting around ms-access-2016, you can execute Data Definition Queries (DDQ) through Macro's
ALTER TABLE <Table> ALTER COLUMN <ID_Field> COUNTER(1,1);
Open Query
actionQuery Name
field; View
and Data Mode
settings are not relevant and can leave the default valuesleft: initial
This will also set left
back to the browser default.
But important to know property: initial
is not supported in IE.
Markdown does not officially support video embeddings but you can embed raw HTML in it. I tested out with GitHub Pages and it works flawlessly.
The snippet looks like:
<iframe width="560" height="315"
src="https://www.youtube.com/embed/MUQfKFzIOeU"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
PS: You can check out the live preview here
I followed the thread and tired all things but didn't work. Finally I saw that my eclipse shortcut target is like below
C:\Eclipse_3.6\eclipse\eclipse.exe -clean -data "C:\workplace" ...
I simply removed -data option and it worked. Now I got popup to choose workspace at startup.
cheers.
Solved the issue by going to File >> Project Structure >> Facets and then adding all the configuration files to Spring Facet. After that it started detecting files in which the beans reside and was able to sort the issue. IntelliJ giving this check is quite valuable and IMHO shouldn't be disabled.
You can specify also imagePullPolicy: Never
in the container's spec:
containers:
- name: nginx
imagePullPolicy: Never
image: custom-nginx
ports:
- containerPort: 80
The accepted answer is fine if you can use lookarounds. However, there is also another approach to solve this problem.
If we look at the widely proposed regex for this question:
.*[^a]$
We will find that it almost works. It does not accept an empty string, which might be a little inconvinient. However, this is a minor issue when dealing with just a one character. However, if we want to exclude whole string, e.g. "abc", then:
.*[^a][^b][^c]$
won't do. It won't accept ac, for example.
There is an easy solution for this problem though. We can simply say:
.{,2}$|.*[^a][^b][^c]$
or more generalized version:
.{,n-1}$|.*[^firstchar][^secondchar]$
where n is length of the string you want forbid (for abc
it's 3), and firstchar
, secondchar
, ... are first, second ... nth characters of your string (for abc
it would be a
, then b
, then c
).
This comes from a simple observation that a string that is shorter than the text we won't forbid can not contain this text by definition. So we can either accept anything that is shorter("ab" isn't "abc"), or anything long enough for us to accept but without the ending.
Here's an example of find that will delete all files that are not .jpg:
find . -regex '.{,3}$|.*[^.][^j][^p][^g]$' -delete
From here:
Root Cause: Maximum connection has been exceeded on your SQL Server Instance.
How to fix it...!
- F8 or Object Explorer
- Right click on Instance --> Click Properties...
- Select "Connections" on "Select a page" area at left
- Chenge the value to 0 (Zero) for "Maximum number of concurrent connections(0 = Unlimited)"
- Restart the SQL Server Instance once.
Apart from that also ensure that below are enabled:
I had the same problem because there was files with windows-1251 encoding and Cyrillic comments. In Android Studio which is based on IntelliJ IDEA you can solve it in two ways:
a) convert file encoding to UTF-8 or
b) set the right file encoding in your build.gradle script:
android {
...
compileOptions.encoding = 'windows-1251' // write your encoding here
...
To convert file encoding use the menu at the bottom right corner of IDE. Select right file encoding first -> press Reload -> select UTF-8 -> press Convert.
Also read this Use the UTF-8, Luke! File Encodings in IntelliJ IDEA
Flushing the output buffers:
printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is
or
fprintf(fd, "Buffered, will be flushed");
fflush(fd); //Prints to a file
Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf()
it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf
something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.
Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf()
, so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.
I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf()
is an expensive operation (which is why it doesn't by default flush the buffer).
As far as flushing the input buffer (stdin
), you should not do that. Flushing stdin
is undefined behavior according to the C11 standard §7.21.5.2 part 2:
If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.
On some systems, Linux being one as you can see in the man page for fflush()
, there's a defined behavior but it's system dependent so your code will not be portable.
Now if you're worried about garbage "stuck" in the input buffer you can use fpurge()
on that.
See here for more on fflush()
and fpurge()
If you want to remove the '!' character from a specific expression("world" in your case), then you can use this regular expression
string input = "Hello! world!";
string output = Regex.Replace(input, "(world)!", "$1", RegexOptions.Multiline | RegexOptions.Singleline);
// result: "Hello! world"
the $1 special character contains all the matching "world" expressions, and it is used to replace the original "world!" expression
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
In my case, the problem was that my POST request was sent to the same url as GET (with get parameters using "?..=..") and that parameters had the same name as form parameters. Probably Spring is merging them into an array and parsing was throwing error.
I can't guarantee that this will work for every new iPad Pro which will be released but this works pretty well as of 2019:
@media only screen and (min-width: 1024px) and (max-height: 1366px)
and (-webkit-min-device-pixel-ratio: 1.5) and (hover: none) {
/* ... */
}
Just move to the new branch. The uncommited changes get carried over.
git checkout -b ABC_1
git commit -m <message>
I also got this error. Though, I did not use boot2docker but just installed "plain" docker on Ubuntu (see https://docs.docker.com/installation/ubuntulinux/).
I got the error ("dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?") because the docker daemon was not running, yet.
On Ubuntu, you need to start the service:
sudo service docker start
See also http://blog.arungupta.me/resolve-dial-unix-docker-sock-error-techtip64
There are two ways to know which rules are overriding:
Search the property in the Filter box at the top of the Styles tab. It will show all the rules containing that property, with the property highlighted in yellow.
Look in the Computed tab to find the same property type, and then expand that to see the source of the various rules that are trying to apply that property.
The named ones are all raster graphics, but beside that don't forget the more and more important vectorgraphics. There are compressed and uncompressed types (in a more or less way), but they're all lossless. Most important are:
Probably not exactly your issue..
Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments
sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /
I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :
Create an Interface :
public interface AsyncResponse {
void processFinish(String output);
}
Then in asynctask
@Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
Then in yout main activity
@Override
public void processFinish(String data) {
// do things
}
.NET Core is an open source and cross platform version of .NET Framework.
Result Set
are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1)
only get you the data in first column of first row. In order to change to next row, you need to call next()
a quick example
while (rs.next()) {
String sid = rs.getString(1);
String lid = rs.getString(2);
// Do whatever you want to do with these 2 values
}
there are many useful method in ResultSet
, you should take a look :)
See this article for a longer discussion of named actions. It also shows that you can use the [HttpGet] attribute instead of prefixing the action name with "get".
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
You could build a Column/Row with Flexible or Expanded children that have flex values that add up to the percentages you want.
You may also find the AspectRatio widget useful.
Try running you asyntask from the UI thread. I faced this issue when I wasn't doing the same!
If you have a lot of custom views in your project you can create class like UIViewFromNib
Swift 2.3
class UIViewFromNib: UIView {
var contentView: UIView!
var nibName: String {
return String(self.dynamicType)
}
//MARK:
override init(frame: CGRect) {
super.init(frame: frame)
loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFromNib()
}
//MARK:
private func loadViewFromNib() {
contentView = NSBundle.mainBundle().loadNibNamed(nibName, owner: self, options: nil)[0] as! UIView
contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
contentView.frame = bounds
addSubview(contentView)
}
}
Swift 3
class UIViewFromNib: UIView {
var contentView: UIView!
var nibName: String {
return String(describing: type(of: self))
}
//MARK:
override init(frame: CGRect) {
super.init(frame: frame)
loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFromNib()
}
//MARK:
func loadViewFromNib() {
contentView = Bundle.main.loadNibNamed(nibName, owner: self, options: nil)?[0] as! UIView
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.frame = bounds
addSubview(contentView)
}
}
And in every class just inherit from UIViewFromNib
, also you can override nibName
property if .xib
file has different name:
class MyCustomClass: UIViewFromNib {
}
I think the correct way to phrase your question is
Is there a way to get the timestamp by specifying the date in UTC?
, because timestamp is just a number which is absolute, not relative. The relative (or timezone aware) piece is the date.
I find pandas very convenient for timestamps, so:
import pandas as pd
dt1 = datetime(2008, 1, 1, 0, 0, 0, 0)
ts1 = pd.Timestamp(dt1, tz='utc').timestamp()
# make sure you get back dt1
datetime.utcfromtimestamp(ts1)
The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject
You have not added the necessary jar file which will be having org.json.JSONObject
class to your classpath
.
You can Download it From Here
Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).
When they return look them up by the remember me token and make sure the UserId matches.
Use:
new Date().toISOString().substring(0, 10);
Try a case statement
WHERE
CASE WHEN @zipCode IS NULL THEN 1
ELSE @zipCode
END
In my case, the host was unkown and instead of typing yes
to the question are you sure you want to continue connecting(yes/no/[fingerprint])?
I was just hitting enter
.
Combining several suggestions I propose the following:
async Task<bool> UpdateDbEntryAsync<T>(T entity, params Expression<Func<T, object>>[] properties) where T : class
{
try
{
var entry = db.Entry(entity);
db.Set<T>().Attach(entity);
foreach (var property in properties)
entry.Property(property).IsModified = true;
await db.SaveChangesAsync();
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("UpdateDbEntryAsync exception: " + ex.Message);
return false;
}
}
called by
UpdateDbEntryAsync(dbc, d => d.Property1);//, d => d.Property2, d => d.Property3, etc. etc.);
Or by
await UpdateDbEntryAsync(dbc, d => d.Property1);
Or by
bool b = UpdateDbEntryAsync(dbc, d => d.Property1).Result;
OK, they all have got some similarities, they do the same things for you in different and similar ways, I divide them in 3 main groups as below:
webpack and browserify as popular ones, work like task runners but with more flexibility, aslo it will bundle everything together as your setting, so you can point to the result as bundle.js for example in one single file including the CSS and Javascript, for more details of each, look at the details below:
webpack
webpack is a module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into a small number of bundles - often only one - to be loaded by the browser.
It is incredibly configurable, but to get started you only need to understand Four Core Concepts: entry, output, loaders, and plugins.
This document is intended to give a high-level overview of these concepts, while providing links to detailed concept specific use-cases.
more here
browserify
Browserify is a development tool that allows us to write node.js-style modules that compile for use in the browser. Just like node, we write our modules in separate files, exporting external methods and properties using the module.exports and exports variables. We can even require other modules using the require function, and if we omit the relative path it’ll resolve to the module in the node_modules directory.
more here
2) Task runners
gulp and grunt are task runners, basically what they do, creating tasks and run them whenever you want, for example you install a plugin to minify your CSS and then run it each time to do minifying, more details about each:
gulp
gulp.js is an open-source JavaScript toolkit by Fractal Innovations and the open source community at GitHub, used as a streaming build system in front-end web development. It is a task runner built on Node.js and Node Package Manager (npm), used for automation of time-consuming and repetitive tasks involved in web development like minification, concatenation, cache busting, unit testing, linting, optimization etc. gulp uses a code-over-configuration approach to define its tasks and relies on its small, single-purposed plugins to carry them out. gulp ecosystem has 1000+ such plugins made available to choose from.
more here
grunt
Grunt is a JavaScript task runner, a tool used to automatically perform frequently used tasks such as minification, compilation, unit testing, linting, etc. It uses a command-line interface to run custom tasks defined in a file (known as a Gruntfile). Grunt was created by Ben Alman and is written in Node.js. It is distributed via npm. Presently, there are more than five thousand plugins available in the Grunt ecosystem.
more here
3) Package managers
package managers, what they do is managing plugins you need in your application and install them for you through github etc using package.json, very handy to update you modules, install them and sharing your app across, more details for each:
npm
npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client, also called npm, and an online database of public packages, called the npm registry. The registry is accessed via the client, and the available packages can be browsed and searched via the npm website.
more here
bower
Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies. To get started, Bower works by fetching and installing packages from all over, taking care of hunting, finding, downloading, and saving the stuff you’re looking for. Bower keeps track of these packages in a manifest file, bower.json.
more here
and the most recent package manager that shouldn't be missed, it's young and fast in real work environment compare to npm which I was mostly using before, for reinstalling modules, it do double checks the node_modules folder to check the existence of the module, also seems installing the modules takes less time:
yarn
Yarn is a package manager for your code. It allows you to use and share code with other developers from around the world. Yarn does this quickly, securely, and reliably so you don’t ever have to worry.
Yarn allows you to use other developers’ solutions to different problems, making it easier for you to develop your software. If you have problems, you can report issues or contribute back, and when the problem is fixed, you can use Yarn to keep it all up to date.
Code is shared through something called a package (sometimes referred to as a module). A package contains all the code being shared as well as a package.json file which describes the package.
more here
just set the width of the td/column you want to be fixed and the rest will expand.
<td width="200"></td>
You can select the form like this:
$("#submit").click(function(){
var form = $(this).parents('form:first');
...
});
However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:
$('form#myform1').submit(function(e){
e.preventDefault(); //Prevent the normal submission action
var form = this;
// ... Handle form submission
});
To select fields inside the form, use the form context. For example:
$("input[name='somename']",form).val();
Be aware to use constant HTTPS or HTTP for all requests. I had the same error msg: "No 'Access-Control-Allow-Origin' header is present on the requested resource."
It sounds like what you really want to do is implement an interface.
Your interface will specify the methods that the object can handle and when you pass an object that implements the interface to a method that wants an object that supports the interface, you just type the argument with the name of the interface.
One of the main differences between surfaceview and view is that to refresh the screen for a normal view we have to call invalidate method from the same thread where the view is defined. But even if we call invalidate, the refreshing does not happen immediately. It occurs only after the next arrival of the VSYNC signal. VSYNC signal is a kernel generated signal which happens every 16.6 ms or this is also known as 60 frame per second. So if we want more control over the refreshing of the screen (for example for very fast moving animation), we should not use normal view class.
On the other hand in case of surfaceview, we can refresh the screen as fast as we want and we can do it from a background thread. So refreshing of the surfaceview really does not depend upon VSYNC, and this is very useful if we want to do high speed animation. I have few training videos and example application which explain all these things nicely. Please have a look at the following training videos.
Check out colorama. It doesn't necessarily help with bolding... but you can do colorized output on both Windows and Linux, and control the brightness:
from colorama import *
init(autoreset=True)
print Fore.RED + 'some red text'
print Style.BRIGHT + Fore.RED + 'some bright red text'
Based on https://developer.android.com/studio/releases/gradle-plugin.html ...
The following table lists which version of Gradle is required for each version of the Android plugin for Gradle. For the best performance, you should use the latest possible version of both Gradle and the Android plugin.
So, the Plugin version with Required Gradle version should be match.
[StringLength(16, ErrorMessageResourceName= "PasswordMustBeBetweenMinAndMaxCharacters", ErrorMessageResourceType = typeof(Resources.Resource), MinimumLength = 6)]
[Display(Name = "Password", ResourceType = typeof(Resources.Resource))]
public string Password { get; set; }
Save resource like this
"ThePasswordMustBeAtLeastCharactersLong" | "The password must be {1} at least {2} characters long"
declare @temp as varchar
set @temp='Measure'
if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
if you want to use report in asp.net then use .rdl if you want to use /view in report builder / report server then use .rdlc just by converting format manually it works
From angular's documentation,
ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit
onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude
The major difference between them is when used with ng-include.
<div ng-include="partialViewUrl" onload="myFunction()"></div>
In this case, myFunction is called everytime the partial view is loaded.
<div ng-include="partialViewUrl" ng-init="myFunction()"></div>
Whereas, in this case, myFunction is called only once when the parent view is loaded.
I don't consider the use of VOLUME good in any case, except if you are creating an image for yourself and no one else is going to use it.
I was impacted negatively due to VOLUME exposed in base images that I extended and only came up to know about the problem after the image was already running, like wordpress that declares the /var/www/html
folder as a VOLUME, and this meant that any files added or changed during the build stage aren't considered, and live changes persist, even if you don't know. There is an ugly workaround to define web directory in another place, but this is just a bad solution to a much simpler one: just remove the VOLUME directive.
You can achieve the intent of volume easily using the -v
option, this not only make it clear what will be the volumes of the container (without having to take a look at the Dockerfile and parent Dockerfiles), but this also gives the consumer the option to use the volume or not.
It's also bad to use VOLUMES due to the following reasons, as said by this answer:
However, the VOLUME instruction does come at a cost.
- Users might not be aware of the unnamed volumes being created, and continuing to take up storage space on their Docker host after containers are removed.
- There is no way to remove a volume declared in a Dockerfile. Downstream images cannot add data to paths where volumes exist.
The latter issue results in problems like these.
Having the option to undeclare a volume would help, but only if you know the volumes defined in the dockerfile that generated the image (and the parent dockerfiles!). Furthermore, a VOLUME could be added in newer versions of a Dockerfile and break things unexpectedly for the consumers of the image.
Another good explanation (about the oracle image having VOLUME, which was removed): https://github.com/oracle/docker-images/issues/640#issuecomment-412647328
More cases in which VOLUME broke stuff for people:
A pull request to add options to reset properties the parent image (including VOLUME), was closed and is being discussed here (and you can see several cases of people affected adversely due to volumes defined in dockerfiles), which has a comment with a good explanation against VOLUME:
Using VOLUME in the Dockerfile is worthless. If a user needs persistence, they will be sure to provide a volume mapping when running the specified container. It was very hard to track down that my issue of not being able to set a directory's ownership (/var/lib/influxdb) was due to the VOLUME declaration in InfluxDB's Dockerfile. Without an UNVOLUME type of option, or getting rid of it altogether, I am unable to change anything related to the specified folder. This is less than ideal, especially when you are security-aware and desire to specify a certain UID the image should be ran as, in order to avoid a random user, with more permissions than necessary, running software on your host.
The only good thing I can see about VOLUME is about documentation, and I would consider it good if it only did that (without any side effects).
TL;DR
I consider that the best use of VOLUME is to be deprecated.
I find that when building long strings, you are usually doing something like building an SQL query, in which case this is best:
query = ' '.join(( # Note double parentheses. join() takes an iterable
"SELECT foo",
"FROM bar",
"WHERE baz",
))
What Levon suggested is good, but it might be vulnerable to mistakes:
query = (
"SELECT foo"
"FROM bar"
"WHERE baz"
)
query == "SELECT fooFROM barWHERE baz" # Probably not what you want
Same thing happened with me, when i have enabled 2-way authentication for github. Things i did to resolve:
Doing this will solve your issue.
string AM_PM = string.Format("{0:hh:mm:ss tt}", DateTime.Now).Split(new char[]{' '})[1];
I think this is what you want http://addyosmani.com/blog/jqueryuicoverflow/
Using interfaces you can get simpler code. No need to create and manually call constructors
Step 1: Declare intefrace with the required fields:
public interface SurveyAnswerStatistics {
String getAnswer();
Long getCnt();
}
Step 2: Select columns with same name as getter in interface and return intefrace from repository method:
public interface SurveyRepository extends CrudRepository<Survey, Long> {
@Query("select v.answer as answer, count(v) as cnt " +
"from Survey v " +
"group by v.answer")
List<SurveyAnswerStatistics> findSurveyCount();
}
C++ expert Alex Allain says it perfectly here (my emphasis added in bold):
...imagine you have the following two function declarations:
void func(int n); void func(char *s); func( NULL ); // guess which function gets called?
Although it looks like the second function will be called--you are, after all, passing in what seems to be a pointer--it's really the first function that will be called! The trouble is that because NULL is 0, and 0 is an integer, the first version of func will be called instead. This is the kind of thing that, yes, doesn't happen all the time, but when it does happen, is extremely frustrating and confusing. If you didn't know the details of what is going on, it might well look like a compiler bug. A language feature that looks like a compiler bug is, well, not something you want.
Enter nullptr. In C++11, nullptr is a new keyword that can (and should!) be used to represent NULL pointers; in other words, wherever you were writing NULL before, you should use nullptr instead. It's no more clear to you, the programmer, (everyone knows what NULL means), but it's more explicit to the compiler, which will no longer see 0s everywhere being used to have special meaning when used as a pointer.
Allain ends his article with:
Regardless of all this--the rule of thumb for C++11 is simply to start using
nullptr
whenever you would have otherwise usedNULL
in the past.
(My words):
Lastly, don't forget that nullptr
is an object--a class. It can be used anywhere NULL
was used before, but if you need its type for some reason, it's type can be extracted with decltype(nullptr)
, or directly described as std::nullptr_t
, which is simply a typedef
of decltype(nullptr)
.
Thanks everyone for the answers. Another quick solution will be to use jQuery.param method with traditional parameter set to true to convert JSON object to string:
$.post("/your/url", $.param(yourJsonObject,true));
You will get last element from an array easily by using below logic
$array = array('a', 'b', 'c', 'd');
echo ($array[count($array)-1]);
Not only last element but you can also get second last, third last and so on by using below logic.
for second last element you have to pass just number 2 in the above statement for example:
echo ($array[count($array)-2]);
I had the same problem. SSMS launches the 32bit version of the import and export wizard which has this issue. Try launching the 64bit version application and it should work fine.