A scenario which I sometimes run into:
Assume you have a trunk, from which you created a release branch. After some changes on trunk (in particular creating "some-dir" directory), you create a feature/fix branch which you want later merge into release branch as well (because changes were small enough and the feature/fix is important for release).
trunk -- ... -- create "some-dir" -- ...
\ \-feature/fix branch
\- release branch
If you then try to merge the feature/fix branch directly into the release branch you will get a tree conflict (even though the directory did not even exist in feature/fix branch):
svn status
! C some-dir
> local missing or deleted or moved away, incoming file edit upon merge
So you need to explicitly merge the commits which were done on trunk before creating feature/fix branch which created the "some-dir" directory before merging the feature/fix branch.
I often forget that as that is not necessary in git.
Basically, tree conflicts arise if there is some restructure in the folder structure on the branch.
You need to delete the conflict folder and use svn clean
once.
Hope this solves your conflict.
What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full
svn resolve --accept base
An alternate is to use a new helper function which will take values from List and update in the DataGridView as following:
private void DisplayStringListInDataGrid(List<string> passedList, ref DataGridView gridToUpdate, string newColumnHeader)
{
DataTable gridData = new DataTable();
gridData.Columns.Add(newColumnHeader);
foreach (string listItem in passedList)
{
gridData.Rows.Add(listItem);
}
BindingSource gridDataBinder = new BindingSource();
gridDataBinder.DataSource = gridData;
dgDataBeingProcessed.DataSource = gridDataBinder;
}
Then we can call this function the following way:
DisplayStringListInDataGrid(<nameOfListWithStrings>, ref <nameOfDataGridViewToDisplay>, <nameToBeGivenForTheNewColumn>);
Try this:
Dim xrndom As Random
Dim x As Integer
xrndom = New Random
Dim yrndom As Random
Dim y As Integer
yrndom = New Random
'chart creation
Chart1.Series.Add("a")
Chart1.Series("a").ChartType = DataVisualization.Charting.SeriesChartType.Point
Chart1.Series("a").MarkerSize = 10
Chart1.Series.Add("b")
Chart1.Series("b").ChartType = DataVisualization.Charting.SeriesChartType.Point
Chart1.Series("b").MarkerSize = 10
Chart1.Series.Add("c")
Chart1.Series("c").ChartType = DataVisualization.Charting.SeriesChartType.Point
Chart1.Series("c").MarkerSize = 10
Chart1.Series.Add("d")
Chart1.Series("d").ChartType = DataVisualization.Charting.SeriesChartType.Point
Chart1.Series("d").MarkerSize = 10
'color
Chart1.Series("a").Color = Color.Red
Chart1.Series("b").Color = Color.Orange
Chart1.Series("c").Color = Color.Black
Chart1.Series("d").Color = Color.Green
Chart1.Series("Chart 1").Color = Color.Blue
For j = 0 To 70
x = xrndom.Next(0, 70)
y = xrndom.Next(0, 70)
'Conditions
If j < 10 Then
Chart1.Series("a").Points.AddXY(x, y)
ElseIf j < 30 Then
Chart1.Series("b").Points.AddXY(x, y)
ElseIf j < 50 Then
Chart1.Series("c").Points.AddXY(x, y)
ElseIf 50 < j Then
Chart1.Series("d").Points.AddXY(x, y)
Else
Chart1.Series("Chart 1").Points.AddXY(x, y)
End If
Next
I don't really understand the full scope of your question, but if all you need is a hash of the string, then it's very easy to get that.
Just use the GetHashCode method.
Like this:
string hash = username.GetHashCode();
In my case it was very weird (use a storyboard): For some reason it changed from "Main storyboard file base name" to "Main nib file base name" in the plist.
Changing back to "Main storyboard file base name" (UIMainStoryboardFile) solved the issue
The following code snippet disables it for all textarea
and input[type=text]
elements:
(function () {
function disableSpellCheck() {
let selector = 'input[type=text], textarea';
let textFields = document.querySelectorAll(selector);
textFields.forEach(
function (field, _currentIndex, _listObj) {
field.spellcheck = false;
}
);
}
disableSpellCheck();
})();
shopt -s dotglob
git clone ssh://[email protected]/home/user/private/repos/project_hub.git tmp && mv tmp/* . && rm -rf tmp
Let's say you have a typical variadic function you've written. Because at least one argument is required before the variadic one ...
, you have to always write an extra argument in usage.
Or do you?
If you wrap your variadic function in a macro, you need no preceding arg. Consider this example:
#define LOGI(...)
((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
This is obviously far more convenient, since you needn't specify the initial argument every time.
Or you can use the Central Maven Repository with the Servlet 3.0 API which is also provided for the Tomcat Server 7.0.X
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>7.0.21</version>
<scope>provided</scope>
</dependency>
from here: http://repo2.maven.org/maven2/org/apache/tomcat/tomcat-servlet-api/7.0.21/
Simply put:
#include <climits>
template <typename T>
T swap_endian(T u)
{
static_assert (CHAR_BIT == 8, "CHAR_BIT != 8");
union
{
T u;
unsigned char u8[sizeof(T)];
} source, dest;
source.u = u;
for (size_t k = 0; k < sizeof(T); k++)
dest.u8[k] = source.u8[sizeof(T) - k - 1];
return dest.u;
}
usage: swap_endian<uint32_t>(42)
.
if you cannot access data folder on Android Device Monitor
cmd
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools
(Where you located sdk folder)
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>adb shell
generic_x86:/ $
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>adb kill-server
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>adb start-server
* daemon not running. starting it now at tcp:5037 *
* daemon started successfully *
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>adb root
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>
working fine.....
You can set a default option for the column in the migration
....
add_column :status, :string, :default => "P"
....
OR
You can use a callback, before_save
class Task < ActiveRecord::Base
before_save :default_values
def default_values
self.status ||= 'P' # note self.status = 'P' if self.status.nil? might be safer (per @frontendbeauty)
end
end
Improve to @RichX answer:
lastRow
can be both [tableView numberOfRowsInSection: 0] - 1
or ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row
.
So the code will be:
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
//end of loading
//for example [activityIndicator stopAnimating];
}
}
UPDATE:
Well, @htafoya's comment is right. If you want this code to detect end of loading all data from source, it wouldn't, but that's not the original question. This code is for detecting when all cells that are meant to be visible are displayed. willDisplayCell:
used here for smoother UI (single cell usually displays fast after willDisplay:
call). You could also try it with tableView:didEndDisplayingCell:
.
If you're using Storyboard, you can follow this step:
- Add a view controller (V2), setup the UI the way you want it
Present V2 Modally
Click the segue. In the Attributes inspector, Set Presentation as Over Full Screen. Remove animation if you like
- Select V2. In the Attributes inspector, Set Presentation as Over Full Screen. Check Defines Context and Provides Context
- Select the MainView of your V2 (Pls. Check image). Set backgroundColor to Clear Color
You could also disable the cascade delete convention in global scope of your application by doing this:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()
If you desire to use Python 3, you can use the following:
import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
result = json.loads(response.readall().decode('utf-8'))
To Windows users:
You can easily "debug" this error by calling the apache httpd-service directly.
XAMPP\apache\bin
httpd.exe
It is usually something within one of the many *.conf-files in the XAMPP\apache\conf\extra
folders.
from http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
package
: take the compiled code and package it in its distributable format, such as a JAR.
install
: install the package into the local repository, for use as a dependency in other projects locally
So the answer to your question is, it depends on whether you want it in installed into your local repo. Install will also run package because it's higher up in the goal phase stack.
You need to give a relative file path of <a href="../index.html">Home</a>
Alternately you can specify a link from the root of your site with
<a href="/pages/en/index.html">Home</a>
..
and .
have special meanings in file paths, ..
means up one directory and .
means current directory.
so <a href="index.html">Home</a>
is the same as <a href="./index.html">Home</a>
Don't forget that an input field must be visible first, thereafter you're able to focus it.
$("#elementid").show();
$("#elementid input[type=text]").focus();
you can define it with using global or GLOBAL, nodejs supports both.
for e.g
global.underscore = require("underscore");
or
GLOBAL.underscore = require("underscore");
I use a trigger as a workaround to set a datetime field to NOW() for new inserts:
CREATE TRIGGER `triggername` BEFORE INSERT ON `tablename`
FOR EACH ROW
SET NEW.datetimefield = NOW()
it should work for updates too
Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.
You dont have to compile it. the first you use it (import) it is compiled by the CPython interpreter. But if you really want to compile there are several options.
To compile to exe
Or 2 compile just a specific *.py file, you can just use
import py_compile
py_compile.compile("yourpythoncode.py")
This is a bit late for those coming in, but check your proguard rules! I wasted a lot of time on this. Your proguard rules could be changing the names to important firebase files. This really only proves a problem in production and instant run :)
proguard-rules.pro
-keep class com.google.firebase.** { *; }
-keep class com.firebase.** { *; }
-keep class org.apache.** { *; }
-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }
-dontwarn org.apache.**
-dontwarn org.w3c.dom.**
I find that image mapping works pretty well. If you have any headers or footers that are images make sure that you apply a bgcolor="fill in the blank" because outlook in most cases wont load the image and you will be left with a transparent header. If you at least designate a color that works with the over all feel of the email it will be less of a shock for the user. Never try and use any styling sheets. Or CSS at all! Just avoid it.
Depending if you're copying content from a word or shared google Doc be sure to (command+F) Find all the (') and (") and replace them within your editing software (especially dreemweaver) because they will show up as code and it's just not good.
ALT is your best friend. use the ALT tag to add in text to all your images. Because odds are they are not going to load right. And that ALT text is what gets people to click the (see images) button. Also define your images Width, Height and make the boarder 0 so you dont get weird lines around your image.
Consider editing all images within Photoshop with a 15px boarder on each side (make background transparent and save as a PNG 24) of image. Sometimes the email clients do not read any padding styles that you apply to the images so it avoids any weird formatting!
Also i found the line under links particularly annoying so if you apply < style="text-decoration:none; color:#whatever color you want here!" > it will remove the line and give you the desired look.
There is alot that can really mess with the over all look and feel.
You can just use either of the following approaches:
.center-block {
margin: auto;
display: block;
}
_x000D_
<div>
<input class="center-block">
</div>
_x000D_
.parent {
display: grid;
place-items: center;
}
_x000D_
<div class="parent">
<input>
</div>
_x000D_
Your session is lost becoz....
I have found a scenario where session is lost - In a asp.net page, for a amount text box field has invalid characters, and followed by a session variable retrieval for other purpose.After posting the invalid number parsing through Convert.ToInt32 or double raises a first chance exception, but error does not show at that line, Instead of that, Session being null because of unhandled exception, shows error at session retrieval, thus deceiving the debugging...
HINT: Test your system to fail it- DESTRUCTIVE.. enter enough junk in unrelated scenarios for ex: after search results shown enter junk in search criteria and goto details of search result... , you would be able to reproduce this machine on your local code base too...:)
Hope it Helps, hydtechie
Try this code:
Bitmap bitmap = null;
File f = new File(_path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
it doesn't matter that you declare your minSdk in build.gradle. You have to copy overrideLibrary
in your AndroidManifest.xml
, as documented here.
<manifest
... >
<uses-sdk tools:overrideLibrary="com.example.lib1, com.example.lib2"/>
...
</manifest>
The system automatically ignores the sdkVersion declared in AndroidManifest.xml.
I hope this solve your problem.
A dirty fix: Add $(VC_IncludePath);$(WindowsSDK_IncludePath); into project Properties / C/C++ / General / Additional include directories
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
the next answer is for those who have a multi-level menu:
var url = window.location.href;
var els = document.querySelectorAll(".dropdown-menu a");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
if (el.href === url) {
el.classList.add("active");
var parent = el.closest(".main-nav"); // add this class for the top level "li" to get easy the parent
parent.classList.add("active");
}
}
To switch to Automatic:
Application.Calculation = xlCalculationAutomatic
To switch to Manual:
Application.Calculation = xlCalculationManual
If you use JQuery, you can use:
$("meta[property='video']").attr('content');
Just like you do for getting something from the CNode
you also need to do for the ANode
XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
XmlNode anode = xn.SelectSingleNode("ANode");
if (anode!= null)
{
string id = anode["ID"].InnerText;
string date = anode["Date"].InnerText;
XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
foreach (XmlNode node in CNodes)
{
XmlNode example = node.SelectSingleNode("Example");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
}
}
I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.
Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).
>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2010-08-04T09:33:09.890000+10:00'
>>>
Why not do it simply by picking eight different numbers from 0
to Horse.count
and use that to get your horses?
offsets = (0...Horse.count).to_a.sample(8)
@suggested_horses = offsets.map{|i| Horse.first(:offset => i) }
This has the added advantage that it won't cause an infinite loop if you happen to have less than 8 horses in your database.
Note: Array#sample
is new to 1.9 (and coming in 1.8.8), so either upgrade your Ruby, require 'backports'
or use something like shuffle.first(n)
.
The below works for me
dataframe[,"newName"] <- NA
Make sure to add ""
for new name string.
I found this line worked best for one of my Windows Server 2008 R2 servers. A couple of others had no issues without this line in my PowerShell scripts:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force -Scope Process
My understanding is you don't need to install Anaconda again to start using a different version of python. Instead, conda has the ability to separately manage python 2 and 3 environments.
the type just tells you what the bit pattern is supposed to represent. the bits are only what you make of them. the same sequences can be interpreted in different ways.
// Using LINQ and just referencing p.Employer will lazy load
// I am not at a computer but I know I have lazy loaded in one
// query with a single query call like below.
List<Person> persons = new List<Person>();
using(MyDbContext dbContext = new MyDbContext())
{
persons = (
from p in dbcontext.Persons
select new Person{
Name = p.Name,
Email = p.Email,
Employer = p.Employer
}).ToList();
}
let storyboard = UIStoryboard(name: "StoryboardFileName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "StoryboardID")
self.present(controller, animated: true, completion: nil)
Note:
"StoryboardFileName"
is the filename of the Storyboard and not the ID of the storyboard!"StoryboardID"
is the ID you have manually set in the identity inspector for that storyboard (see screenshot below). Sometimes people believe that the first one is the Storyboard ID and the second one the View Controller class name, so note the difference.
There are some predefined formats in date_d.php
to use with format
like:
define ('DATE_ATOM', "Y-m-d\TH:i:sP");
define ('DATE_COOKIE', "l, d-M-y H:i:s T");
define ('DATE_ISO8601', "Y-m-d\TH:i:sO");
define ('DATE_RFC822', "D, d M y H:i:s O");
define ('DATE_RFC850', "l, d-M-y H:i:s T");
define ('DATE_RFC1036', "D, d M y H:i:s O");
define ('DATE_RFC1123', "D, d M Y H:i:s O");
define ('DATE_RFC2822', "D, d M Y H:i:s O");
define ('DATE_RFC3339', "Y-m-d\TH:i:sP");
define ('DATE_RSS', "D, d M Y H:i:s O");
define ('DATE_W3C', "Y-m-d\TH:i:sP");
Use like this:
$date = new \DateTime();
$string = $date->format(DATE_RFC2822);
You can use a DOMParser
, like so:
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";_x000D_
var doc = new DOMParser().parseFromString(xmlString, "text/xml");_x000D_
console.log(doc.firstChild.innerHTML); // => <a href="#">Link..._x000D_
console.log(doc.firstChild.firstChild.innerHTML); // => Link
_x000D_
This can be done for a normal subview
inside a larger UIView
, but it doesn't work automatically for headerViews
. The height of a headerView
is determined by what's returned by tableView:heightForHeaderInSection:
so you have to calculate the height
based on the height
of the UILabel
plus space for the UIButton
and any padding
you need. You need to do something like this:
-(CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
NSString *s = self.headeString[indexPath.section];
CGSize size = [s sizeWithFont:[UIFont systemFontOfSize:17]
constrainedToSize:CGSizeMake(281, CGFLOAT_MAX)
lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 60;
}
Here headerString
is whatever string you want to populate the UILabel
, and the 281 number is the width
of the UILabel
(as setup in Interface Builder
)
What you’re looking for is the CSS Sticky Footer.
* {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
#wrap {_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
#main {_x000D_
overflow: auto;_x000D_
padding-bottom: 180px;_x000D_
/* must be same height as the footer */_x000D_
}_x000D_
_x000D_
#footer {_x000D_
position: relative;_x000D_
margin-top: -180px;_x000D_
/* negative value of footer height */_x000D_
height: 180px;_x000D_
clear: both;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Opera Fix thanks to Maleika (Kohoutec) */_x000D_
_x000D_
body:before {_x000D_
content: "";_x000D_
height: 100%;_x000D_
float: left;_x000D_
width: 0;_x000D_
margin-top: -32767px;_x000D_
/* thank you Erik J - negate effect of float*/_x000D_
}
_x000D_
<div id="wrap">_x000D_
<div id="main"></div>_x000D_
</div>_x000D_
_x000D_
<div id="footer"></div>
_x000D_
instead of using try-except blocks, you could use, if else
this will not execute if the file is non-existent, open(name,'r+')
if os.path.exists('location\filename.txt'):
print "File exists"
else:
open("location\filename.txt", 'w')
'w' creates a file if its non-exis
On linux you can check epiphany-browser, resizes the windows you'll get same bugs as in ios. Both browsers uses Webkit.
Ubuntu/Mint:
sudo apt install epiphany-browser
There are helper classes in bootstrap 3 with contextual colors please use these classes in html attributes.
<p class="text-muted">...</p>
<p class="text-primary">...</p>
<p class="text-success">...</p>
<p class="text-info">...</p>
<p class="text-warning">...</p>
<p class="text-danger">...</p>
Reference: http://getbootstrap.com/css/#type
Another way of doing this, using only JavaScript, would be this:
window.addEventListener('resize', functionName);
This fires every time the size changes, like the other answer.
functionName
is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).
Here's a start.. Open to suggestions/improvements.
Server
public class ChatHub : Hub
{
public void SendChatMessage(string who, string message)
{
string name = Context.User.Identity.Name;
Clients.Group(name).addChatMessage(name, message);
Clients.Group("[email protected]").addChatMessage(name, message);
}
public override Task OnConnected()
{
string name = Context.User.Identity.Name;
Groups.Add(Context.ConnectionId, name);
return base.OnConnected();
}
}
JavaScript
(Notice how addChatMessage
and sendChatMessage
are also methods in the server code above)
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.addChatMessage = function (who, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(who).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#chat').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
Testing
The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html
The method DocumentBuilder.parse(String)
takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream
or Reader
, for example a StringReader
. ... Welcome to the Java standard levels of indirections !
Basically :
DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));
Note that if you read your XML from a file, you can directly give the File
object to DocumentBuilder.parse()
.
As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !
For an uglier version of unshift
use splice
:
TheArray.splice(0, 0, TheNewObject);
Just add to your command line the parameter -config c:\your_openssl_path\openssl.cfg
, changing your_openssl_path
to the real installed path.
As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap
is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:
private _entityId: number;
constructor(private _route: ActivatedRoute) {
// ...
}
ngOnInit() {
// For a static snapshot of the route...
this._entityId = this._route.snapshot.paramMap.get('id');
// For subscribing to the observable paramMap...
this._route.paramMap.pipe(
switchMap((params: ParamMap) => this._entityId = params.get('id'))
);
// Or as an alternative, with slightly different execution...
this._route.paramMap.subscribe((params: ParamMap) => {
this._entityId = params.get('id');
});
}
I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.
This does what you want, and will work in nearly all cases:
>>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])
True
The expression 'a','b' in ['b', 'a', 'foo', 'bar']
doesn't work as expected because Python interprets it as a tuple:
>>> 'a', 'b'
('a', 'b')
>>> 'a', 5 + 2
('a', 7)
>>> 'a', 'x' in 'xerxes'
('a', True)
There are other ways to execute this test, but they won't work for as many different kinds of inputs. As Kabie points out, you can solve this problem using sets...
>>> set(['a', 'b']).issubset(set(['a', 'b', 'foo', 'bar']))
True
>>> {'a', 'b'} <= {'a', 'b', 'foo', 'bar'}
True
...sometimes:
>>> {'a', ['b']} <= {'a', ['b'], 'foo', 'bar'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Sets can only be created with hashable elements. But the generator expression all(x in container for x in items)
can handle almost any container type. The only requirement is that container
be re-iterable (i.e. not a generator). items
can be any iterable at all.
>>> container = [['b'], 'a', 'foo', 'bar']
>>> items = (i for i in ('a', ['b']))
>>> all(x in [['b'], 'a', 'foo', 'bar'] for x in items)
True
In many cases, the subset test will be faster than all
, but the difference isn't shocking -- except when the question is irrelevant because sets aren't an option. Converting lists to sets just for the purpose of a test like this won't always be worth the trouble. And converting generators to sets can sometimes be incredibly wasteful, slowing programs down by many orders of magnitude.
Here are a few benchmarks for illustration. The biggest difference comes when both container
and items
are relatively small. In that case, the subset approach is about an order of magnitude faster:
>>> smallset = set(range(10))
>>> smallsubset = set(range(5))
>>> %timeit smallset >= smallsubset
110 ns ± 0.702 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> %timeit all(x in smallset for x in smallsubset)
951 ns ± 11.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
This looks like a big difference. But as long as container
is a set, all
is still perfectly usable at vastly larger scales:
>>> bigset = set(range(100000))
>>> bigsubset = set(range(50000))
>>> %timeit bigset >= bigsubset
1.14 ms ± 13.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit all(x in bigset for x in bigsubset)
5.96 ms ± 37 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Using subset testing is still faster, but only by about 5x at this scale. The speed boost is due to Python's fast c
-backed implementation of set
, but the fundamental algorithm is the same in both cases.
If your items
are already stored in a list for other reasons, then you'll have to convert them to a set before using the subset test approach. Then the speedup drops to about 2.5x:
>>> %timeit bigset >= set(bigsubseq)
2.1 ms ± 49.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
And if your container
is a sequence, and needs to be converted first, then the speedup is even smaller:
>>> %timeit set(bigseq) >= set(bigsubseq)
4.36 ms ± 31.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
The only time we get disastrously slow results is when we leave container
as a sequence:
>>> %timeit all(x in bigseq for x in bigsubseq)
184 ms ± 994 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
And of course, we'll only do that if we must. If all the items in bigseq
are hashable, then we'll do this instead:
>>> %timeit bigset = set(bigseq); all(x in bigset for x in bigsubseq)
7.24 ms ± 78 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
That's just 1.66x faster than the alternative (set(bigseq) >= set(bigsubseq)
, timed above at 4.36).
So subset testing is generally faster, but not by an incredible margin. On the other hand, let's look at when all
is faster. What if items
is ten-million values long, and is likely to have values that aren't in container
?
>>> %timeit hugeiter = (x * 10 for bss in [bigsubseq] * 2000 for x in bss); set(bigset) >= set(hugeiter)
13.1 s ± 167 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
>>> %timeit hugeiter = (x * 10 for bss in [bigsubseq] * 2000 for x in bss); all(x in bigset for x in hugeiter)
2.33 ms ± 65.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Converting the generator into a set turns out to be incredibly wasteful in this case. The set
constructor has to consume the entire generator. But the short-circuiting behavior of all
ensures that only a small portion of the generator needs to be consumed, so it's faster than a subset test by four orders of magnitude.
This is an extreme example, admittedly. But as it shows, you can't assume that one approach or the other will be faster in all cases.
Most of the time, converting container
to a set is worth it, at least if all its elements are hashable. That's because in
for sets is O(1), while in
for sequences is O(n).
On the other hand, using subset testing is probably only worth it sometimes. Definitely do it if your test items are already stored in a set. Otherwise, all
is only a little slower, and doesn't require any additional storage. It can also be used with large generators of items, and sometimes provides a massive speedup in that case.
Right click on eclipse icon and click on open file location then delete the eclipse folder from drive(Save backup of your eclipse workspace if you want). Also delete eclipse icon. Thats it..
In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch
where we accepted json in the following format:
[
{
path: '/docs',
method: 'post',
body: {
doc_number: 1,
binder: 1
}
},
{
path: '/docs',
method: 'post',
body: {
doc_number: 5,
binder: 8
}
},
{
path: '/docs',
method: 'post',
body: {
doc_number: 6,
binder: 3
}
},
]
The response have the status code 207 (Multi-Status) and looks like this:
[
{
path: '/docs',
method: 'post',
body: {
doc_number: 1,
binder: 1
}
status: 200
},
{
path: '/docs',
method: 'post',
body: {
error: {
msg: 'A document with doc_number 5 already exists'
...
}
},
status: 409
},
{
path: '/docs',
method: 'post',
body: {
doc_number: 6,
binder: 3
},
status: 200
},
]
You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.
Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests
When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:
In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.
http://restcookbook.com/HTTP%20Methods/put-vs-post/
As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.
Another system (not mentioned in the accepted answer yet) is PyInstaller, which worked for a PyQt project of mine when py2exe would not. I found it easier to use.
Pyinstaller is based on Gordon McMillan's Python Installer. Which is no longer available.
$(function(){
$("#my-div").toggle();
$("#my-div").click(function(){$("#my-div").toggle()})
})
// you don't even have to set the #my-div
.hide
nor !important
, just paste/repeat the toggle in the event function.
You can use a Web Method and Ajax:
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
I am late for the answer but I think this is another solution which is not mentioned here so posting.
Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.
filter.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="@+id/action_filter"
android:title="@string/filter"
android:orderInCategory="10"
android:icon="@drawable/filter"
app:showAsAction="ifRoom" />
</menu>
Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Step 3: Now add the method onCreateOptionsMenu which will be override as:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.filter, menu); // Use filter.xml from step 1
}
Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_filter){
//Do whatever you want to do
return true;
}
return super.onOptionsItemSelected(item);
}
function String2Stars($string='',$first=0,$last=0,$rep='*'){
$begin = substr($string,0,$first);
$middle = str_repeat($rep,strlen(substr($string,$first,$last)));
$end = substr($string,$last);
$stars = $begin.$middle.$end;
return $stars;
}
example
$string = 'abcdefghijklmnopqrstuvwxyz';
echo String2Stars($string,5,-5); // abcde****************vwxyz
Who "they"? I don't think there's a visible
attribute in html
.
Here's how I would do it.
I think it's about as efficient as it reasonably can be. It optimizes the single character case and avoids creating multiple substrings for each subsequence removed.
Note that the corner case of passing an empty string to trim is handled (some of the other answers would go into an infinite loop).
/** Trim all occurrences of the string <code>rmvval</code> from the left and right of <code>src</code>. Note that <code>rmvval</code> constitutes an entire string which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String rmvval) {
return trim(src,rmvval,rmvval,true);
}
/** Trim all occurrences of the string <code>lftval</code> from the left and <code>rgtval</code> from the right of <code>src</code>. Note that the values to remove constitute strings which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String lftval, String rgtval, boolean igncas) {
int str=0,end=src.length();
if(lftval.length()==1) { // optimize for common use - trimming a single character from left
char chr=lftval.charAt(0);
while(str<end && src.charAt(str)==chr) { str++; }
}
else if(lftval.length()>1) { // handle repeated removal of a specific character sequence from left
int vallen=lftval.length(),newstr;
while((newstr=(str+vallen))<=end && src.regionMatches(igncas,str,lftval,0,vallen)) { str=newstr; }
}
if(rgtval.length()==1) { // optimize for common use - trimming a single character from right
char chr=rgtval.charAt(0);
while(str<end && src.charAt(end-1)==chr) { end--; }
}
else if(rgtval.length()>1) { // handle repeated removal of a specific character sequence from right
int vallen=rgtval.length(),newend;
while(str<=(newend=(end-vallen)) && src.regionMatches(igncas,newend,rgtval,0,vallen)) { end=newend; }
}
if(str!=0 || end!=src.length()) {
if(str<end) { src=src.substring(str,end); } // str is inclusive, end is exclusive
else { src=""; }
}
return src;
}
There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).
You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:
Company: Vodafone
------------------
LSE symbol: VOD
in Google: LON:VOD
in Yahoo: VOD.L
NASDAQ symbol: VOD
in Google: NASDAQ:VOD
in Yahoo: VOD
Copying and pasting from the MS-DOS tree
command might also work for you. Examples:
tree
C:\Foobar>tree
C:.
+---FooScripts
+---barconfig
+---Baz
¦ +---BadBaz
¦ +---Drop
...
tree /F
C:\Foobar>tree
C:.
+---FooScripts
¦ foo.sh
+---barconfig
¦ bar.xml
+---Baz
¦ +---BadBaz
¦ ¦ badbaz.xml
¦ +---Drop
...
tree /A
C:\Foobar>tree /A
C:.
+---FooScripts
+---barconfig
+---Baz
¦ +---BadBaz
¦ \---Drop
...
tree /F /A
C:\Foobar>tree /A
C:.
+---FooScripts
¦ foo.sh
+---barconfig
¦ bar.xml
+---Baz
¦ +---BadBaz
¦ ¦ badbaz.xml
¦ \---Drop
...
tree
[drive:
][path
] [/F
] [/A
]
drive:\path
— Drive and directory containing disk for display of directory structure, without listing files.
/F
— Include all files living in every directory.
/A
— Replace graphic characters used for linking lines with ext characters , instead of graphic characters./a
is used with code pages that do not support graphic characters and to send output to printers that do not properly interpret graphic characters.
The following is equivalent to your second code block:
var f = function () {
//Some logic here...
};
var fr = f;
fr(pars);
If you want to actually pass a reference to a function to some other function, you can do something like this:
function fiz(x, y, z) {
return x + y + z;
}
// elsewhere...
function foo(fn, p, q, r) {
return function () {
return fn(p, q, r);
}
}
// finally...
f = foo(fiz, 1, 2, 3);
f(); // returns 6
You're almost certainly better off using a framework for this sort of thing, though.
Using GROUP BY CUBE
:
SELECT ROWNUM
FROM (SELECT 1 AS c FROM dual GROUP BY CUBE(1,1,1,1,1,1,1) ) sub
WHERE ROWNUM <=100;
Instead of '2013-04-12' whose meaning depends on the local culture, use '20130412' which is recognized as the culture invariant format.
If you want to compare with December 4th, you should write '20131204'. If you want to compare with April 12th, you should write '20130412'.
The article Write International Transact-SQL Statements from SQL Server's documentation explains how to write statements that are culture invariant:
Applications that use other APIs, or Transact-SQL scripts, stored procedures, and triggers, should use the unseparated numeric strings. For example, yyyymmdd as 19980924.
EDIT
Since you are using ADO, the best option is to parameterize the query and pass the date value as a date parameter. This way you avoid the format issue entirely and gain the performance benefits of parameterized queries as well.
UPDATE
To use the the the ISO 8601 format in a literal, all elements must be specified. To quote from the ISO 8601 section of datetime's documentation
To use the ISO 8601 format, you must specify each element in the format. This also includes the T, the colons (:), and the period (.) that are shown in the format.
... the fraction of second component is optional. The time component is specified in the 24-hour format.
npm i lodash
let non_duplicated_data = _.uniqBy(pendingDeposits, v => [v.stellarAccount, v.externalTransactionId].join());
One solution is to wrap it in a subquery
SELECT *
FROM
(
SELECT COUNT(column1),column1 FROM table GROUP BY column1
UNION ALL
SELECT COUNT(column2),column2 FROM table GROUP BY column2
UNION ALL
SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s
for me the following commands worked:
$ brew install mysql
$ brew services start mysql
If you're after readable fail messages, you can do without hamcrest by using the usual assertEquals with an empty list:
assertEquals(new ArrayList<>(0), yourList);
E.g. if you run
assertEquals(new ArrayList<>(0), Arrays.asList("foo", "bar");
you get
java.lang.AssertionError
Expected :[]
Actual :[foo, bar]
-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER
Here we just use a Socket Attaching Connector, which is enabled by default when the dt_socket transport is configured and the VM is running in the server debugging mode.
For more details u can refer to : https://stackify.com/java-remote-debugging/
TAXI ANALOGY
Intent
Intents are typically used for starting Services. For example:
Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
startService(intent);
This is like when you call for a taxi:
Myself = CurrentClass
Taxi Driver = ServiceClass
Pending Intent
You will need to use something like this:
Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
PendingIntent pi = PendingIntent.getService(parameter, parameter, intent, parameter);
getDataFromThirdParty(parameter, parameter, pi, parameter);
Now this Third party will start the service acting on your behalf. A real life analogy is Uber or Lyft who are both taxi companies.
You send a request for a ride to Uber/Lyft. They will then go ahead and call one of their drivers on your behalf.
Therefore:
Uber/Lyft ------ ThirdParty which receives PendingIntent
Myself --------- Class calling PendingIntent
Taxi Driver ---- ServiceClass
Another way to restore the menu bar is to trigger the View: Toggle Menu Bar
command in the command palette (F1).
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
Using COALESCE to Build Comma-Delimited String in SQL Server
http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string
Example:
DECLARE @EmployeeList varchar(100)
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
SELECT @EmployeeList
The ssh daemon (sshd), which runs server-side, closes the connection from the server-side if the client goes silent (i.e., does not send information). To prevent connection loss, instruct the ssh client to send a sign-of-life signal to the server once in a while.
The configuration for this is in the file $HOME/.ssh/config
, create the file if it does not exist (the config file must not be world-readable, so run chmod 600 ~/.ssh/config
after creating the file). To send the signal every e.g. four minutes (240 seconds) to the remote host, put the following in that configuration file:
Host remotehost
HostName remotehost.com
ServerAliveInterval 240
To enable sending a keep-alive signal for all hosts, place the following contents in the configuration file:
Host *
ServerAliveInterval 240
My favorite is this one-liner:
git log --oneline $( git fsck --no-reflogs | awk '/dangling commit/ {print $3}' )
This is basically the same idea as this answer but much shorter. Of course, you can still add --graph
to get a tree-like display.
When you have found the commit in the list, apply with
git stash apply THE_COMMIT_HASH_FOUND
For me, using --no-reflogs
did reveal the lost stash entry, but --unreachable
(as found in many other answers) did not.
Run it on git bash when you are under Windows.
Credits: The details of the above commands are taken from https://gist.github.com/joseluisq/7f0f1402f05c45bac10814a9e38f81bf
I tried to call
startService(oIntent);
bindService(oIntent, mConnection, Context.BIND_AUTO_CREATE);
consequently and I could create a sticky service and bind to it. Detailed tutorial for Bound Service Example.
In SQL Server Management Studio of Any Version, Use
BIT
as Data Type
which will provide you with True
or False
Value options. in case you want to use Only 1
or 0
then you can use this method:
CREATE TABLE SampleBit(
bar int NOT NULL CONSTRAINT CK_foo_bar CHECK (bar IN (-1, 0, 1))
)
But I will strictly advise BIT
as The BEST Option. Hope fully it's help someone.
You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest
.
The main difference is that
substr() allows you to specify the maximum length to return
substring() allows you to specify the indices and the second argument is NOT inclusive
There are some additional subtleties between substr() and substring() such as the handling of equal arguments and negative arguments. Also note substring() and slice() are similar but not always the same.
//*** length vs indices:
"string".substring(2,4); // "ri" (start, end) indices / second value is NOT inclusive
"string".substr(2,4); // "ring" (start, length) length is the maximum length to return
"string".slice(2,4); // "ri" (start, end) indices / second value is NOT inclusive
//*** watch out for substring swap:
"string".substring(3,2); // "r" (swaps the larger and the smaller number)
"string".substr(3,2); // "in"
"string".slice(3,2); // "" (just returns "")
//*** negative second argument:
"string".substring(2,-4); // "st" (converts negative numbers to 0, then swaps first and second position)
"string".substr(2,-4); // ""
"string".slice(2,-4); // ""
//*** negative first argument:
"string".substring(-3); // "string"
"string".substr(-3); // "ing" (read from end of string)
"string".slice(-3); // "ing"
Please note that android:windowSoftInputMode="adjustResize"
does not work when WindowManager.LayoutParams.FLAG_FULLSCREEN
is set for an activity. You've got two options.
Either disable fullscreen mode for your activity. Activity is not re-sized in fullscreen mode. You can do this either in xml (by changing the theme of the activity) or in Java code. Add the following lines in your onCreate() method.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);`
OR
Use an alternative way to achieve fullscreen mode. Add the following code in your onCreate() method.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
View decorView = getWindow().getDecorView();
// Hide the status bar.
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);`
Please note that method-2 only works in Android 4.1 and above.
Config to install from public Github repository, even if machine is under firewall:
dependencies: {
"foo": "https://github.com/package/foo/tarball/master"
}
This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):
from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
print(e.output.decode()) # print out the stdout messages up to the exception
print(e) # To print out the exception message
I suspect you would just want to grab a few columns from V$SESSION and the SQL statement from V$SQL. Assuming you want to exclude the background processes that Oracle itself is running
SELECT sess.process, sess.status, sess.username, sess.schemaname, sql.sql_text
FROM v$session sess,
v$sql sql
WHERE sql.sql_id(+) = sess.sql_id
AND sess.type = 'USER'
The outer join is to handle those sessions that aren't currently active, assuming you want those. You could also get the sql_fulltext column from V$SQL which will have the full SQL statement rather than the first 1000 characters, but that is a CLOB and so likely a bit more complicated to deal with.
Realistically, you probably want to look at everything that is available in V$SESSION because it's likely that you can get a lot more information than SP_WHO provides.
What you are trying to do is not possible. The reason for this is that in a POSIX system (Linux, OSX, etc), a child process cannot modify the environment of a parent process. This includes modifying the parent process's working directory and environment variables.
When you are on the commandline and you go to execute your Node script, your current process (bash
, zsh
, whatever) spawns a new process which has it's own environment, typically a copy of your current environment (it is possible to change this via system calls; but that's beyond the scope of this reply), allowing that process to do whatever it needs to do in complete isolation. When the subprocess exits, control is handed back to your shell's process, where the environment hasn't been affected.
There are a lot of reasons for this, but for one, imagine that you executed a script in the background (via ./foo.js &
) and as it ran, it started changing your working directory or overriding your PATH
. That would be a nightmare.
If you need to perform some actions that require changing your working directory of your shell, you'll need to write a function in your shell. For example, if you're running Bash, you could put this in your ~/.bash_profile
:
do_cool_thing() {
cd "/Users"
echo "Hey, I'm in $PWD"
}
and then this cool thing is doable:
$ pwd
/Users/spike
$ do_cool_thing
Hey, I'm in /Users
$ pwd
/Users
If you need to do more complex things in addition, you could always call out to your nodejs script from that function.
This is the only way you can accomplish what you're trying to do.
I encounter similar problem when installing oracle 11gR2 on Windows 2012 server. the problem is solved when I run cmd.exe as Admistrator privilege and run "lsnrctl start LISTENER".
This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.
var myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);
1 To 1 Relationships in SQL are made by merging the field of both table in one !
I know you can split a Table in two entity with a 1 to 1 relation. Most of time you use this because you want to use lazy loading on "heavy field of binary data in a table".
Exemple: You have a table containing pictures with a name column (string), maybe some metadata column, a thumbnail column and the picture itself varbinary(max). In your application, you will certainly display first only the name and the thumbnail in a collection control and then load the "full picture data" only if needed.
If it is what your are looking for. It is something called "table splitting" or "horizontal splitting".
https://visualstudiomagazine.com/articles/2014/09/01/splitting-tables.aspx
To undo your last commit, simply do git reset --hard HEAD~
.
Edit: this answer applied to an earlier version of the question that did not mention preserving local changes; the accepted answer from Tim is indeed the correct one. Thanks to qwertzguy for the heads up.
If you are allowed to use LINQ, take a look at the following example. It creates two DataTables with integer columns, fills them with some records, join them using LINQ query and outputs them to Console.
DataTable dt1 = new DataTable();
dt1.Columns.Add("CustID", typeof(int));
dt1.Columns.Add("ColX", typeof(int));
dt1.Columns.Add("ColY", typeof(int));
DataTable dt2 = new DataTable();
dt2.Columns.Add("CustID", typeof(int));
dt2.Columns.Add("ColZ", typeof(int));
for (int i = 1; i <= 5; i++)
{
DataRow row = dt1.NewRow();
row["CustID"] = i;
row["ColX"] = 10 + i;
row["ColY"] = 20 + i;
dt1.Rows.Add(row);
row = dt2.NewRow();
row["CustID"] = i;
row["ColZ"] = 30 + i;
dt2.Rows.Add(row);
}
var results = from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable() on (int)table1["CustID"] equals (int)table2["CustID"]
select new
{
CustID = (int)table1["CustID"],
ColX = (int)table1["ColX"],
ColY = (int)table1["ColY"],
ColZ = (int)table2["ColZ"]
};
foreach (var item in results)
{
Console.WriteLine(String.Format("ID = {0}, ColX = {1}, ColY = {2}, ColZ = {3}", item.CustID, item.ColX, item.ColY, item.ColZ));
}
Console.ReadLine();
// Output:
// ID = 1, ColX = 11, ColY = 21, ColZ = 31
// ID = 2, ColX = 12, ColY = 22, ColZ = 32
// ID = 3, ColX = 13, ColY = 23, ColZ = 33
// ID = 4, ColX = 14, ColY = 24, ColZ = 34
// ID = 5, ColX = 15, ColY = 25, ColZ = 35
On a Mac with a US keyboard, you want cmd+/.
I guess you'll need absolute position
.vertical_banner {position:relative;}
#bottom_link{position:absolute; bottom:0;}
Pull to refresh is built in iOS. You could do this in swift like
var refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
tableView.addSubview(refreshControl) // not required when using UITableViewController
}
@objc func refresh(_ sender: AnyObject) {
// Code to refresh table view
}
At some point you could end refreshing.
refreshControl.endRefreshing()
I see one problem with std::make_shared, it doesn't support private/protected constructors
After you add the .gitignore
file and commit it, it will no longer show up in the "untracked files" list.
git add .gitignore
git commit -m "add .gitignore file"
git status
This should work for you
sed -e 's_^all: .*_& anotherthing_'
Using s command (substitute) you can search for a line which satisfies a regular expression. In the command above, &
stands for the matched string.
those icons are a way of Egit to show you status of the current file/folder in git. You might want to check this out:
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.
>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False
Edit
Further explanation: How does Python compare string and int?
You can also use Perl for this:
perl -wnl -e '$.== NUM && print && exit;' some.file
You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.
I actually used pretty much the same code as you above. My service registration in the manifest is the following
<service android:name=".service.MyService" android:enabled="true">
<intent-filter android:label="@string/menuItemStartService" >
<action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
</intent-filter>
</service>
In the service class I created an according constant string identifying the service name like:
public class MyService extends ForeGroundService {
public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
...
}
and from the according Activity I call it with
startService(new Intent(MyService.MY_SERVICE));
and stop it with
stopService(new Intent(MyService.MY_SERVICE));
It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.
the first command is correct but change from convert to export to csv, as below,
Get-ADUser -Filter * -Properties * `
| Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
| Sort-Object -Property Name `
| Export-Csv -path C:\Users\*\Desktop\file1.csv
just share what i've been used, and works nicely
#content{
height: auto;
min-height:350px;
}
Alternatively, you could go with pgrep
or Process Grep. (Busybox is needed)
You could do a adb shell pgrep com.example.app
and it would display just the process Id.
As a suggestion, since Android is Linux, you can use most basic Linux commands with adb shell
to navigate/control around. :D
If you're not sure your input is going to be a Numpy array, you can use asarray
with dtype=int
instead of astype
:
>>> np.asarray([1,2,3,4], dtype=int)
array([1, 2, 3, 4])
If the input array already has the correct dtype, asarray
avoids the array copy while astype
does not (unless you specify copy=False
):
>>> a = np.array([1,2,3,4])
>>> a is np.asarray(a) # no copy :)
True
>>> a is a.astype(int) # copy :(
False
>>> a is a.astype(int, copy=False) # no copy :)
True
For me Updating the SDK Tools fixed the errors.
You need to add a reference to System.Web.Extensions.dll
in project for System.Web.Script.Serialization error.
You can declare a new type:
declare type MyHandler = (myArgument: string) => void;
var handler: MyHandler;
The declare
keyword is not necessary. It should be used in the .d.ts files or in similar cases.
I submitted an updated version of a patch to the PostgreSQL JDBC driver to enable this a few years back. You'll have to build the PostreSQL JDBC driver from source (after adding in the patch) to use it:
http://archives.postgresql.org/pgsql-jdbc/2008-07/msg00012.php
For Angular(7+) Project:
::ng-deep .modal-backdrop.show {
opacity: 0.7 !important;
}
Otherwise you can use:
.modal-backdrop.show {
opacity: 0.7 !important;
}
Given that 'table-layout:fixed' is the essential layout requirement, that this creates evenly spaced non-adjustable columns, but that you need to make cells of different percentage widths, perhaps set the 'colspan' of your cells to a multiple?
For example, using a total width of 100 for easy percentage calculations, and saying that you need one cell of 80% and another of 20%, consider:
<TABLE width=100% style="table-layout:fixed;white-space:nowrap;overflow:hidden;">
<tr>
<td colspan=100>
text across entire width of table
</td>
<tr>
<td colspan=80>
text in lefthand bigger cell
</td>
<td colspan=20>
text in righthand smaller cell
</td>
</TABLE>
Of course, for columns of 80% and 20%, you could just set the 100% width cell colspan to 5, the 80% to 4, and the 20% to 1.
The answer may be outdated, since there is a name
property on the UploadedFile
class. See: Uploaded Files and Upload Handlers (Django docs). So, if you bind your form with a FileField
correctly, the access should be as easy as:
if form.is_valid():
form.cleaned_data['my_file'].name
Just place the css in a template string.
const cssTemplateString = `.foo:[psuedoSelector]{prop: value}`;
Then create a style element and place the string in the style tag and attach it to the document.
const styleTag = document.createElement("style");
styleTag.innerHTML = cssTemplateString;
document.head.insertAdjacentElement('beforeend', styleTag);
Specificity will take care of the rest. Then you can remove and add style tags dynamically. This is a simple alternative to libraries and messing with the stylesheet array in the DOM. Happy Coding!
I took the answer from PirateApp and made it reusable. If you include this script it will transform all selects with the class '.dropdown' to searchable dropdowns.
$('.dropdown').each(function(index, dropdown) {
//Find the input search box
let search = $(dropdown).find('.search');
//Find every item inside the dropdown
let items = $(dropdown).find('.dropdown-item');
//Capture the event when user types into the search box
$(search).on('input', function() {
filter($(search).val().trim().toLowerCase())
});
//For every word entered by the user, check if the symbol starts with that word
//If it does show the symbol, else hide it
function filter(word) {
let length = items.length
let collection = []
let hidden = 0
for (let i = 0; i < length; i++) {
if (items[i].value.toString().toLowerCase().includes(word)) {
$(items[i]).show()
} else {
$(items[i]).hide()
hidden++
}
}
//If all items are hidden, show the empty view
if (hidden === length) {
$(dropdown).find('.dropdown_empty').show();
} else {
$(dropdown).find('.dropdown_empty').hide();
}
}
//If the user clicks on any item, set the title of the button as the text of the item
$(dropdown).find('.dropdown-menu').find('.menuItems').on('click', '.dropdown-item', function() {
$(dropdown).find('.dropdown-toggle').text($(this)[0].value);
$(dropdown).find('.dropdown-toggle').dropdown('toggle');
})
});
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="dropdown">
<button class="btn btn-sm btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Benutzer
</button>
<div class="dropdown-menu" aria-labelledby="dropdown_user">
<form class="px-4 py-2">
<input type="search" class="form-control search" placeholder="Suche.." autofocus="autofocus">
</form>
<div class="menuItems">
<input type="button" class="dropdown-item" type="button" value="Test1" />
<input type="button" class="dropdown-item" type="button" value="Test2" />
<input type="button" class="dropdown-item" type="button" value="Test3" />
</div>
<div style="display:none;" class="dropdown-header dropdown_empty">No entry found</div>
</div>
</div>
_x000D_
Java9 has an "Ahead of time" compiler that does several optimizations at compile-time, rather than runtime, which can be seen as inlining.
This was my solution to protect against an empty array as well:
import React, { Component } from 'react';
import { arrayOf, shape, string, number } from 'prop-types';
ReactComponent.propTypes = {
arrayWithShape: (props, propName, componentName) => {
const arrayWithShape = props[propName]
PropTypes.checkPropTypes({ arrayWithShape:
arrayOf(
shape({
color: string.isRequired,
fontSize: number.isRequired,
}).isRequired
).isRequired
}, {arrayWithShape}, 'prop', componentName);
if(arrayWithShape.length < 1){
return new Error(`${propName} is empty`)
}
}
}
I think that your question is not defined well enough, for the following reason.
Answers relying on months_between have to deal with the following issue: that the function reports exactly one month between 2013-02-28 and 2013-03-31, and between 2013-01-28 and 2013-02-28, and between 2013-01-31 and 2013-02-28 (I suspect that some answerers have not used these functions in practice, or are now going to have to review some production code!)
This is documented behaviour, in which dates that are both the last in their respective months or which fall on the same day of the month are judged to be an integer number of months apart.
So, you get the same result of "1" when comparing 2013-02-28 with 2013-01-28 or with 2013-01-31, but comparing it with 2013-01-29 or 2013-01-30 gives 0.967741935484 and 0.935483870968 respectively -- so as one date approaches the other the difference reported by this function can increase.
If this is not an acceptable situation then you'll have to write a more complex function, or just rely on a calculation that assumes 30 (for example) days per month. In the latter case, how will you deal with 2013-02-28 and 2013-03-31?
Grab it from here
Just choose required version and click 'Binary'. e.g direct link to version 2.5
In visual studio 2017 please do following steps:
1) select Tool=>Options=>NuGet Package Manager=> Package Sources then uncheck Microsoft Visual Studio Offline Packages Option.
2) now open Tool=>NuGet Package Maneger=>Package Manager Console. 3) execute command in PM>dotnet restore.
Hope its working...
I have a simple solution which is working perfectly. The code is not mine, I found it on this link. Here are the steps to follow:
1. Before downloading the image, let’s write a method for saving bitmap into an image file in the internal storage in android. It needs a context, better to use the pass in the application context by getApplicationContext(). This method can be dumped into your Activity class or other util classes.
public void saveImage(Context context, Bitmap b, String imageName)
{
FileOutputStream foStream;
try
{
foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.PNG, 100, foStream);
foStream.close();
}
catch (Exception e)
{
Log.d("saveImage", "Exception 2, Something went wrong!");
e.printStackTrace();
}
}
2. Now we have a method to save bitmap into an image file in andorid, let’s write the AsyncTask for downloading images by url. This private class need to be placed in your Activity class as a subclass. After the image is downloaded, in the onPostExecute method, it calls the saveImage method defined above to save the image. Note, the image name is hardcoded as “my_image.png”.
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
private String TAG = "DownloadImage";
private Bitmap downloadImageBitmap(String sUrl) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(sUrl).openStream(); // Download Image from URL
bitmap = BitmapFactory.decodeStream(inputStream); // Decode Bitmap
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "Exception 1, Something went wrong!");
e.printStackTrace();
}
return bitmap;
}
@Override
protected Bitmap doInBackground(String... params) {
return downloadImageBitmap(params[0]);
}
protected void onPostExecute(Bitmap result) {
saveImage(getApplicationContext(), result, "my_image.png");
}
}
3. The AsyncTask for downloading the image is defined, but we need to execute it in order to run that AsyncTask. To do so, write this line in your onCreate method in your Activity class, or in an onClick method of a button or other places you see fit.
new DownloadImage().execute("http://developer.android.com/images/activity_lifecycle.png");
The image should be saved in /data/data/your.app.packagename/files/my_image.jpeg, check this post for accessing this directory from your device.
IMO this solves the issue! If you want further steps such as load the image you can follow these extra steps:
4. After the image is downloaded, we need a way to load the image bitmap from the internal storage, so we can use it. Let’s write the method for loading the image bitmap. This method takes two paramethers, a context and an image file name, without the full path, the context.openFileInput(imageName) will look up the file at the save directory when this file name was saved in the above saveImage method.
public Bitmap loadImageBitmap(Context context, String imageName) {
Bitmap bitmap = null;
FileInputStream fiStream;
try {
fiStream = context.openFileInput(imageName);
bitmap = BitmapFactory.decodeStream(fiStream);
fiStream.close();
} catch (Exception e) {
Log.d("saveImage", "Exception 3, Something went wrong!");
e.printStackTrace();
}
return bitmap;
}
5. Now we have everything we needed for setting the image of an ImageView or any other Views that you like to use the image on. When we save the image, we hardcoded the image name as “my_image.jpeg”, now we can pass this image name to the above loadImageBitmap method to get the bitmap and set it to an ImageView.
someImageView.setImageBitmap(loadImageBitmap(getApplicationContext(), "my_image.jpeg"));
6. To get the image full path by image name.
File file = getApplicationContext().getFileStreamPath("my_image.jpeg");
String imageFullPath = file.getAbsolutePath();
7. Check if the image file exists.
File file =
getApplicationContext().getFileStreamPath("my_image.jpeg");
if (file.exists()) Log.d("file", "my_image.jpeg exists!");
To delete the image file.
File file = getApplicationContext().getFileStreamPath("my_image.jpeg"); if (file.delete()) Log.d("file", "my_image.jpeg deleted!");
It can be easily solved by package java.util.Zip
no need any extra Jar
files
Just copy the following code and run it
with your IDE
//Import all needed packages
package general;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
private List <String> fileList;
private static final String OUTPUT_ZIP_FILE = "Folder.zip";
private static final String SOURCE_FOLDER = "D:\\Reports"; // SourceFolder path
public ZipUtils() {
fileList = new ArrayList < String > ();
}
public static void main(String[] args) {
ZipUtils appZip = new ZipUtils();
appZip.generateFileList(new File(SOURCE_FOLDER));
appZip.zipIt(OUTPUT_ZIP_FILE);
}
public void zipIt(String zipFile) {
byte[] buffer = new byte[1024];
String source = new File(SOURCE_FOLDER).getName();
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + zipFile);
FileInputStream in = null;
for (String file: this.fileList) {
System.out.println("File Added : " + file);
ZipEntry ze = new ZipEntry(source + File.separator + file);
zos.putNextEntry(ze);
try {
in = new FileInputStream(SOURCE_FOLDER + File.separator + file);
int len;
while ((len = in .read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
} finally {
in.close();
}
}
zos.closeEntry();
System.out.println("Folder successfully compressed");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void generateFileList(File node) {
// add file only
if (node.isFile()) {
fileList.add(generateZipEntry(node.toString()));
}
if (node.isDirectory()) {
String[] subNote = node.list();
for (String filename: subNote) {
generateFileList(new File(node, filename));
}
}
}
private String generateZipEntry(String file) {
return file.substring(SOURCE_FOLDER.length() + 1, file.length());
}
}
Refer mkyong..I changed the code for the requirement of current question
Here is my solution that is based on the idea of the book "Cracking the Coding Interview" (P54):
/**
* List permutations of a string.
*
* @param s the input string
* @return the list of permutations
*/
public static ArrayList<String> permutation(String s) {
// The result
ArrayList<String> res = new ArrayList<String>();
// If input string's length is 1, return {s}
if (s.length() == 1) {
res.add(s);
} else if (s.length() > 1) {
int lastIndex = s.length() - 1;
// Find out the last character
String last = s.substring(lastIndex);
// Rest of the string
String rest = s.substring(0, lastIndex);
// Perform permutation on the rest string and
// merge with the last character
res = merge(permutation(rest), last);
}
return res;
}
/**
* @param list a result of permutation, e.g. {"ab", "ba"}
* @param c the last character
* @return a merged new list, e.g. {"cab", "acb" ... }
*/
public static ArrayList<String> merge(ArrayList<String> list, String c) {
ArrayList<String> res = new ArrayList<>();
// Loop through all the string in the list
for (String s : list) {
// For each string, insert the last character to all possible positions
// and add them to the new list
for (int i = 0; i <= s.length(); ++i) {
String ps = new StringBuffer(s).insert(i, c).toString();
res.add(ps);
}
}
return res;
}
Running output of string "abcd":
Step 1: Merge [a] and b: [ba, ab]
Step 2: Merge [ba, ab] and c: [cba, bca, bac, cab, acb, abc]
Step 3: Merge [cba, bca, bac, cab, acb, abc] and d: [dcba, cdba, cbda, cbad, dbca, bdca, bcda, bcad, dbac, bdac, badc, bacd, dcab, cdab, cadb, cabd, dacb, adcb, acdb, acbd, dabc, adbc, abdc, abcd]
For those using TortoiseSVN, you can accomplish this by using the Repository Browser (it's labeled "Repo-browser" in the context menu.)
Find the branch folder you want to delete, right-click it, and select "Delete."
Enter your commit message, and you're done.
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
Key input is a predefined event. You can catch events by attaching event_sequence
(s) to event_handle
(s) by using one or multiple of the existing binding methods(bind
, bind_class
, tag_bind
, bind_all
). In order to do that:
event_handle
methodevent_sequence
) that fits your case from an events listWhen an event happens, all of those binding methods implicitly calls the event_handle
method while passing an Event
object, which includes information about specifics of the event that happened, as the argument.
In order to detect the key input, one could first catch all the '<KeyPress>'
or '<KeyRelease>'
events and then find out the particular key used by making use of event.keysym
attribute.
Below is an example using bind
to catch both '<KeyPress>'
and '<KeyRelease>'
events on a particular widget(root
):
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def event_handle(event):
# Replace the window's title with event.type: input key
root.title("{}: {}".format(str(event.type), event.keysym))
if __name__ == '__main__':
root = tk.Tk()
event_sequence = '<KeyPress>'
root.bind(event_sequence, event_handle)
root.bind('<KeyRelease>', event_handle)
root.mainloop()
Real world example from SQL Server 2008.
Source data:
ID Start
1 2010-04-30 00:00:01.000
2 2010-04-02 00:00:00.000
3 2010-05-01 00:00:00.000
4 2010-07-31 00:00:00.000
Query:
SELECT
*
FROM
tbl
WHERE
Start BETWEEN '2010-04-01 00:00:00' AND '2010-05-01 00:00:00'
Results:
ID Start
1 2010-04-30 00:00:01.000
2 2010-04-02 00:00:00.000
In my case, I couldn't see any of the controls in the project. Only when right clicking on toolBox and selecting "Show All" I saw them, but yet they were disabled...
Changing Project type from Windows application to ClassLibrary made the fix.
i've solved this issue with these steps: expand your project, right click "JRE System Library" > Properties > choose 3rd option "Workspace default JRE" > OK . Hope it help you too
From WWDC 2015 there is a session on Implementing UI Designs in Interface Builder. Around the 32min mark he says that you always want to make your @IBOutlet
strong.
Use mydate.Date
to work with the date part of the DateTime class only.
If its just about detecting whether or not you're dealing with an Object
, I could think of
Object.getPrototypeOf( obj ) === Object.prototype
However, this would probably fail for non-object primitive values. Actually there is nothing wrong with invoking .toString()
to retreive the [[cclass]] property. You can even create a nice syntax like
var type = Function.prototype.call.bind( Object.prototype.toString );
and then use it like
if( type( obj ) === '[object Object]' ) { }
It might not be the fastest operation but I don't think the performance leak there is too big.
You can try the following code:
$("input[name=cols][value=" + value + "]").attr('checked', 'checked');
This will set the attribute checked for the radio columns and value as specified.
You could use actionLayout
from the support library.
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/button_item"
android:title=""
app:actionLayout="@layout/button_layout"
app:showAsAction="always"
/>
</menu>
button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Activity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.button_item);
Button btn = item.getActionView().findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Toolbar Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
return true;
}
Remove /etc/my.cnf file and retry the installation, it worked for me for exactly same problem. :-)
You can use CSS3 to create an effect like that, but then you're only going to see it in modern browsers that support box shadow, unless you use a polyfill like CSS3PIE. So, for example, you could do something like this: http://jsfiddle.net/cany2/
Another way to accomplish this is with the jq "--arg" flag. Using the original example:
#!/bin/sh
#this works ***
projectID=$(cat file.json | jq -r '.resource[] |
select(.username=="[email protected]") | .id')
echo "$projectID"
[email protected]
# Use --arg to pass the variable to jq. This should work:
projectID=$(cat file.json | jq --arg EMAILID $EMAILID -r '.resource[]
| select(.username=="$EMAILID") | .id')
echo "$projectID"
See here, which is where I found this solution: https://github.com/stedolan/jq/issues/626
This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.
The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.
Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)
This answer assumes that the PATH has been correctly set as described in the other answers
If you're on Windows 10 and dont have Admin rights then right click on the CMD, powershell ... program and select run as administrator. Then try adb [command]
Look at the WSGI reference implementation. You already have it in your Python libraries. It's quite simple.
You can't control the timeout due to UnknownHostException
. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.
But I find it hard to believe that you are really getting an UnknownHostException
when you specify an IP address rather than a hostname.
EDIT To control Java's DNS timeouts see this answer.
If you want, you can use the private framework CoreTelephony
which called CTMessageCenter
class. There are a few methods to send sms.
The following worked for me. First I'd make sure the files in the a
directory are source-controlled:
$ cd a
$ git init
$ git add .
$ git commit -m "..."
Then
$ git remote add origin https://URL/TO/REPO
$ git pull origin master --allow-unrelated-histories
$ git push origin master
relative position
, inside this parent you can set the absolute position
of your divs<div> <------Relative
<div/> <------Absolute
<div/> <------Absolute
<div/> <------Absolute
<div/>
Final result:
https://codepen.io/hiteshsahu/pen/XWKYEYb?editors=0100
<div class="container">
<div class="header">TOP: I am at Top & above of body container</div>
<div class="center">CENTER: I am at Top & in Center of body container</div>
<div class="footer">BOTTOM: I am at Bottom & above of body container</div>
</div>
Set HTML Body full width
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
After that, you can set a div with the relative position to take full width and height
.container {
position: relative;
background-color: blue;
height: 100%;
width: 100%;
border:1px solid;
color: white;
background-image: url("https://images.pexels.com/photos/5591663/pexels-photo-5591663.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260");
background-color: #cccccc;
}
Inside this div with the relative position you can put your div with absolute positions
On TOP above the container
.header {
position: absolute;
margin-top: -10px;
background-color: #d81b60 ;
left:0;
right:0;
margin:15px;
padding:10px;
font-size: large;
}
On BOTTOM above the container
.footer {
position: absolute;
background-color: #00bfa5;
left:0;
right:0;
bottom:0;
margin:15px;
padding:10px;
color: white;
font-size: large;
}
In CENTER above the container
.center {
position: absolute;
background-color: #00bfa5;
left: 30%;
right: 30%;
bottom:30%;
top: 30%;
margin:10px;
padding:10px;
color: white;
font-size: large;
}
For example,
package verbose
import (
"fmt"
"testing"
)
func TestPrintSomething(t *testing.T) {
fmt.Println("Say hi")
t.Log("Say bye")
}
go test -v
=== RUN TestPrintSomething
Say hi
--- PASS: TestPrintSomething (0.00 seconds)
v_test.go:10: Say bye
PASS
ok so/v 0.002s
-v Verbose output: log all tests as they are run. Also print all text from Log and Logf calls even if the test succeeds.
func (c *T) Log(args ...interface{})
Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.
Running python -h
, I see a command line option:
-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'
Here is the relevant doc.
For pointers, you need them to point to something, so pointers cost memory space.
For example a function that takes an integer pointer will not take the integer variable. So you will need to create a pointer for that first to pass on to the function.
As for a reference, it will not cost memory. You have an integer variable, and you can pass it as a reference variable. That's it. You don't need to create a reference variable specially for it.
May be this will help you.
SELECT SUBSTRING(myColumn, 1, CASE CHARINDEX('/', myColumn)
WHEN 0
THEN LEN(myColumn)
ELSE CHARINDEX('/', myColumn) - 1
END) AS FirstName
,SUBSTRING(myColumn, CASE CHARINDEX('/', myColumn)
WHEN 0
THEN LEN(myColumn) + 1
ELSE CHARINDEX('/', myColumn) + 1
END, 1000) AS LastName
FROM MyTable
dir /ad /b /s
will give the required answer.
Try something like this (use this.url to get the url):
$.ajax({
url: 'http://www.example.org',
data: {'a':1,'b':2,'c':3},
dataType: 'xml',
complete : function(){
alert(this.url)
},
success: function(xml){
}
});
Taken from here
Note that there is a difference between a cast to long
and a cast to Long
. If you cast to long
(a primitive value) then it should be automatically boxed to a Long
(the reference type that wraps it).
You could alternatively use new
to create an instance of Long
, initializing it with the int
value.
For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.
The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval]
(string or int) which then allows you to refer to an existing record.
Weirdly, I found that REMOVING &characterEncoding=UTF-8
from the JDBC url
did the trick for me with similar issues.
Based on my properties,
jdbc_url=jdbc:mysql://localhost:3306/dbName?useUnicode=true
I think this supports what @Esailija has said above, i.e. my MySQL, which is indeed 5.5, is figuring out its own favorite flavor of UTF-8 encoding.
(Note, I'm also specifying the InputStream
I'm reading from as UTF-8
in the java code, which probably doesn't hurt)...
I believe I should add a hardware designer’s perspective to this since I design and build floating point hardware. Knowing the origin of the error may help in understanding what is happening in the software, and ultimately, I hope this helps explain the reasons for why floating point errors happen and seem to accumulate over time.
From an engineering perspective, most floating point operations will have some element of error since the hardware that does the floating point computations is only required to have an error of less than one half of one unit in the last place. Therefore, much hardware will stop at a precision that's only necessary to yield an error of less than one half of one unit in the last place for a single operation which is especially problematic in floating point division. What constitutes a single operation depends upon how many operands the unit takes. For most, it is two, but some units take 3 or more operands. Because of this, there is no guarantee that repeated operations will result in a desirable error since the errors add up over time.
Most processors follow the IEEE-754 standard but some use denormalized, or different standards . For example, there is a denormalized mode in IEEE-754 which allows representation of very small floating point numbers at the expense of precision. The following, however, will cover the normalized mode of IEEE-754 which is the typical mode of operation.
In the IEEE-754 standard, hardware designers are allowed any value of error/epsilon as long as it's less than one half of one unit in the last place, and the result only has to be less than one half of one unit in the last place for one operation. This explains why when there are repeated operations, the errors add up. For IEEE-754 double precision, this is the 54th bit, since 53 bits are used to represent the numeric part (normalized), also called the mantissa, of the floating point number (e.g. the 5.3 in 5.3e5). The next sections go into more detail on the causes of hardware error on various floating point operations.
The main cause of the error in floating point division is the division algorithms used to calculate the quotient. Most computer systems calculate division using multiplication by an inverse, mainly in Z=X/Y
, Z = X * (1/Y)
. A division is computed iteratively i.e. each cycle computes some bits of the quotient until the desired precision is reached, which for IEEE-754 is anything with an error of less than one unit in the last place. The table of reciprocals of Y (1/Y) is known as the quotient selection table (QST) in the slow division, and the size in bits of the quotient selection table is usually the width of the radix, or a number of bits of the quotient computed in each iteration, plus a few guard bits. For the IEEE-754 standard, double precision (64-bit), it would be the size of the radix of the divider, plus a few guard bits k, where k>=2
. So for example, a typical Quotient Selection Table for a divider that computes 2 bits of the quotient at a time (radix 4) would be 2+2= 4
bits (plus a few optional bits).
3.1 Division Rounding Error: Approximation of Reciprocal
What reciprocals are in the quotient selection table depend on the division method: slow division such as SRT division, or fast division such as Goldschmidt division; each entry is modified according to the division algorithm in an attempt to yield the lowest possible error. In any case, though, all reciprocals are approximations of the actual reciprocal and introduce some element of error. Both slow division and fast division methods calculate the quotient iteratively, i.e. some number of bits of the quotient are calculated each step, then the result is subtracted from the dividend, and the divider repeats the steps until the error is less than one half of one unit in the last place. Slow division methods calculate a fixed number of digits of the quotient in each step and are usually less expensive to build, and fast division methods calculate a variable number of digits per step and are usually more expensive to build. The most important part of the division methods is that most of them rely upon repeated multiplication by an approximation of a reciprocal, so they are prone to error.
Another cause of the rounding errors in all operations are the different modes of truncation of the final answer that IEEE-754 allows. There's truncate, round-towards-zero, round-to-nearest (default), round-down, and round-up. All methods introduce an element of error of less than one unit in the last place for a single operation. Over time and repeated operations, truncation also adds cumulatively to the resultant error. This truncation error is especially problematic in exponentiation, which involves some form of repeated multiplication.
Since the hardware that does the floating point calculations only needs to yield a result with an error of less than one half of one unit in the last place for a single operation, the error will grow over repeated operations if not watched. This is the reason that in computations that require a bounded error, mathematicians use methods such as using the round-to-nearest even digit in the last place of IEEE-754, because, over time, the errors are more likely to cancel each other out, and Interval Arithmetic combined with variations of the IEEE 754 rounding modes to predict rounding errors, and correct them. Because of its low relative error compared to other rounding modes, round to nearest even digit (in the last place), is the default rounding mode of IEEE-754.
Note that the default rounding mode, round-to-nearest even digit in the last place, guarantees an error of less than one half of one unit in the last place for one operation. Using the truncation, round-up, and round down alone may result in an error that is greater than one half of one unit in the last place, but less than one unit in the last place, so these modes are not recommended unless they are used in Interval Arithmetic.
In short, the fundamental reason for the errors in floating point operations is a combination of the truncation in hardware, and the truncation of a reciprocal in the case of division. Since the IEEE-754 standard only requires an error of less than one half of one unit in the last place for a single operation, the floating point errors over repeated operations will add up unless corrected.
Add this into your httpd.conf file
Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore
If you use code analysis tools (e.g. FxCop), it will recommend that you mark a method static
if that method don't access instance data. The rationale is that there is a performance gain. MSDN: CA1822 - Mark members as static.
It is more of a guideline than a rule, really...
Using furl and regex (python 3)
>>> import re
>>> import furl
>>> p = re.compile(r'(\/)+')
>>> url = furl.furl('/media/path').add(path='/js/foo.js').url
>>> url
'/media/path/js/foo.js'
>>> p.sub(r"\1", url)
'/media/path/js/foo.js'
>>> url = furl.furl('/media/path').add(path='js/foo.js').url
>>> url
'/media/path/js/foo.js'
>>> p.sub(r"\1", url)
'/media/path/js/foo.js'
>>> url = furl.furl('/media/path/').add(path='js/foo.js').url
>>> url
'/media/path/js/foo.js'
>>> p.sub(r"\1", url)
'/media/path/js/foo.js'
>>> url = furl.furl('/media///path///').add(path='//js///foo.js').url
>>> url
'/media///path/////js///foo.js'
>>> p.sub(r"\1", url)
'/media/path/js/foo.js'
The full list of readyState
values is:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
(from https://www.w3schools.com/js/js_ajax_http_response.asp)
In practice you almost never use any of them except for 4.
Some XMLHttpRequest implementations may let you see partially received responses in responseText
when readyState==3
, but this isn't universally supported and shouldn't be relied upon.
If I understood you correctly, you need to convert your NSString
to int
? Try this peace of code:
NSString *stringWithNumberInside = [_returnedArguments objectAtIndex:2];
int number;
sscanf([stringWithNumberInside UTF8String], "%x", &flags);
Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row
:
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
You could then access one:
MyStringArrays.ElementAt(0)[1]
If you use linqpad, here is a very simple scenario of your example:
class Datatable
{
public List<data> rows { get; set; }
public Datatable(){
rows = new List<data>();
}
}
class data
{
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}
void Main()
{
var datatable = new Datatable();
var r = new data();
r.Name = "Jim";
r.Address = "USA";
r.Age = 23;
datatable.rows.Add(r);
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
var s = MyStringArrays.ElementAt(0)[1];
Console.Write(s);//"USA"
}
If you prefer to use the simplest possible solution to a problem, an alternative to RedirectMatch is, the more basic, Redirect directive.
It does not use pattern matching and so is more explicit and easier for others to understand.
i.e
<IfModule mod_alias.c>
#Repoint old contact page to new contact page:
Redirect 301 /contact.php http://example.com/contact-us.php
</IfModule>
Query strings should be carried over because the docs say:
Additional path information beyond the matched URL-path will be appended to the target URL.
ng g c COMPONENTNAME
should work, if your are getting module not found exception then try these things-
Use os.path.normpath
, then os.path.basename
:
>>> os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
'folderD'
The first strips off any trailing slashes, the second gives you the last part of the path. Using only basename
gives everything after the last slash, which in this case is ''
.
You may have a try for https://github.com/cls1991/pef. It will remove package with its all dependencies.
Doing a relative import is absolulutely OK! Here's what little 'ol me does:
#first change the cwd to the script path
scriptPath = os.path.realpath(os.path.dirname(sys.argv[0]))
os.chdir(scriptPath)
#append the relative location you want to import from
sys.path.append("../common")
#import your module stored in '../common'
import common.py
Thank you for inspiration.
I had the same problem and instead of just copy-pasting some function from the Internet, I wrote an open source tool for it. Feel free to use it or provide feedback!
https://github.com/BrandEmbassy/php-memory
Just install it using Composer and then you get the current PHP memory limit like this:
$configuration = new \BrandEmbassy\Memory\MemoryConfiguration();
$limitProvider = new \BrandEmbassy\Memory\MemoryLimitProvider($configuration);
$limitInBytes = $memoryLimitProvider->getLimitInBytes();
==
checks to see if they are actually the same object in memory (which confusingly sometimes is true, since they may both be from the pool), where as equals()
is overridden by java.lang.String
to check each character to ensure true equality. So therefore, equals()
is what you want.
You can just change the project structure to add that folder as a "source" directory.
Project Structure ? Modules ? Click the generated-sources
folder and make it a sources
folder.
Or:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<id>test</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${basedir}/target/generated-sources</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
If you want insert all data from one table to another table there is a very simply sql
INSERT INTO destinationTable (SELECT * FROM sourceDbName.SourceTableName);
To loop from current record to the end:
While Me.CurrentRecord < Me.Recordset.RecordCount
' ... do something to current record
' ...
DoCmd.GoToRecord Record:=acNext
Wend
To check if it is possible to go to next record:
If Me.CurrentRecord < Me.Recordset.RecordCount Then
' ...
End If
I pressed Deny by mistake and I was stuck, no way to code sign any Pods.
This is how I solved the problem:
com.apple.gs.xcode.auth.com.apple.account.AppleIDAuthentication.token
Save Changes
The parent probably isn't yet set when you are trying to access it.
Try this:
loginForm = new SubLogin();
loginForm.Show(this);
loginForm.CenterToParent()
The python 2.5 documentation explains it well.
Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).
Unfortunately that page seems to have disappeared in the documentation for more recent versions.
There are a couple of CSS 3 measurement units called:
From the linked W3 Candidate Recommendation above:
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.
These units are vh
(viewport height), vw
(viewport width), vmin
(viewport minimum length) and vmax
(viewport maximum length).
For this question, we can make use of vh
: 1vh
is equal to 1% of the viewport's height. That is to say, 100vh
is equal to the height of the browser window, regardless of where the element is situated in the DOM tree:
<div></div>
div {
height: 100vh;
}
This is literally all that's needed. Here is a JSFiddle example of this in use.
This is currently supported on all up-to-date major browsers apart from Opera Mini. Check out Can I use... for further support.
In the case of the question at hand, featuring a left and a right divider, here is a JSFiddle example showing a two-column layout involving both vh
and vw
.
100vh
different to 100%
?Take this layout for example:
<body style="height:100%">
<div style="height:200px">
<p style="height:100%; display:block;">Hello, world!</p>
</div>
</body>
The p
tag here is set to 100% height, but because its containing div
has 200 pixels height, 100% of 200 pixels becomes 200 pixels, not 100% of the body
height. Using 100vh
instead means that the p
tag will be 100% height of the body
regardless of the div
height. Take a look at this accompanying JSFiddle to easily see the difference!
$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick. unless you're loading the button with ajax. In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.
Firstly, check that you're using the same accounts in both Application Loaded (or XCode) and iTunes connect. Secondly, check that Bundle Id in error message and in iTunes connect are match, including tHe cAsE!
From the documentation:
It is necessary to keep in mind that the browsers do not know how to correctly show this error.
I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.
You just need to create a class which extends Exception (for a checked exception) or any subclass of Exception, or RuntimeException (for a runtime exception) or any subclass of RuntimeException.
Then, in your code, just use
if (word.contains(" "))
throw new MyException("some message");
}
Read the Java tutorial. This is basic stuff that every Java developer should know: http://docs.oracle.com/javase/tutorial/essential/exceptions/
When you use GROUP BY
, the resulting rows will be usually less then incoming rows.
But, when you use PARTITION BY
, the resulting row count should be the same as incoming.
A really simple way to use argparse and amend the '-h'/ '--help' switches to display your own personal code help instructions is to set the default help to False, you can also add as many additional .add_arguments as you like:
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.parse_args()
Run: python test.py -h
Output:
usage: test.py [-h]
optional arguments:
-h, --help To run this script please provide two arguments
I recommend you to use JSON.NET
. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...
Serialization Example:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Performance Comparison To Other JSON serializiation Techniques
Instead of looking at the source code, you should read the javadoc String.format() and Formatter syntax.
You specify the format of the value after the %. For instance for decimal integer it is d
, and for String it is s
:
String aString = "world";
int aInt = 20;
String.format("Hello, %s on line %d", aString, aInt );
Output:
Hello, world on line 20
To do what you tried (use an argument index), you use: *n*$
,
String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );
Output:
Line:20. Value:world. Result: Hello world at line 20
For Example:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
For changing key value:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
output:
Array ( [firstKey] => changedValue [secondKey] => secondValue )
For adding new key value pair:
$data['newKey'] = 'newValue';
//this will add new key and value because newKey is not available in array
output:
Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue )
Get fields where a timestamp is greater than date in postgresql:
SELECT * from yourtable
WHERE your_timestamp_field > to_date('05 Dec 2000', 'DD Mon YYYY');
Subtract minutes from timestamp in postgresql:
SELECT * from yourtable
WHERE your_timestamp_field > current_timestamp - interval '5 minutes'
Subtract hours from timestamp in postgresql:
SELECT * from yourtable
WHERE your_timestamp_field > current_timestamp - interval '5 hours'
Regan's answer is great, but it's a bit out of date, since the correct way to do this is avoid the lxc execution context as Docker has dropped LXC as the default execution context as of docker 0.9.
Instead it's better to tell docker about the nvidia devices via the --device flag, and just use the native execution context rather than lxc.
These instructions were tested on the following environment:
See CUDA 6.5 on AWS GPU Instance Running Ubuntu 14.04 to get your host machine setup.
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
$ sudo sh -c "echo deb https://get.docker.com/ubuntu docker main > /etc/apt/sources.list.d/docker.list"
$ sudo apt-get update && sudo apt-get install lxc-docker
ls -la /dev | grep nvidia
crw-rw-rw- 1 root root 195, 0 Oct 25 19:37 nvidia0
crw-rw-rw- 1 root root 195, 255 Oct 25 19:37 nvidiactl
crw-rw-rw- 1 root root 251, 0 Oct 25 19:37 nvidia-uvm
I've created a docker image that has the cuda drivers pre-installed. The dockerfile is available on dockerhub if you want to know how this image was built.
You'll want to customize this command to match your nvidia devices. Here's what worked for me:
$ sudo docker run -ti --device /dev/nvidia0:/dev/nvidia0 --device /dev/nvidiactl:/dev/nvidiactl --device /dev/nvidia-uvm:/dev/nvidia-uvm tleyden5iwx/ubuntu-cuda /bin/bash
This should be run from inside the docker container you just launched.
Install CUDA samples:
$ cd /opt/nvidia_installers
$ ./cuda-samples-linux-6.5.14-18745345.run -noprompt -cudaprefix=/usr/local/cuda-6.5/
Build deviceQuery sample:
$ cd /usr/local/cuda/samples/1_Utilities/deviceQuery
$ make
$ ./deviceQuery
If everything worked, you should see the following output:
deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 6.5, CUDA Runtime Version = 6.5, NumDevs = 1, Device0 = GRID K520
Result = PASS
After upgrade my computer with pip today, and check the other answers here, I can tell you that it could be ANYTHING. You should check error by error, looking for what's the specific library that you need. In my case, these were the libraries that I had to install:
$ sudo apt-get install libssl-dev
$ sudo apt-get install libffi-dev
$ sudo apt-get install libjpeg-dev
$ sudo apt-get install libvirt-dev
$ sudo apt-get install libsqlite3-dev
$ sudo apt-get install libcurl4-openssl-dev
$ sudo apt-get install libxml2-dev libxslt1-dev python-dev
HTH
This is not exactly a hot topic, but I have a factory class that allows a dll to create an instance and return it as a DLL. It is what I came looking for but couldn't find exactly.
It is called like,
IHTTP_Server *server = SN::SN_Factory<IHTTP_Server>::CreateObject();
IHTTP_Server *server2 =
SN::SN_Factory<IHTTP_Server>::CreateObject(IHTTP_Server_special_entry);
where IHTTP_Server is the pure virtual interface for a class created either in another DLL, or the same one.
DEFINE_INTERFACE is used to give a class id an interface. Place inside interface;
An interface class looks like,
class IMyInterface
{
DEFINE_INTERFACE(IMyInterface);
public:
virtual ~IMyInterface() {};
virtual void MyMethod1() = 0;
...
};
The header file is like this
#if !defined(SN_FACTORY_H_INCLUDED)
#define SN_FACTORY_H_INCLUDED
#pragma once
The libraries are listed in this macro definition. One line per library/executable. It would be cool if we could call into another executable.
#define SN_APPLY_LIBRARIES(L, A) \
L(A, sn, "sn.dll") \
L(A, http_server_lib, "http_server_lib.dll") \
L(A, http_server, "")
Then for each dll/exe you define a macro and list its implementations. Def means that it is the default implementation for the interface. If it is not the default, you give a name for the interface used to identify it. Ie, special, and the name will be IHTTP_Server_special_entry.
#define SN_APPLY_ENTRYPOINTS_sn(M) \
M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, def) \
M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, special)
#define SN_APPLY_ENTRYPOINTS_http_server_lib(M) \
M(IHTTP_Server, HTTP::server::server, http_server_lib, def)
#define SN_APPLY_ENTRYPOINTS_http_server(M)
With the libraries all setup, the header file uses the macro definitions to define the needful.
#define APPLY_ENTRY(A, N, L) \
SN_APPLY_ENTRYPOINTS_##N(A)
#define DEFINE_INTERFACE(I) \
public: \
static const long Id = SN::I##_def_entry; \
private:
namespace SN
{
#define DEFINE_LIBRARY_ENUM(A, N, L) \
N##_library,
This creates an enum for the libraries.
enum LibraryValues
{
SN_APPLY_LIBRARIES(DEFINE_LIBRARY_ENUM, "")
LastLibrary
};
#define DEFINE_ENTRY_ENUM(I, C, L, D) \
I##_##D##_entry,
This creates an enum for interface implementations.
enum EntryValues
{
SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_ENUM)
LastEntry
};
long CallEntryPoint(long id, long interfaceId);
This defines the factory class. Not much to it here.
template <class I>
class SN_Factory
{
public:
SN_Factory()
{
}
static I *CreateObject(long id = I::Id )
{
return (I *)CallEntryPoint(id, I::Id);
}
};
}
#endif //SN_FACTORY_H_INCLUDED
Then the CPP is,
#include "sn_factory.h"
#include <windows.h>
Create the external entry point. You can check that it exists using depends.exe.
extern "C"
{
__declspec(dllexport) long entrypoint(long id)
{
#define CREATE_OBJECT(I, C, L, D) \
case SN::I##_##D##_entry: return (int) new C();
switch (id)
{
SN_APPLY_CURRENT_LIBRARY(APPLY_ENTRY, CREATE_OBJECT)
case -1:
default:
return 0;
}
}
}
The macros set up all the data needed.
namespace SN
{
bool loaded = false;
char * libraryPathArray[SN::LastLibrary];
#define DEFINE_LIBRARY_PATH(A, N, L) \
libraryPathArray[N##_library] = L;
static void LoadLibraryPaths()
{
SN_APPLY_LIBRARIES(DEFINE_LIBRARY_PATH, "")
}
typedef long(*f_entrypoint)(long id);
f_entrypoint libraryFunctionArray[LastLibrary - 1];
void InitlibraryFunctionArray()
{
for (long j = 0; j < LastLibrary; j++)
{
libraryFunctionArray[j] = 0;
}
#define DEFAULT_LIBRARY_ENTRY(A, N, L) \
libraryFunctionArray[N##_library] = &entrypoint;
SN_APPLY_CURRENT_LIBRARY(DEFAULT_LIBRARY_ENTRY, "")
}
enum SN::LibraryValues libraryForEntryPointArray[SN::LastEntry];
#define DEFINE_ENTRY_POINT_LIBRARY(I, C, L, D) \
libraryForEntryPointArray[I##_##D##_entry] = L##_library;
void LoadLibraryForEntryPointArray()
{
SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_POINT_LIBRARY)
}
enum SN::EntryValues defaultEntryArray[SN::LastEntry];
#define DEFINE_ENTRY_DEFAULT(I, C, L, D) \
defaultEntryArray[I##_##D##_entry] = I##_def_entry;
void LoadDefaultEntries()
{
SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_DEFAULT)
}
void Initialize()
{
if (!loaded)
{
loaded = true;
LoadLibraryPaths();
InitlibraryFunctionArray();
LoadLibraryForEntryPointArray();
LoadDefaultEntries();
}
}
long CallEntryPoint(long id, long interfaceId)
{
Initialize();
// assert(defaultEntryArray[id] == interfaceId, "Request to create an object for the wrong interface.")
enum SN::LibraryValues l = libraryForEntryPointArray[id];
f_entrypoint f = libraryFunctionArray[l];
if (!f)
{
HINSTANCE hGetProcIDDLL = LoadLibraryA(libraryPathArray[l]);
if (!hGetProcIDDLL) {
return NULL;
}
// resolve function address here
f = (f_entrypoint)GetProcAddress(hGetProcIDDLL, "entrypoint");
if (!f) {
return NULL;
}
libraryFunctionArray[l] = f;
}
return f(id);
}
}
Each library includes this "cpp" with a stub cpp for each library/executable. Any specific compiled header stuff.
#include "sn_pch.h"
Setup this library.
#define SN_APPLY_CURRENT_LIBRARY(L, A) \
L(A, sn, "sn.dll")
An include for the main cpp. I guess this cpp could be a .h. But there are different ways you could do this. This approach worked for me.
#include "../inc/sn_factory.cpp"
Another approach would be to deserialize into a java.util.Map
, and then just modify the Java Map
as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
You need to register the directory with Oracle. fopen takes the name of a directory object, not the path. For example:
(you may need to login as SYS to execute these)
CREATE DIRECTORY MY_DIR AS 'C:\';
GRANT READ ON DIRECTORY MY_DIR TO SCOTT;
Then, you can refer to it in the call to fopen:
execute sal_status('MY_DIR','vin1.txt');
For 32 bit it will return 32 and for 64 bit it will return 64
import struct
print(struct.calcsize("P") * 8)
Even tidier:
select string = replace(replace(replace(' select single spaces',' ','<>'),'><',''),'<>',' ')
Output:
select single spaces
It's strange because @ControllerAdvice should works, are you catching the correct Exception?
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ResponseBody
@ExceptionHandler(value = DataAccessException.class)
public String defaultErrorHandler(HttpServletResponse response, DataAccessException e) throws Exception {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//Json return
}
}
Also try to catch this exception in CorsFilter and send 500 error, something like this
@ExceptionHandler(DataAccessException.class)
@ResponseBody
public String handleDataException(DataAccessException ex, HttpServletResponse response) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//Json return
}
To lock whole workbook from opening, Thisworkbook.password
option can be used in VBA.
If you want to Protect Worksheets, then you have to first Lock the cells with option Thisworkbook.sheets.cells.locked = True
and then use the option Thisworkbook.sheets.protect password:="pwd"
.
Primarily search for these keywords: Thisworkbook.password
or Thisworkbook.Sheets.Cells.Locked
unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.
So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.
Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.
What you call "Two-Way SSL" is usually called TLS/SSL with client certificate authentication.
In a "normal" TLS connection to example.com only the client verifies that it is indeed communicating with the server for example.com. The server doesn't know who the client is. If the server wants to authenticate the client the usual thing is to use passwords, so a client needs to send a user name and password to the server, but this happens inside the TLS connection as part of an inner protocol (e.g. HTTP) it's not part of the TLS protocol itself. The disadvantage is that you need a separate password for every site because you send the password to the server. So if you use the same password on for example PayPal and MyPonyForum then every time you log into MyPonyForum you send this password to the server of MyPonyForum so the operator of this server could intercept it and try it on PayPal and can issue payments in your name.
Client certificate authentication offers another way to authenticate the client in a TLS connection. In contrast to password login, client certificate authentication is specified as part of the TLS protocol. It works analogous to the way the client authenticates the server: The client generates a public private key pair and submits the public key to a trusted CA for signing. The CA returns a client certificate that can be used to authenticate the client. The client can now use the same certificate to authenticate to different servers (i.e. you could use the same certificate for PayPal and MyPonyForum without risking that it can be abused). The way it works is that after the server has sent its certificate it asks the client to provide a certificate too. Then some public key magic happens (if you want to know the details read RFC 5246) and now the client knows it communicates with the right server, the server knows it communicates with the right client and both have some common key material to encrypt and verify the connection.