NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];
The name will be something like "Australia/Sydney", or "Europe/Lisbon".
Since it sounds like you might only care about the continent, that might be all you need.
You can create the manifest using ClickOnce Security Settings, and then disable it:
Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings
After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings
option
Open that file and change this line :
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will make the program require administrator privileges.
You should add id attribute to your image tag, like this:
<div id="d1">
<div class="c1">
<a href="#"><img id="img1" src="img1_on.gif"></a>
<a href="#"><img id="img2" src="img2_on.gif"></a>
</div>
</div>
then you can use this code to change the source of images:
$(document).ready(function () {
$("#img1").attr({ "src": "logo-ex-7.png" });
$("#img2").attr({ "src": "logo-ex-8.png" });
});
Could you use jQuery, since it's cross-browser compatible?
function isOnScreen(element)
{
var curPos = element.offset();
var curTop = curPos.top;
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
And then call the function using something like:
if(isOnScreen($('#myDivId'))) { /* Code here... */ };
Easy way: to do this by extending UITextField
extension UITextField {
func setPadding(left: CGFloat? = nil, right: CGFloat? = nil){
if let left = left {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: left, height: self.frame.size.height))
self.leftView = paddingView
self.leftViewMode = .always
}
if let right = right {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: right, height: self.frame.size.height))
self.rightView = paddingView
self.rightViewMode = .always
}
}
}
Then you can set padding to any edge this way:
textField.setPadding(left: 5, right: 5)
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
Use:
SELECT *
FROM `table`
WHERE INSTR(`column`, '{$needle}') > 0
Reference:
I got the same problem, but i find the answer in this page! it works for me, you can try it.
iconv -f cp936 -t utf-8
Bitmasks are used when you want to encode multiple layers of information in a single number.
So (assuming unix file permissions) if you want to store 3 levels of access restriction (read, write, execute) you could check for each level by checking the corresponding bit.
rwx
---
110
110 in base 2 translates to 6 in base 10.
So you can easily check if someone is allowed to e.g. read the file by and'ing the permission field with the wanted permission.
Pseudocode:
PERM_READ = 4
PERM_WRITE = 2
PERM_EXEC = 1
user_permissions = 6
if (user_permissions & PERM_READ == TRUE) then
// this will be reached, as 6 & 4 is true
fi
You need a working understanding of binary representation of numbers and logical operators to understand bit fields.
I am brand new to WindowBuilder, and, in fact, just getting back into Java after a few years, but I implemented "something", then thought I'd look it up and came across this thread.
I'm in the middle of testing this, so, based on being new to all this, I'm sure I must be missing something.
Here's what I did, where "runTxt" is a textbox and "runName" is a data member of the class:
public void focusGained(FocusEvent e) {
if (e.getSource() == runTxt) {
System.out.println("runTxt got focus");
runTxt.selectAll();
}
}
public void focusLost(FocusEvent e) {
if (e.getSource() == runTxt) {
System.out.println("runTxt lost focus");
if(!runTxt.getText().equals(runName))runName= runTxt.getText();
System.out.println("runText.getText()= " + runTxt.getText() + "; runName= " + runName);
}
}
Seems a lot simpler than what's here so far, and seems to be working, but, since I'm in the middle of writing this, I'd appreciate hearing of any overlooked gotchas. Is it an issue that the user could enter & leave the textbox w/o making a change? I think all you've done is an unnecessary assignment.
You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo
#one
{
background-color: #EEE;
margin: 62px 258px;
padding: 5px;
width: 200px;
position: relative;
}
#two
{
background-color: #F00;
display: inline-block;
height: 30px;
position: absolute;
width: 100px;
top:10px;
}?
Try:
var selectedVal;
for( i = 0; i < document.form_name.gender.length; i++ )
{
if(document.form_name.gender[i].checked)
selectedVal = document.form_name.gender[i].value; //male or female
break;
}
}
One more option, not exactly what you asked, but can be useful:
Go to Settings
-> Editor
-> File and code templates
-> Includes
tab (on the right). There is a template header for the new files, you can use the username here:
/**
* @author myname
*/
For system username use:
/**
* @author ${USER}
*/
From the javadocs..http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Path p1 = Paths.get("/tmp/foo");
is the same as
Path p4 = FileSystems.getDefault().getPath("/tmp/foo");
Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));
Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log");
In Windows, creates file C:\joe\logs\foo.log (assuming user home as C:\joe)
In Unix, creates file /u/joe/logs/foo.log (assuming user home as /u/joe)
Not all USB cables can transfer data. Try using a different USB cable if your device is charging, but doesn't establish a connection to your machine.
It seems trivial. But it's worth a try if each and every other solution that normally works, doesn't.
I recommend Vorlon, works like weinre. I like the UI of Vorlon, and it support SSL, my application is in HTTPS, I tried weinre with ngrok, ghostlab and vorlon, only vorlon works fine.
iOS 5 has implemented Custom Vibrations mode. So in some cases variable vibration is acceptable. The only thing is unknown what library deals with that (pretty sure not CoreTelephony) and if it is open for developers. So keep on searching.
If you want to do manually then You also can clear your user data by clicking “Clear Data”
button in Settings–>Applications–>Manage Aplications–>
YOUR APPLICATION
or Is there any other way to do that?
Then Download code here
I also had same problem but i have solved by adding 'Content-Type' : 'application/x-font-ttf' in response header for all .ttf files
I have tried this with your data and it is working :
%pyspark
import pandas as pd
from pyspark.sql import SQLContext
print sc
df = pd.read_csv("test.csv")
print type(df)
print df
sqlCtx = SQLContext(sc)
sqlCtx.createDataFrame(df).show()
I found the answer on the web:
Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.WriteText "special characters: äöüß"
fsT.SaveToFile sFileName, 2 'Save binary data To disk
Certainly not as I expected...
You can take a look at the source code .
DataFrame
has a private function _slice()
to slice the DataFrame
, and it allows the parameter axis
to determine which axis to slice. The __getitem__()
for DataFrame
doesn't set the axis while invoking _slice()
. So the _slice()
slice it by default axis 0.
You can take a simple experiment, that might help you:
print df._slice(slice(0, 2))
print df._slice(slice(0, 2), 0)
print df._slice(slice(0, 2), 1)
Use this way:
$selectOption = $_POST['taskOption'];
But it is always better to give values to your <option>
tags.
<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
String1.scan(/<([^>]*)>/).last.first
scan
creates an array which, for each <item>
in String1
contains the text between the <
and the >
in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last
gives you the last of those arrays and first
then gives you the string in it.
This line helps to write a file from an Array or String.
new PrintWriter(outputPath) { write(ArrayName.mkString("")); close }
For adding argument to delay function.
First setup a dictionary then add it as the userInfo. Unwrap the info with the timer as the argument.
let arg : Int = 42
let infoDict : [String : AnyObject] = ["argumentInt", arg]
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false)
Then in the called function
func functionHereWithArgument (timer : NSTimer)
{
if let userInfo = timer.userInfo as? Dictionary<String, AnyObject>
{
let argumentInt : Int = (userInfo[argumentInt] as! Int)
}
}
Here's a possibile solution (in Python):
Let's say you have a notebook with a file name, call it Notebook.ipynb. You are currently working in that notebook, and want to access other folders and files around it. Here's it's path:
import os
notebook_path = os.path.abspath("Notebook.ipynb")
In other words, just use the os module, and get the absolute path of your notebook (it's a file, too!). From there, use the os module and your path to navigate.
For example, if your train.csv is in a folder called 'Datasets', and the notebook is sitting right next to that folder, you could get the data like this:
train_csv = os.path.join(os.path.dirname(notebook_path), "Datasets/train.csv")
with open(train_csv) as file:
#....etc
The takeaway is that the notebook has a file name, and as long as your language supports pathname manipulations (e.g. the os module in Python) you can likely use the notebook filename.
Lastly, the reason your code fails is probably because you're either trying to access local files (like your Mac's 'Downloads' folder) when you're working in an online Notebook (like Kaggle, which hosts your environment for you, online and away from your Mac), or you moved or deleted something in that path. This is what the os module in Python is meant to do; it will find the file's path whether it's on your Mac or in a Kaggle server.
export **default** class MyComponentComponent
!Related issue that might fall under the title, if not the specific question:
I accidentally did a...
export default class MyComponentComponent {
... and that screwed things up too.
Why? VS Code added the import to my module when I put it into declarations
, but instead of...
import { MyComponentComponent } from '...';
it had
import MyComponentComponent from '...';
And that didn't map up downstream, assumedly since it wasn't "really" named anywhere with the default import.
export class MyComponentComponent {
No default
. Profit.
Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.
extension DateFormatter {
static var sharedDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
// Add your formatter configuration here
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
}
Usage:
let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
I think zeroclipboard is great. this version work with latest Flash 11: http://www.itjungles.com/javascript/javascript-easy-cross-browser-copy-to-clipboard-solution.
Go to dev.twitter.com and create an application. This will provide you with the credentials you need. Here is an implementation I've recently written with PHP and cURL.
<?php
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$oauth_access_token = "YOURVALUE";
$oauth_access_token_secret = "YOURVALUE";
$consumer_key = "YOURVALUE";
$consumer_secret = "YOURVALUE";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// Make requests
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
//print it out
print_r ($twitter_data);
?>
This can be run from the command line:
$ php <name of PHP script>.php
First, I see you're using an explicit $.parseJSON()
. If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return value and jQuery will automatically deserialize it for you too.
To iterate through the first item in the array you've got there, use code like this:
var firstItem = response.d[0];
for(key in firstItem) {
console.log(key + ':' + firstItem[key]);
}
If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d
and then use this code inside that outer loop.
You can try this to change the link background on hover
.nav > li > a:hover{
background-color:#FCC;
}
If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit
var thisIsObject= {
'Cow' : 'Moo',
'Cat' : 'Meow',
'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object
=> {'Cat' : 'Meow', 'Dog' : 'Bark'} //result
If you want to modify the current object, assign the returning object to the current object.
thisIsObject = _.omit(thisIsObject,'Cow');
With pure JavaScript, use:
delete thisIsObject['Cow'];
Another option with pure JavaScript.
thisIsObject.cow = undefined;
thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));
Another way to convert an Enum-Type to an int:
enum E
{
A = 1, /* index 0 */
B = 2, /* index 1 */
C = 4, /* index 2 */
D = 4 /* index 3, duplicate use of 4 */
}
void Main()
{
E e = E.C;
int index = Array.IndexOf(Enum.GetValues(e.GetType()), e);
// index is 2
E f = (E)(Enum.GetValues(e.GetType())).GetValue(index);
// f is E.C
}
More complex but independent from the INT values assigned to the enum values.
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
With VLC i'm able to transcode a live RTSP stream (mpeg4) to an HTTP stream in a OGG format (Vorbis/Theora). The quality is poor but the video work in Chrome 9. I have also tested with a trancoding in WEBM (VP8) but it's don't seem to work (VLC have the option but i don't know if it's really implemented for now..)
The first to have a doc on this should notify us ;)
If you care about getting coordinates based on an ellipsoid rather than a sphere, take a look at Geographic_coordinate_conversion - it gives the formulae. GEodetic Datum has the WGS84 constants you need for the conversion.
The formulae there also take into account the altitude relative to the reference ellipsoid surface (useful if you are getting altitude data from a GPS device).
When I get this kind of error I had to update the data type by a notch. For Example, if I have it as "tiny int" change it to "small int" ~ Nita
The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.
Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.
With ES2015/ES6 you can take advantage of Object.assign
which can replace $.extend()
or _.defaults()
function myFunc(requiredArg, options = {}) {
const defaults = {
message: 'Hello',
color: 'red',
importance: 1
};
const settings = Object.assign({}, defaults, options);
// do stuff
}
You can also use defaults arguments like this
function myFunc(requiredArg, { message: 'Hello', color: 'red', importance: 1 } = {}) {
// do stuff
}
Try to use anyMatch
of Lambda Expression. It is much better approach.
boolean idExists = tabPane.getTabs().stream()
.anyMatch(t -> t.getId().equals(idToCheck));
It's simple. For example:
<?php
function filePath($filePath)
{
$fileParts = pathinfo($filePath);
if (!isset($fileParts['filename']))
{
$fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));
}
return $fileParts;
}
$filePath = filePath('/www/htdocs/index.html');
print_r($filePath);
?>
The output will be:
Array
(
[dirname] => /www/htdocs
[basename] => index.html
[extension] => html
[filename] => index
)
Yeah in simulator. Some times it wont recognise the selector there is a bug it seems. Even i faced not for your code , then i just changed the action name (selector). It works
let buttonPuzzle:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
buttonPuzzle.backgroundColor = UIColor.greenColor()
buttonPuzzle.setTitle("Puzzle", forState: UIControlState.Normal)
buttonPuzzle.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
buttonPuzzle.tag = 22;
self.view.addSubview(buttonPuzzle)
Selector Function is Here:
func buttonAction(sender:UIButton!)
{
var btnsendtag:UIButton = sender
if btnsendtag.tag == 22 {
//println("Button tapped tag 22")
}
}
In Swift 3.0 to 4.0 it's as easy as typing this into your function:
self.dismiss(animated: true, completion: nil)
Or if you're in a navigation controller you can "pop" it:
self.navigationController?.popViewController(animated: true)
I think schemas are like a lot of new features (whether to SQL Server or any other software tool). You need to carefully evaluate whether the benefit of adding it to your development kit offsets the loss of simplicity in design and implementation.
It looks to me like schemas are roughly equivalent to optional namespaces. If you're in a situation where object names are colliding and the granularity of permissions is not fine enough, here's a tool. (I'd be inclined to say there might be design issues that should be dealt with at a more fundamental level first.)
The problem can be that, if it's there, some developers will start casually using it for short-term benefit; and once it's in there it can become kudzu.
So far I found this is a good and quick solution
//CPID[] is the array
string cps = "";
if (CPID.Length > 0)
{
foreach (var item in CPID)
{
cps += item.Trim() + ",";
}
}
//Use the string cps
you can do this very easy by using following in sudo vi /etc/nginx/sites-available/default
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _ your_domain;
location /health {
access_log off;
return 200 "healthy\n";
}
location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
}
Be careful with the syntax! Great Turtle used them interchangeably, but:
error_page 404 = /404.html;
Will return the 404.html page with a status code of 200 (because = has relayed that to this page)
error_page 404 /404.html;
Will return the 404.html page with a (the original) 404 error code.
https://serverfault.com/questions/295789/nginx-return-correct-headers-with-custom-error-documents
This is simple way to Display Div using:-
$("#musicinfo").show(); //or
$("#musicinfo").css({'display':'block'}); //or
$("#musicinfo").toggle("slow"); //or
$("#musicinfo").fadeToggle(); //or
Solution
Angular2 developed on the ground of modern technologies like TypeScript and ES6.
So you can just do let copy = Object.assign({}, myObject)
.
Object assign - nice examples.
For nested objects :
let copy = JSON.parse(JSON.stringify(myObject))
If i understand you correctly, (i probably don't)
'SELECT @RowCount = COUNT(*)
FROM dbo.Comm_Services
WHERE CompanyId = ' + CAST(@CompanyId AS CHAR) + '
AND ' + @condition
No, unfortunately this will not be possible because ConverterParameter
is not a DependencyProperty
so you won't be able to use bindings
But perhaps you could cheat and use a MultiBinding
with IMultiValueConverter
to pass in the 2 Tag
properties.
Using Java 8 you can do this in a very clean way:
String.join(delimiter, elements);
This works in three ways:
1) directly specifying the elements
String joined1 = String.join(",", "a", "b", "c");
2) using arrays
String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);
3) using iterables
List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);
Here is an elegant solution.
There is hidden property for each input element on the form that you can use to determine whether or not the value was changed. Each type of input has it's own property name. For example
text/textarea
it's defaultValueselect
it's defaultSelectcheckbox/radio
it's defaultCheckedHere is the example.
function bindFormChange($form) {
function touchButtons() {
var
changed_objects = [],
$observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');
changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
var
$input = $(this),
changed = false;
if ($input.is('input:text') || $input.is('textarea') ) {
changed = (($input).prop('defaultValue') != $input.val());
}
if (!changed && $input.is('select') ) {
changed = !$('option:selected', $input).prop('defaultSelected');
}
if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
changed = (($input).prop('defaultChecked') != $input.is(':checked'));
}
if (changed) {
return $input.attr('id');
}
}).toArray();
if (changed_objects.length) {
$observable_buttons.removeAttr('disabled')
} else {
$observable_buttons.attr('disabled', 'disabled');
}
};
touchButtons();
$('input, textarea, select', $form).each(function () {
var $input = $(this);
$input.on('keyup change', function () {
touchButtons();
});
});
};
Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.
$('form').each(function () {
bindFormChange($(this));
});
Implementation as a jQuery
plugin is here https://github.com/kulbida/jmodifiable
if we use the system given action bar following code works fine
getActionBar().setHomeButtonEnabled(true);
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
//do your action here.
break;
}
return true;
}
/[\W\S_]/
This creates a character class removing the word characters, space characters, and adding back the underscore character (as underscore is a "word" character). All that is left is the special characters. Capital letters represent the negation of their lowercase counterparts.
\W
will select all non "word" characters equivalent to [^a-zA-Z0-9_]
\S
will select all non "whitespace" characters equivalent to [ \t\n\r\f\v]
_
will select "_" because we negate it when using the \W
and need to add it back in
You don't have all digit characters in your string. So you have to split by space
QString Abcd = "123.5 Kb";
Abcd.split(" ")[0].toInt(); //convert the first part to Int
Abcd.split(" ")[0].toDouble(); //convert the first part to double
Abcd.split(" ")[0].toFloat(); //convert the first part to float
Update: I am updating an old answer. That was a straight forward answer to the specific question, with a strict assumption. However as noted by @DomTomCat in comments and @Mikhail in answer, In general one should always check whether the operation is successful or not. So using a boolean flag is necessary.
bool flag;
double v = Abcd.split(" ")[0].toDouble(&flag);
if(flag){
// use v
}
Also if you are taking that string as user input, then you should also be doubtful about whether the string is really splitable with space. If there is a possibility that the assumption may break then a regex verifier is more preferable. A regex like the following will extract the floating point value and the prefix character of 'b'. Then you can safely convert the captured strings to double.
([0-9]*\.?[0-9]+)\s+(\w[bB])
You can have an utility function like the following
QPair<double, QString> split_size_str(const QString& str){
QRegExp regex("([0-9]*\\.?[0-9]+)\\s+(\\w[bB])");
int pos = regex.indexIn(str);
QStringList captures = regex.capturedTexts();
if(captures.count() > 1){
double value = captures[1].toDouble(); // should succeed as regex matched
QString unit = captures[2]; // should succeed as regex matched
return qMakePair(value, unit);
}
return qMakePair(0.0f, QString());
}
You can create a list of lists
public class MultiDimList: List<List<string>> { }
or a Dictionary of key-accessible Lists
public class MultiDimDictList: Dictionary<string, List<int>> { }
MultiDimDictList myDicList = new MultiDimDictList ();
myDicList.Add("ages", new List<int>());
myDicList.Add("Salaries", new List<int>());
myDicList.Add("AccountIds", new List<int>());
Generic versions, to implement suggestion in comment from @user420667
public class MultiDimList<T>: List<List<T>> { }
and for the dictionary,
public class MultiDimDictList<K, T>: Dictionary<K, List<T>> { }
// to use it, in client code
var myDicList = new MultiDimDictList<string, int> ();
myDicList.Add("ages", new List<T>());
myDicList["ages"].Add(23);
myDicList["ages"].Add(32);
myDicList["ages"].Add(18);
myDicList.Add("salaries", new List<T>());
myDicList["salaries"].Add(80000);
myDicList["salaries"].Add(100000);
myDicList.Add("accountIds", new List<T>());
myDicList["accountIds"].Add(321123);
myDicList["accountIds"].Add(342653);
or, even better, ...
public class MultiDimDictList<K, T>: Dictionary<K, List<T>>
{
public void Add(K key, T addObject)
{
if(!ContainsKey(key)) Add(key, new List<T>());
if (!base[key].Contains(addObject)) base[key].Add(addObject);
}
}
// and to use it, in client code
var myDicList = new MultiDimDictList<string, int> ();
myDicList.Add("ages", 23);
myDicList.Add("ages", 32);
myDicList.Add("ages", 18);
myDicList.Add("salaries", 80000);
myDicList.Add("salaries", 110000);
myDicList.Add("accountIds", 321123);
myDicList.Add("accountIds", 342653);
EDIT: to include an Add() method for nested instance:
public class NestedMultiDimDictList<K, K2, T>:
MultiDimDictList<K, MultiDimDictList<K2, T>>:
{
public void Add(K key, K2 key2, T addObject)
{
if(!ContainsKey(key)) Add(key,
new MultiDimDictList<K2, T>());
if (!base[key].Contains(key2))
base[key].Add(key2, addObject);
}
}
Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:
if grep -q "poet" $file_name
then
echo "poet was found in $file_name"
fi
============
Here are some commonly used tests:
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
-h FILE
FILE exists and is a symbolic link (same as -L)
-r FILE
FILE exists and is readable
-s FILE
FILE exists and has a size greater than zero
-w FILE
FILE exists and is writable
-x FILE
FILE exists and is executable
-z STRING
the length of STRING is zero
Example:
if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
echo "$file_name exists and $used_var is not empty"
fi
First of all, never use a for in
loop to enumerate over an array. Never. Use good old for(var i = 0; i<arr.length; i++)
.
The reason behind this is the following: each object in JavaScript has a special field called prototype
. Everything you add to that field is going to be accessible on every object of that type. Suppose you want all arrays to have a cool new function called filter_0
that will filter zeroes out.
Array.prototype.filter_0 = function() {
var res = [];
for (var i = 0; i < this.length; i++) {
if (this[i] != 0) {
res.push(this[i]);
}
}
return res;
};
console.log([0, 5, 0, 3, 0, 1, 0].filter_0());
//prints [5,3,1]
This is a standard way to extend objects and add new methods. Lots of libraries do this.
However, let's look at how for in
works now:
var listeners = ["a", "b", "c"];
for (o in listeners) {
console.log(o);
}
//prints:
// 0
// 1
// 2
// filter_0
Do you see? It suddenly thinks filter_0 is another array index. Of course, it is not really a numeric index, but for in
enumerates through object fields, not just numeric indexes. So we're now enumerating through every numeric index and filter_0
. But filter_0
is not a field of any particular array object, every array object has this property now.
Luckily, all objects have a hasOwnProperty
method, which checks if this field really belongs to the object itself or if it is simply inherited from the prototype chain and thus belongs to all the objects of that type.
for (o in listeners) {
if (listeners.hasOwnProperty(o)) {
console.log(o);
}
}
//prints:
// 0
// 1
// 2
Note, that although this code works as expected for arrays, you should never, never, use for in
and for each in
for arrays. Remember that for in
enumerates the fields of an object, not array indexes or values.
var listeners = ["a", "b", "c"];
listeners.happy = "Happy debugging";
for (o in listeners) {
if (listeners.hasOwnProperty(o)) {
console.log(o);
}
}
//prints:
// 0
// 1
// 2
// happy
Use the strong element, that is it's purpose:
<div id="content">
<p><strong>First Word</strong> rest of paragraph.</p>
</div>
Then create a style for it in your style sheet.
#content p strong
{
font-size: 14pt;
}
Here's how I fixed it:
nltk.download()
.The download graphic window opened and all the packages got installed.You need jackson dependency for this serialization and deserialization.
Add this dependency:
Gradle:
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.4")
Maven:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
After that, You need to tell Jackson ObjectMapper to use JavaTimeModule. To do that, Autowire ObjectMapper in the main class and register JavaTimeModule to it.
import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@SpringBootApplication
public class MockEmployeeApplication {
@Autowired
private ObjectMapper objectMapper;
public static void main(String[] args) {
SpringApplication.run(MockEmployeeApplication.class, args);
}
@PostConstruct
public void setUp() {
objectMapper.registerModule(new JavaTimeModule());
}
}
After that, Your LocalDate and LocalDateTime should be serialized and deserialized correctly.
The problem is that there is an in-browser print dialogue within the popup window. If you call window.close()
immediately then the dialogue is not seen by the user. The user needs to click "Print" within the dialogue. This is not the same as on other browsers where the print dialogue is part of the OS, and blocks the window.close()
until dismissed - on Chrome, it's part of Chrome, not the OS.
This is the code I used, in a little popup window that is created by the parent window:
var is_chrome = function () { return Boolean(window.chrome); }
window.onload = function() {
if(is_chrome){
/*
* These 2 lines are here because as usual, for other browsers,
* the window is a tiny 100x100 box that the user will barely see.
* On Chrome, it needs to be big enough for the dialogue to be read
* (NB, it also includes a page preview).
*/
window.moveTo(0,0);
window.resizeTo(640, 480);
// This line causes the print dialogue to appear, as usual:
window.print();
/*
* This setTimeout isn't fired until after .print() has finished
* or the dialogue is closed/cancelled.
* It doesn't need to be a big pause, 500ms seems OK.
*/
setTimeout(function(){
window.close();
}, 500);
} else {
// For other browsers we can do things more briefly:
window.print();
window.close();
}
}
A nice trick to use in place of the various print formats:
(1) Pad with spaces to the right:
('hi' + ' ')[:8]
(2) Pad with leading zeros on the left:
('0000' + str(2))[-4:]
Well System.Reflection.MethodBase.GetCurrentMethod().Name
is not a very good choice 'cause it will just display the method name without additional information.
Like for string MyMethod(string str)
the above property will return just MyMethod
which is hardly adequate.
It is better to use System.Reflection.MethodBase.GetCurrentMethod().ToString()
which will return the entire method signature...
Go to the Eclipse base folder ? open eclipse.ini ? you will find the below line at line no 4:
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316 plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120913-144807
As you can see, line 1 is of 64-bit Eclipse. It contains x86_64 and line 2 is of 32-bit Eclipse. It contains x_86.
For 32-bit Eclipse only x86 will be present and for 64-bit Eclipse x86_64 will be present.
Negative numbers mean that you count from the right instead of the left. So, list[-1]
refers to the last element, list[-2]
is the second-last, and so on.
style is accordingly vis css. An example
<h1 class="mynotsoboldtitle">Im not bold</h1>
<style>
.mynotsoboldtitle { font-weight:normal; }
</style>
Most easiest way is to use ViewTreeObserver, if you directly use .height or .width you get values as 0, due to views are not have size until they draw on our screen. Following example will show how to use ViewTreeObserver
ViewTreeObserver viewTreeObserver = YOUR_VIEW_TO_MEASURE.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
YOUR_VIEW_TO_MEASURE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int viewHeight = YOUR_VIEW_TO_MEASURE.getHeight();
int viewWeight = YOUR_VIEW_TO_MEASURE.getWidth();
}
});
}
if you need to use this on method, use like this and to save the values you can use globle variables.
continue
must be inside a loop Otherwise it showsThe error below:
Continue outside the loop
CrossAlignment.center is using the Width of the 'Child Widget'
to center itself and hence gets rendered at the start of the page.
When the Column is centered within the page body's 'Center Container'
, the CrossAlignment.center uses page body's 'Center' as reference and renders the widget at the center of the page
Code
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
title:"DynamicWidgetApp",
home:DynamicWidgetApp(),
));
class DynamicWidgetApp extends StatefulWidget{
@override
DynamicWidgetAppState createState() => DynamicWidgetAppState();
}
class DynamicWidgetAppState extends State<DynamicWidgetApp>{
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
//Removing body:Center will change the reference
// and render the widget at the start of the page
child: Column(
mainAxisAlignment : MainAxisAlignment.center,
crossAxisAlignment : CrossAxisAlignment.center,
children: [
Text("My Centered Widget"),
]
),
),
floatingActionButton: FloatingActionButton(
// onPressed: ,
child : Icon(Icons.add),
),
);
}
}
My take on this for future people watching this:
This could also happen if you're using: <?
instead of <?php
.
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
Please refer to this SO Post
example of a regular expression in jquery for phone numbers
/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
are supported
Font Squirrel has a wonderful web font generator.
I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.
For those using newer versions of java: jhat
has been removed since Java 9. Source: https://www.infoq.com/news/2015/12/OpenJDK-9-removal-of-HPROF-jhat/
That same article recommends using Java VisualVM instead.
Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser
RSA Public Key
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
Encrypted Private Key
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----
CRL
-----BEGIN X509 CRL-----
-----END X509 CRL-----
CRT
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
CSR
-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----
NEW CSR
-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----
PEM
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
PKCS7
-----BEGIN PKCS7-----
-----END PKCS7-----
PRIVATE KEY
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
DSA KEY
-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----
Elliptic Curve
-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----
PGP Private Key
-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----
PGP Public Key
-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----
I would try to solve this without VBA. Just select this space and use replace (change to nothing) on that worksheet you're trying to get rid off those spaces.
If you really want to use VBA I believe you could select first character
strSpace = left(range("A1").Value,1)
and use replace function in VBA the same way
Range("A1").Value = Replace(Range("A1").Value, strSpace, "")
or
for each cell in selection.cells
cell.value = replace(cell.value, strSpace, "")
next
Based on the answer by Adam Boduch, I wrote this function which compares two objects in the deepest possible sense, returning paths that have different values as well as paths missing from one or the other object.
The code was not written with efficiency in mind, and improvements in that regard are most welcome, but here is the basic form:
var compare = function (a, b) {
var result = {
different: [],
missing_from_first: [],
missing_from_second: []
};
_.reduce(a, function (result, value, key) {
if (b.hasOwnProperty(key)) {
if (_.isEqual(value, b[key])) {
return result;
} else {
if (typeof (a[key]) != typeof ({}) || typeof (b[key]) != typeof ({})) {
//dead end.
result.different.push(key);
return result;
} else {
var deeper = compare(a[key], b[key]);
result.different = result.different.concat(_.map(deeper.different, (sub_path) => {
return key + "." + sub_path;
}));
result.missing_from_second = result.missing_from_second.concat(_.map(deeper.missing_from_second, (sub_path) => {
return key + "." + sub_path;
}));
result.missing_from_first = result.missing_from_first.concat(_.map(deeper.missing_from_first, (sub_path) => {
return key + "." + sub_path;
}));
return result;
}
}
} else {
result.missing_from_second.push(key);
return result;
}
}, result);
_.reduce(b, function (result, value, key) {
if (a.hasOwnProperty(key)) {
return result;
} else {
result.missing_from_first.push(key);
return result;
}
}, result);
return result;
}
You can try the code using this snippet (running in full page mode is recommended):
var compare = function (a, b) {_x000D_
_x000D_
var result = {_x000D_
different: [],_x000D_
missing_from_first: [],_x000D_
missing_from_second: []_x000D_
};_x000D_
_x000D_
_.reduce(a, function (result, value, key) {_x000D_
if (b.hasOwnProperty(key)) {_x000D_
if (_.isEqual(value, b[key])) {_x000D_
return result;_x000D_
} else {_x000D_
if (typeof (a[key]) != typeof ({}) || typeof (b[key]) != typeof ({})) {_x000D_
//dead end._x000D_
result.different.push(key);_x000D_
return result;_x000D_
} else {_x000D_
var deeper = compare(a[key], b[key]);_x000D_
result.different = result.different.concat(_.map(deeper.different, (sub_path) => {_x000D_
return key + "." + sub_path;_x000D_
}));_x000D_
_x000D_
result.missing_from_second = result.missing_from_second.concat(_.map(deeper.missing_from_second, (sub_path) => {_x000D_
return key + "." + sub_path;_x000D_
}));_x000D_
_x000D_
result.missing_from_first = result.missing_from_first.concat(_.map(deeper.missing_from_first, (sub_path) => {_x000D_
return key + "." + sub_path;_x000D_
}));_x000D_
return result;_x000D_
}_x000D_
}_x000D_
} else {_x000D_
result.missing_from_second.push(key);_x000D_
return result;_x000D_
}_x000D_
}, result);_x000D_
_x000D_
_.reduce(b, function (result, value, key) {_x000D_
if (a.hasOwnProperty(key)) {_x000D_
return result;_x000D_
} else {_x000D_
result.missing_from_first.push(key);_x000D_
return result;_x000D_
}_x000D_
}, result);_x000D_
_x000D_
return result;_x000D_
}_x000D_
_x000D_
var a_editor = new JSONEditor($('#a')[0], {_x000D_
name: 'a',_x000D_
mode: 'code'_x000D_
});_x000D_
var b_editor = new JSONEditor($('#b')[0], {_x000D_
name: 'b',_x000D_
mode: 'code'_x000D_
});_x000D_
_x000D_
var a = {_x000D_
same: 1,_x000D_
different: 2,_x000D_
missing_from_b: 3,_x000D_
missing_nested_from_b: {_x000D_
x: 1,_x000D_
y: 2_x000D_
},_x000D_
nested: {_x000D_
same: 1,_x000D_
different: 2,_x000D_
missing_from_b: 3_x000D_
}_x000D_
}_x000D_
_x000D_
var b = {_x000D_
same: 1,_x000D_
different: 99,_x000D_
missing_from_a: 3,_x000D_
missing_nested_from_a: {_x000D_
x: 1,_x000D_
y: 2_x000D_
},_x000D_
nested: {_x000D_
same: 1,_x000D_
different: 99,_x000D_
missing_from_a: 3_x000D_
}_x000D_
}_x000D_
_x000D_
a_editor.set(a);_x000D_
b_editor.set(b);_x000D_
_x000D_
var result_editor = new JSONEditor($('#result')[0], {_x000D_
name: 'result',_x000D_
mode: 'view'_x000D_
});_x000D_
_x000D_
var do_compare = function() {_x000D_
var a = a_editor.get();_x000D_
var b = b_editor.get();_x000D_
result_editor.set(compare(a, b));_x000D_
}
_x000D_
#objects {} #objects section {_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
#objects section h1 {_x000D_
background: #444;_x000D_
color: white;_x000D_
font-family: monospace;_x000D_
display: inline-block;_x000D_
margin: 0;_x000D_
padding: 5px;_x000D_
}_x000D_
.jsoneditor-outer, .ace_editor {_x000D_
min-height: 230px !important;_x000D_
}_x000D_
button:hover {_x000D_
background: orangered;_x000D_
}_x000D_
button {_x000D_
cursor: pointer;_x000D_
background: red;_x000D_
color: white;_x000D_
text-align: left;_x000D_
font-weight: bold;_x000D_
border: 5px solid crimson;_x000D_
outline: 0;_x000D_
padding: 10px;_x000D_
margin: 10px 0px;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.5.10/jsoneditor.min.css" rel="stylesheet" />_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.5.10/jsoneditor.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="objects">_x000D_
<section>_x000D_
<h1>a (first object)</h1>_x000D_
<div id="a"></div>_x000D_
</section>_x000D_
<section>_x000D_
<h1>b (second object)</h1>_x000D_
<div id="b"></div>_x000D_
</section>_x000D_
<button onClick="do_compare()">compare</button>_x000D_
<section>_x000D_
<h1>result</h1>_x000D_
<div id="result"></div>_x000D_
</section>_x000D_
</div>
_x000D_
Delete the jars under system32 for windows. Delete the jars under C:\Program Files\Common Files\Oracle
Edit the environment variable set JAVA_HOME and SET PATH to bin
Does the user that you are using to connect to the database (user A
in this example) have SELECT
access on the objects in the PCT
schema? Assuming that A
does not have this access, you would get the "table or view does not exist" error.
Most likely, you need your DBA to grant user A
access to whatever tables in the PCT
schema that you need. Something like
GRANT SELECT ON pct.pi_int
TO a;
Once that is done, you should be able to refer to the objects in the PCT
schema using the syntax pct.pi_int
as you demonstrated initially in your question. The bracket syntax approach will not work.
Improved Crop image functionality in PHP on the fly.
http://www.example.com/cropimage.php?filename=a.jpg&newxsize=100&newysize=200&constrain=1
Code in cropimage.php
$basefilename = @basename(urldecode($_REQUEST['filename']));
$path = 'images/';
$outPath = 'crop_images/';
$saveOutput = false; // true/false ("true" if you want to save images in out put folder)
$defaultImage = 'no_img.png'; // change it with your default image
$basefilename = $basefilename;
$w = $_REQUEST['newxsize'];
$h = $_REQUEST['newysize'];
if ($basefilename == "") {
$img = $path . $defaultImage;
$percent = 100;
} else {
$img = $path . $basefilename;
$len = strlen($img);
$ext = substr($img, $len - 3, $len);
$img2 = substr($img, 0, $len - 3) . strtoupper($ext);
if (!file_exists($img)) $img = $img2;
if (file_exists($img)) {
$percent = @$_GET['percent'];
$constrain = @$_GET['constrain'];
$w = $w;
$h = $h;
} else if (file_exists($path . $basefilename)) {
$img = $path . $basefilename;
$percent = $_GET['percent'];
$constrain = $_GET['constrain'];
$w = $w;
$h = $h;
} else {
$img = $path . 'no_img.png'; // change with your default image
$percent = @$_GET['percent'];
$constrain = @$_GET['constrain'];
$w = $w;
$h = $h;
}
}
// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];
if ($percent > 0) {
// calculate resized height and width if percent is defined
$percent = $percent * 0.01;
$w = $sw * $percent;
$h = $sh * $percent;
} else {
if (isset ($w) AND !isset ($h)) {
// autocompute height if only width is set
$h = (100 / ($sw / $w)) * .01;
$h = @round($sh * $h);
} elseif (isset ($h) AND !isset ($w)) {
// autocompute width if only height is set
$w = (100 / ($sh / $h)) * .01;
$w = @round($sw * $w);
} elseif (isset ($h) AND isset ($w) AND isset ($constrain)) {
// get the smaller resulting image dimension if both height
// and width are set and $constrain is also set
$hx = (100 / ($sw / $w)) * .01;
$hx = @round($sh * $hx);
$wx = (100 / ($sh / $h)) * .01;
$wx = @round($sw * $wx);
if ($hx < $h) {
$h = (100 / ($sw / $w)) * .01;
$h = @round($sh * $h);
} else {
$w = (100 / ($sh / $h)) * .01;
$w = @round($sw * $w);
}
}
}
$im = @ImageCreateFromJPEG($img) or // Read JPEG Image
$im = @ImageCreateFromPNG($img) or // or PNG Image
$im = @ImageCreateFromGIF($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
if (!$im) {
// We get errors from PHP's ImageCreate functions...
// So let's echo back the contents of the actual image.
readfile($img);
} else {
// Create the resized image destination
$thumb = @ImageCreateTrueColor($w, $h);
// Copy from image source, resize it, and paste to image destination
@ImageCopyResampled($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
//Other format imagepng()
if ($saveOutput) { //Save image
$save = $outPath . $basefilename;
@ImageJPEG($thumb, $save);
} else { // Output resized image
header("Content-type: image/jpeg");
@ImageJPEG($thumb);
}
}
@HostListener('window:click', ['$event']) onClick(event){ }
check this below link to detect CapsLock on click, keyup and keydown on current window. No need to add any event in html doc
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
You could also use Spring's UriUtils
Either use a real fully qualified domain name (like dev.yourdomain.com
) that pointing to 127.0.0.1
or try editing the proper hosts file (usually /etc/hosts in *nix environments).
use the val() function
Here are two functions that may help if your backup is corrupted, or you have a few partially corrupted backups as well (this may happen if you backup the corrupted objects).
Run both in the repo you're trying to recover.
Standard warning: only use if you're really desperate and you have backed up your (corrupted) repo. This might not resolve anything, but at least should highlight the level of corruption.
fsck_rm_corrupted() {
corrupted='a'
while [ "$corrupted" ]; do
corrupted=$( \
git fsck --full --no-dangling 2>&1 >/dev/null \
| grep 'stored in' \
| sed -r 's:.*(\.git/.*)\).*:\1:' \
)
echo "$corrupted"
rm -f "$corrupted"
done
}
if [ -z "$1" ] || [ ! -d "$1" ]; then
echo "'$1' is not a directory. Please provide the directory of the git repo"
exit 1
fi
pushd "$1" >/dev/null
fsck_rm_corrupted
popd >/dev/null
and
unpack_rm_corrupted() {
corrupted='a'
while [ "$corrupted" ]; do
corrupted=$( \
git unpack-objects -r < "$1" 2>&1 >/dev/null \
| grep 'stored in' \
| sed -r 's:.*(\.git/.*)\).*:\1:' \
)
echo "$corrupted"
rm -f "$corrupted"
done
}
if [ -z "$1" ] || [ ! -d "$1" ]; then
echo "'$1' is not a directory. Please provide the directory of the git repo"
exit 1
fi
for p in $1/objects/pack/pack-*.pack; do
echo "$p"
unpack_rm_corrupted "$p"
done
You can scale the image with pygame.transform.scale
:
import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))
You can then get the bounding rectangle of picture
with
rect = picture.get_rect()
and move the picture with
rect = rect.move((x, y))
screen.blit(picture, rect)
where screen
was set with something like
screen = pygame.display.set_mode((1600, 900))
To allow your widgets to adjust to various screen sizes, you could make the display resizable:
import os
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
Your best bet to start is to use ?str()
. To explore some examples, let's make some data:
set.seed(3221) # this makes the example exactly reproducible
my.data <- data.frame(y=rnorm(5),
x1=c(1:5),
x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
X3=letters[1:5])
@Wilmer E Henao H's solution is very streamlined:
sapply(my.data, class)
y x1 x2 X3
"numeric" "integer" "logical" "factor"
Using str()
gets you that information plus extra goodies (such as the levels of your factors and the first few values of each variable):
str(my.data)
'data.frame': 5 obs. of 4 variables:
$ y : num 1.03 1.599 -0.818 0.872 -2.682
$ x1: int 1 2 3 4 5
$ x2: logi TRUE TRUE FALSE FALSE FALSE
$ X3: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
@Gavin Simpson's approach is also streamlined, but provides slightly different information than class()
:
sapply(my.data, typeof)
y x1 x2 X3
"double" "integer" "logical" "integer"
For more information about class
, typeof
, and the middle child, mode
, see this excellent SO thread: A comprehensive survey of the types of things in R. 'mode' and 'class' and 'typeof' are insufficient.
Use an image loading library like Picasso or Glide. Using these libraries will prevent crashes in the future.
From https://idlebox.net/2010/apidocs/gdb-7.0.zip/gdb_9.html
The values of arguments that were not saved in their stack frames are shown as `value optimized out'.
Im guessing you compiled with -O(somevalue) and are accessing variables a,b,c in a function where optimization has occurred.
In C#, the For loop is slightly faster.
For loop average about 2.95 to 3.02 ms.
The While loop averaged about 3.05 to 3.37 ms.
Quick little console app to prove:
class Program
{
static void Main(string[] args)
{
int max = 1000000000;
Stopwatch stopWatch = new Stopwatch();
if (args.Length == 1 && args[0].ToString() == "While")
{
Console.WriteLine("While Loop: ");
stopWatch.Start();
WhileLoop(max);
stopWatch.Stop();
DisplayElapsedTime(stopWatch.Elapsed);
}
else
{
Console.WriteLine("For Loop: ");
stopWatch.Start();
ForLoop(max);
stopWatch.Stop();
DisplayElapsedTime(stopWatch.Elapsed);
}
}
private static void WhileLoop(int max)
{
int i = 0;
while (i <= max)
{
//Console.WriteLine(i);
i++;
};
}
private static void ForLoop(int max)
{
for (int i = 0; i <= max; i++)
{
//Console.WriteLine(i);
}
}
private static void DisplayElapsedTime(TimeSpan ts)
{
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime, "RunTime");
}
}
For me work, first review
php -m
php -version
Later install the extension
apt-get update
apt-get install php7.2-zip
systemctl restart apache2
CSS is not HTML.
is a named character reference in HTML; equivalent to the decimal numeric character reference  
. 160 is the decimal code point of the NO-BREAK SPACE
character in Unicode (or UCS-2; see the HTML 4.01 Specification). The hexadecimal representation of that code point is U+00A0 (160 = 10 × 161 + 0 × 160). You will find that in the Unicode Code Charts and Character Database.
In CSS you need to use a Unicode escape sequence for such characters, which is based on the hexadecimal value of the code point of a character. So you need to write
.breadcrumbs a:before {
content: '\a0';
}
This works as long as the escape sequence comes last in a string value. If characters follow, there are two ways to avoid misinterpretation:
a) (mentioned by others) Use exactly six hexadecimal digits for the escape sequence:
.breadcrumbs a:before {
content: '\0000a0foo';
}
b) Add one white-space (e. g., space) character after the escape sequence:
.breadcrumbs a:before {
content: '\a0 foo';
}
(Since f
is a hexadecimal digit, \a0f
would otherwise mean GURMUKHI LETTER EE
here, or ? if you have a suitable font.)
The delimiting white-space will be ignored, and this will be displayed foo
, where the displayed space here would be a NO-BREAK SPACE
character.
The white-space approach ('\a0 foo'
) has the following advantages over the six-digit approach ('\0000a0foo'
):
Thus, to display a space after an escaped character, use two spaces in the stylesheet –
.breadcrumbs a:before {
content: '\a0 foo';
}
– or make it explicit:
.breadcrumbs a:before {
content: '\a0\20 foo';
}
See CSS 2.1, section "4.1.3 Characters and case" for details.
/* Adding the script tag to the head as suggested before */
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "http://code.jquery.com/jquery-2.2.1.min.js";
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = handler;
script.onload = handler;
// Fire the loading
head.appendChild(script);
function handler(){
console.log('jquery added :)');
}
I know that I have arrived after 4 years and am too late but I think I have another way that someone can use. I had used getchar()
Function like this:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//I had putten the main Function Bellow this function.
//d for asking string,f is pointer to the string pointer
void GetStr(char *d,char **f)
{
printf("%s",d);
for(int i =0;1;i++)
{
if(i)//I.e if i!=0
*f = (char*)realloc((*f),i+1);
else
*f = (char*)malloc(i+1);
(*f)[i]=getchar();
if((*f)[i] == '\n')
{
(*f)[i]= '\0';
break;
}
}
}
int main()
{
char *s =NULL;
GetStr("Enter the String:- ",&s);
printf("Your String:- %s \nAnd It's length:- %lu\n",s,(strlen(s)));
free(s);
}
here is the sample run for this program:-
Enter the String:- I am Using Linux Mint XFCE 18.2 , eclispe CDT and GCC7.2 compiler!!
Your String:- I am Using Linux Mint XFCE 18.2 , eclispe CDT and GCC7.2 compiler!!
And It's length:- 67
In my case there was a conflict in the namespaces , I have:
using System.Web.Mvc;
and
using System.Collections.Generic;
I explicitly want to use the Mvc one so I declared it as :
new System.Web.Mvc.SelectList(...)
The code can be cleaned up, but if you are using a list to store your tuples, any such lookup will be O(N).
If lookup speed is important, you should use a dict
to store your tuples. The key should be the 0th element of your tuples, since that's what you're searching on. You can easily create a dict from your list:
my_dict = dict(my_list)
Then, (VALUE, my_dict[VALUE])
will give you your matching tuple (assuming VALUE
exists).
if the possible values are integers you can bunch up cases. Otherwise, use ifs.
var api, tem;
switch(liCount){
case 0:
tem= 'start';
break;
case 1: case 2: case 3: case 4: case 5:
tem= 'upload1Row';
break;
case 6: case 7: case 8: case 9: case 10:
tem= 'upload2Rows';
break;
default:
break;
}
if(tem) setLayoutState((tem);
api= $('#UploadList').data('jsp');
api.reinitialise();
The JSON standard requires double quotes and will not accept single quotes, nor will the parser.
If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"')
and you should end up with valid JSON.
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).
Setting overflow: hidden
on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.
Why JSON RPC:
In case of REST APIs, we have to define a controller for each functionality/method we might need. As a result if we have 10 methods that we want accessible to a client, we have to write 10 controllers to interface the client's request to a particular method.
Another factor is, even though we have different controllers for each method/functionality, the client has to remember wether to use POST or GET. This complicates things further. On top of that to send data, one has to set the content type of the request if POST is used.
In case of JSON RPC, things are greatly simplified because most JSONRPC servers operate on POST HTTP methods and the content type is always application/json. This takes the load off of remembering to use proper HTTP method and content settings on client side.
One doesn't have to create separate controllers for different methods/functionalities the server wants to expose to a client.
Why REST:
You have separate URLs for different functionality the server wants to expose to client side. As a result, you can embed these urls.
Most of these points are debatable and completely depend upon the need of a person.
Others have already given great explanations regarding why you can not (and should not!) be able to add items to an IEnumerable
. I will only add that if you are looking to continue coding to an interface that represents a collection and want an add method, you should code to ICollection
or IList
. As an added bonanza, these interfaces implement IEnumerable
.
ob_start(); // turns on output buffering
$foo->bar(); // all output goes only to buffer
ob_clean(); // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents(); // buffer content is now an empty string
ob_end_clean(); // turn off output buffering
Buffers can be nested, so while one buffer is active, another ob_start()
activates a new buffer. So ob_end_flush()
and ob_flush()
are not really sending the buffer to the output, but to the parent buffer. And only when there is no parent buffer, contents is sent to browser or terminal.
Nicely explained here: https://phpfashion.com/everything-about-output-buffering-in-php
DATE_FORMAT(column name, '%Y-%m-%d %T') as dtime
Use this to avoid the error. It return the date in string format and then you can get it as a string.
resultset.getString("dtime");
This actually does NOT work. Even though you call getString. Internally mysql still tries to convert it to date first.
at com.mysql.jdbc.ResultSetImpl.getDateFromString(ResultSetImpl.java:2270)
~[mysql-connector-java-5.1.15.jar:na] at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5743)
~[mysql-connector-java-5.1.15.jar:na] at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5576)
~[mysql-connector-java-5.1.15.jar:na]
The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.
Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).
The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.
In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.
If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.
i think this is enough to get month name when u have date.
SELECT DATENAME(month ,GETDATE())
If it is possible to read the input file more than once (your problem statement doesn't say it can't), the following should work. It is described in Benchley's book "Programming Perls." If we store each number in 8 bytes we can store 250,000 numbers in one megabyte. Use a program that makes 40 passes over the input file. On the first pass it reads into memory any integer between 0 and 249,999, sorts the (at most) 250,000 integers and writes them to the output file. The second pass sorts the integers from 250,000 to 499,999 and so on to the 40th pass, which sorts 9,750,000 to 9,999,999.
Look at the widgets documentation. Basically it would look like:
q = forms.CharField(label='search',
widget=forms.TextInput(attrs={'placeholder': 'Search'}))
More writing, yes, but the separation allows for better abstraction of more complicated cases.
You can also declare a widgets
attribute containing a <field name> => <widget instance>
mapping directly on the Meta
of your ModelForm
sub-class.
I just wanted to check if the browser was IE11 or older, because well, they're crap.
function isCrappyIE() {
var ua = window.navigator.userAgent;
var crappyIE = false;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {// IE 10 or older => return version number
crappyIE = true;
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {// IE 11 => return version number
crappyIE = true;
}
return crappyIE;
}
if(!isCrappyIE()){console.table('not a crappy browser);}
You can do this:
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
and most of it will work (although MS support will tell you that doing this is not supported because it bypasses RBAC).
I've seen issues with some cmdlets (specifically enable/disable UMmailbox) not working with just the snapin loaded.
In Exchange 2010, they basically don't support using Powershell outside of the the implicit remoting environment of an actual EMS shell.
I agree with Cat Plus Plus's answer. However, if you know this will only be used on Unix-like OSes, you can use external calls to the shell commands mkdir
, chmod
, and chown
. Make sure to pass extra flags to recursively affect directories:
>>> import subprocess
>>> subprocess.check_output(['mkdir', '-p', 'first/second/third'])
# Equivalent to running 'mkdir -p first/second/third' in a shell (which creates
# parent directories if they do not yet exist).
>>> subprocess.check_output(['chown', '-R', 'dail:users', 'first'])
# Recursively change owner to 'dail' and group to 'users' for 'first' and all of
# its subdirectories.
>>> subprocess.check_output(['chmod', '-R', 'g+w', 'first'])
# Add group write permissions to 'first' and all of its subdirectories.
EDIT I originally used commands
, which was a bad choice since it is deprecated and vulnerable to injection attacks. (For example, if a user gave input to create a directory called first/;rm -rf --no-preserve-root /;
, one could potentially delete all directories).
EDIT 2 If you are using Python less than 2.7, use check_call
instead of check_output
. See the subprocess
documentation for details.
After this question was asked, Facebook launched HipHop for PHP which is probably the best-tested PHP compiler to date (seeing as it ran one of the world’s 10 biggest websites). However, Facebook discontinued it in favour of HHVM, which is a virtual machine, not a compiler.
Beyond that, googling PHP compiler
turns up a number of 3rd party solutions.
bcompiler_write_exe_footer()
manual)You could use an image submit button:
<input type="image" id="saveform" src="logg.png " alt="Submit Form" />
The language
attribute has been deprecated for a long time, and should not be used.
When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type
, so they standardized it to be the default value. Hence, you don't need type
either.
For pages in XHTML 1.0 or HTML 4.01 omitting type
is considered invalid. Try validating the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>
You will be informed of the following error:
Line 4, Column 41: required attribute "type" not specified
So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.
Here is a way to do it with a closure:
def generate_add_mult_func(func):
def function_generator(x):
return reduce(func,range(1,x))
return function_generator
def add(x,y):
return x+y
def mult(x,y):
return x*y
adding=generate_add_mult_func(add)
multiplying=generate_add_mult_func(mult)
print adding(10)
print multiplying(10)
Don't forget to change the iDisplayLength as well:
$(document).ready(function() {
$('#tbl_id').dataTable({
"aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
"iDisplayLength": 25
});
} );
You must fill the "Button" attribute of the "CompoundButton" class with a XML drawable path (my_checkbox). In the XML drawable, you must have :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false" android:drawable="@drawable/checkbox_not_checked" />
<item android:state_checked="true" android:drawable="@drawable/checkbox_checked" />
<item android:drawable="@drawable/checkbox_not_checked" /> <!-- default -->
</selector>
Don't forget to replace my_checkbox by your filename of the checkbox drawable , checkbox_not_checked by your PNG drawable which is your checkbox when it's not checked and checkbox_checked with your image when it's checked.
For the size, directly update the layout parameters.
This is because of ng-include
which creates a new child scope, so $scope.lineText
isn’t changed. I think that this
refers to the current scope, so this.lineText
should be set.
This just requires a small change to my last answer:
my ($guid, $scheme, $star) = $line =~ m{
The [ ] Scheme [ ] GUID: [ ]
([a-zA-Z0-9-]+) #capture the guid
[ ]
\( (.+) \) #capture the scheme
(?:
[ ]
([*]) #capture the star
)? #if it exists
}x;
If you wish to achieve this using standard MS-DOS commands in a batch file then you could use:
FOR /F "TOKENS=1 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET dd=%%A
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2,3 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET yyyy=%%C
I'm sure this can be improved upon further but this gives the date into 3 variables for Day (dd), Month (mm) and Year (yyyy). You can then use these later in your batch script as required.
SET todaysdate=%yyyy%%mm%%dd%
echo %dd%
echo %mm%
echo %yyyy%
echo %todaysdate%
While I understand an answer has been accepted for this question this alternative method may be appreciated by many looking to achieve this without using the WMI console, so I hope it adds some value to this question.
For users that are not members of the sysadmin role on the SQL Server instance you need to do the following actions to grant access to the xp_cmdshell extended stored procedure. In addition if you forgot one of the steps I have listed the error that will be thrown.
Enable the xp_cmdshell procedure
Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online.*
Create a login for the non-sysadmin user that has public access to the master database
Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*
Grant EXEC permission on the xp_cmdshell stored procedure
Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*
Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account
Msg 15153, Level 16, State 1, Procedure xp_cmdshell, Line 1 The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.*
It would seem from your error that either step 2 or 3 was missed. I am not familiar with clusters to know if there is anything particular to that setup.
Is just this:
int strcmp(char *str1, char *str2){
while( (*str1 == *str2) && (*str1 != 0) ){
++*str1;
++*str2;
}
return (*str1-*str2);
}
if you want more fast, you can add "register " before type, like this: register char
then, like this:
int strcmp(register char *str1, register char *str2){
while( (*str1 == *str2) && (*str1 != 0) ){
++*str1;
++*str2;
}
return (*str1-*str2);
}
this way, if possible, the register of the ALU are used.
please modify your router.module.ts as:
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree',
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
},
{
path: '',
redirectTo: 'two',
pathMatch: 'full'
}
]
},];
and in your component1.html
<h3>In One</h3>
<nav>
<a routerLink="/two" class="dash-item">...Go to Two...</a>
<a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
<a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>
<router-outlet></router-outlet> // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.
Just because I feel nice today:
<!doctype html>
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('time', function(data) {
addMessage(data.time);
});
socket.on('error', console.error.bind(console));
socket.on('message', console.log.bind(console));
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
}
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.on('connection', function(socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });
socket.on('i am client', console.log);
});
app.listen(3000);
With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.
Dont use this
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
Use this instead.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency>
Also use com.fasterxml.jackson.databind.JsonDeserializer
and com.fasterxml.jackson.databind.annotation.JsonDeserialize
for the deserialization and not the classes from org.codehaus.jackson
This must be used with care because an override on the objects __sizeof__ might be misleading.
Using the bregman.suite, some tests with sys.getsizeof output a copy of an array object (data) in an object instance as being bigger than the object itself (mfcc).
>>> mfcc = MelFrequencyCepstrum(filepath, params)
>>> data = mfcc.X[:]
>>> sys.getsizeof(mfcc)
64
>>> sys.getsizeof(mfcc.X)
>>>80
>>> sys.getsizeof(data)
80
>>> mfcc
<bregman.features.MelFrequencyCepstrum object at 0x104ad3e90>
If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.
<script type="text/javascript">
phpVars = new Array();
<?php foreach($vars as $var) {
echo 'phpVars.push("' . $var . '");';
};
?>
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>
If you're trying to call functions, then you can do this like this
<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
functionTwo(<?php echo $moreVars; ?>, <?php echo $evenMoreVars; ?>);
</script>
If what you need is UPDATE from SELECT statement you can do something like this:
UPDATE suppliers
SET city = (SELECT customers.city FROM customers
WHERE customers.customer_name = suppliers.supplier_name)
Your comment to cletus' (correct) answer implies that there are multiple Maven settings files involved.
Maven always uses either one or two settings files. The global settings defined in (${M2_HOME}/conf/settings.xml) is always required. The user settings file (defined in ${user.home}/.m2/settings.xml) is optional. Any settings defined in the user settings take precedence over the corresponding global settings.
You can override the location of the global and user settings from the command line, the following example will set the global settings to c:\global\settings.xml and the user settings to c:\user\settings.xml:
mvn install --settings c:\user\settings.xml
--global-settings c:\global\settings.xml
Currently there is no property or means to establish what user and global settings files were used from with Maven. To access these values, you would have to modify MavenCli and/or DefaultMavenSettingsBuilder to inject the file locations into the resolved Settings object.
You might be able to do something with sibling selectors e.g.:
div + div + div + div{
float: left
}
Not tried it but this might float the 4th div left perhaps doing what you want. Again not fully supported.
<-
does assignment in the current environment.
When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.
In most cases <<-
will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.
This might illustrate what is going on.
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
bar <- "in baz - before <<-"
bar <<- "in baz - after <<-"
print(bar)
}
print(bar)
baz()
print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"
The first time we print bar we haven't called foo
yet so it should still be global - this makes sense. The second time we print it's inside of foo
before calling baz
so the value "in foo" makes sense. The following is where we see what <<-
is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-
. This is because <<-
doesn't look in the current environment (unless you're in the global environment in which case <<-
acts like <-
). So inside of baz
the value of bar stays as "in baz - before <<-". Once we call baz
the copy of bar inside of foo
gets changed to "in baz" but as we can see the global bar
is unchanged. This is because the copy of bar
that is defined inside of foo
is in the parent environment when we created baz
so this is the first copy of bar
that <<-
sees and thus the copy it assigns to. So <<-
isn't just directly assigning to the global environment.
<<-
is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.
Now I change the <<-
to an assign statement and we can see what effect that has:
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
assign("bar", "in baz", envir = .GlobalEnv)
}
print(bar)
baz()
print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"
So both times we print bar inside of foo
the value is "in foo" even after calling baz
. This is because assign
never even considered the copy of bar
inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.
Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local
function.
bar <- "global"
# local will create a new environment for us to play in
local({
bar <- "local"
print(bar)
})
#[1] "local"
bar
#[1] "global"
Advanced bash scripting guide, 10.2. Parameter Substitution:
to base your program logic on whether the variable $mystr is defined or not, you can do the following:
isdefined=0
${mystr+ export isdefined=1}
now, if isdefined=0 then the variable was undefined, if isdefined=1 the variable was defined
This way of checking variables is better than the above answer because it is more elegant, readable, and if your bash shell was configured to error on the use of undefined variables (set -u)
, the script will terminate prematurely.
Other useful stuff:
to have a default value of 7 assigned to $mystr if it was undefined, and leave it intact otherwise:
mystr=${mystr- 7}
to print an error message and exit the function if the variable is undefined:
: ${mystr? not defined}
Beware here that I used ':' so as not to have the contents of $mystr executed as a command in case it is defined.
setInterval
or setTimeout
You should pass a reference to a function as the first argument for setTimeout
or setInterval
. This reference may be in the form of:
An anonymous function
setTimeout(function(){/* Look mah! No name! */},2000);
A name of an existing function
function foo(){...}
setTimeout(foo, 2000);
A variable that points to an existing function
var foo = function(){...};
setTimeout(foo, 2000);
Do note that I set "variable in a function" separately from "function name". It's not apparent that variables and function names occupy the same namespace and can clobber each other.
To call a function and pass parameters, you can call the function inside the callback assigned to the timer:
setTimeout(function(){
foo(arg1, arg2, ...argN);
}, 1000);
There is another method to pass in arguments into the handler, however it's not cross-browser compatible.
setTimeout(foo, 2000, arg1, arg2, ...argN);
By default, the context of the callback (the value of this
inside the function called by the timer) when executed is the global object window
. Should you want to change it, use bind
.
setTimeout(function(){
this === YOUR_CONTEXT; // true
}.bind(YOUR_CONTEXT), 2000);
Although it's possible, you should not pass a string to setTimeout
or setInterval
. Passing a string makes setTimeout()
or setInterval()
use a functionality similar to eval()
that executes strings as scripts, making arbitrary and potentially harmful script execution possible.
It's worth adding here as it is such a highly ranking question on zip. zip
is great, idiomatic Python - but it doesn't scale very well at all for large lists.
Instead of:
books = ['AAAAAAA', 'BAAAAAAA', ... , 'ZZZZZZZ']
words = [345, 567, ... , 672]
for book, word in zip(books, words):
print('{}: {}'.format(book, word))
Use izip
. For modern processing, it stores it in L1 Cache memory and is far more performant for larger lists. Use it as simply as adding an i
:
for book, word in izip(books, words):
print('{}: {}'.format(book, word))
genrsa
has been replaced by genpkey
& when run manually in a terminal it will prompt for a password:
openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096
However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell
script:
get_passwd() {
local passwd=
echo -ne "Enter passwd for private key: ? "; read -s passwd
openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}
Try my xsd-viewer available from https://github.com/santhosh-tekuri/jlibs.
While this isn't cloning, one simple way to get your result is to use the original object as the prototype of a new one.
You can do this using Object.create
:
var obj = {a: 25, b: 50, c: 75};
var A = Object.create(obj);
var B = Object.create(obj);
A.a = 30;
B.a = 40;
alert(obj.a + " " + A.a + " " + B.a); // 25 30 40
This creates a new object in A
and B
that inherits from obj
. This means that you can add properties without affecting the original.
To support legacy implementations, you can create a (partial) shim that will work for this simple task.
if (!Object.create)
Object.create = function(proto) {
function F(){}
F.prototype = proto;
return new F;
}
It doesn't emulate all the functionality of Object.create
, but it'll fit your needs here.
Thanks Anda, your post has been a great help!! However the OR sentence didnt' quite work for me and I was getting an error: getCollection() "invalid argument supplied for foreach".
So this is what I ended with (notice the attribute being specified 3 times instead of 2 in this case):
$collection->addFieldToFilter('attribute', array(
array('attribute'=>'my_field1','eq'=>'my_value1'),
array('attribute'=>'my_field2','eq'=>'my_value2') ));
addFieldToFilter first requires a field and then condition -> link.
if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:
<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
see the fiddle : http://jsfiddle.net/Lk2Rh/27/
but still it better to handling this with CSS, i suggest you that.
Polling the last modified file property is a simple yet effective solution though. Just define a class extending my FileChangedWatcher
and implement the onModified()
method:
import java.io.File;
public abstract class FileChangedWatcher
{
private File file;
public FileChangedWatcher(String filePath)
{
file = new File(filePath);
}
public void watch() throws InterruptedException
{
long currentModifiedDate = file.lastModified();
while (true)
{
long newModifiedDate = file.lastModified();
if (newModifiedDate != currentModifiedDate)
{
currentModifiedDate = newModifiedDate;
onModified();
}
Thread.sleep(100);
}
}
public String getFilePath()
{
return file.getAbsolutePath();
}
protected abstract void onModified();
}
There's actually a section in the OSTEP online textbook for an undergraduate course in operating systems which discusses exactly your question.
The relevant section is "Forgetting To Free Memory" in the Memory API chapter on page 6 which gives the following explanation:
In some cases, it may seem like not calling free() is reasonable. For example, your program is short-lived, and will soon exit; in this case, when the process dies, the OS will clean up all of its allocated pages and thus no memory leak will take place per se. While this certainly “works” (see the aside on page 7), it is probably a bad habit to develop, so be wary of choosing such a strategy
This excerpt is in the context of introducing the concept of virtual memory. Basically at this point in the book, the authors explain that one of the goals of an operating system is to "virtualize memory," that is, to let every program believe that it has access to a very large memory address space.
Behind the scenes, the operating system will translate "virtual addresses" the user sees to actual addresses pointing to physical memory.
However, sharing resources such as physical memory requires the operating system to keep track of what processes are using it. So if a process terminates, then it is within the capabilities and the design goals of the operating system to reclaim the process's memory so that it can redistribute and share the memory with other processes.
EDIT: The aside mentioned in the excerpt is copied below.
ASIDE: WHY NO MEMORY IS LEAKED ONCE YOUR PROCESS EXITS
When you write a short-lived program, you might allocate some space using
malloc()
. The program runs and is about to complete: is there need to callfree()
a bunch of times just before exiting? While it seems wrong not to, no memory will be "lost" in any real sense. The reason is simple: there are really two levels of memory management in the system. The first level of memory management is performed by the OS, which hands out memory to processes when they run, and takes it back when processes exit (or otherwise die). The second level of management is within each process, for example within the heap when you callmalloc()
andfree()
. Even if you fail to callfree()
(and thus leak memory in the heap), the operating system will reclaim all the memory of the process (including those pages for code, stack, and, as relevant here, heap) when the program is finished running. No matter what the state of your heap in your address space, the OS takes back all of those pages when the process dies, thus ensuring that no memory is lost despite the fact that you didn’t free it.Thus, for short-lived programs, leaking memory often does not cause any operational problems (though it may be considered poor form). When you write a long-running server (such as a web server or database management system, which never exit), leaked memory is a much bigger issue, and will eventually lead to a crash when the application runs out of memory. And of course, leaking memory is an even larger issue inside one particular program: the operating system itself. Showing us once again: those who write the kernel code have the toughest job of all...
from Page 7 of Memory API chapter of
Operating Systems: Three Easy Pieces
Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau Arpaci-Dusseau Books March, 2015 (Version 0.90)
I am using such code in config.php:
$lang = 'ru'; // this language will be used if there is no any lang information from useragent (for example, from command line, wget, etc...
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
$tmp_value = $_COOKIE['language'];
if (!empty($tmp_value)) $lang = $tmp_value;
switch ($lang)
{
case 'ru':
$config['language'] = 'russian';
setlocale(LC_ALL,'ru_RU.UTF-8');
break;
case 'uk':
$config['language'] = 'ukrainian';
setlocale(LC_ALL,'uk_UA.UTF-8');
break;
case 'foo':
$config['language'] = 'foo';
setlocale(LC_ALL,'foo_FOO.UTF-8');
break;
default:
$config['language'] = 'english';
setlocale(LC_ALL,'en_US.UTF-8');
break;
}
.... and then i'm using usualy internal mechanizm of CI
o, almost forget! in views i using buttons, which seting cookie 'language' with language, prefered by user.
So, first this code try to detect "preffered language" setted in user`s useragent (browser). Then code try to read cookie 'language'. And finaly - switch sets language for CI-application
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
I wrote an article on how to set a hyperlink or a mailto on a jLabel.
So just try it :
I think that's exactly what you're searching for.
Here's the complete code example :
/**
* Example of a jLabel Hyperlink and a jLabel Mailto
*/
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author ibrabelware
*/
public class JLabelLink extends JFrame {
private JPanel pan;
private JLabel contact;
private JLabel website;
/**
* Creates new form JLabelLink
*/
public JLabelLink() {
this.setTitle("jLabelLinkExample");
this.setSize(300, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
pan = new JPanel();
contact = new JLabel();
website = new JLabel();
contact.setText("<html> contact : <a href=\"\">[email protected]</a></html>");
contact.setCursor(new Cursor(Cursor.HAND_CURSOR));
website.setText("<html> Website : <a href=\"\">http://www.google.com/</a></html>");
website.setCursor(new Cursor(Cursor.HAND_CURSOR));
pan.add(contact);
pan.add(website);
this.setContentPane(pan);
this.setVisible(true);
sendMail(contact);
goWebsite(website);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Create and display the form
*/
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new JLabelLink().setVisible(true);
}
});
}
private void goWebsite(JLabel website) {
website.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().browse(new URI("http://www.google.com/webhp?nomo=1&hl=fr"));
} catch (URISyntaxException | IOException ex) {
//It looks like there's a problem
}
}
});
}
private void sendMail(JLabel contact) {
contact.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().mail(new URI("mailto:[email protected]?subject=TEST"));
} catch (URISyntaxException | IOException ex) {
//It looks like there's a problem
}
}
});
}
}
Yes, it is a bit puzzling at first.
In Ruby, methods may receive a code block in order to perform arbitrary segments of code.
When a method expects a block, it invokes it by calling the yield
function.
This is very handy, for instance, to iterate over a list or to provide a custom algorithm.
Take the following example:
I'm going to define a Person
class initialized with a name, and provide a do_with_name
method that when invoked, would just pass the name
attribute, to the block received.
class Person
def initialize( name )
@name = name
end
def do_with_name
yield( @name )
end
end
This would allow us to call that method and pass an arbitrary code block.
For instance, to print the name we would do:
person = Person.new("Oscar")
#invoking the method passing a block
person.do_with_name do |name|
puts "Hey, his name is #{name}"
end
Would print:
Hey, his name is Oscar
Notice, the block receives, as a parameter, a variable called name
(N.B. you can call this variable anything you like, but it makes sense to call it name
). When the code invokes yield
it fills this parameter with the value of @name
.
yield( @name )
We could provide another block to perform a different action. For example, reverse the name:
#variable to hold the name reversed
reversed_name = ""
#invoke the method passing a different block
person.do_with_name do |name|
reversed_name = name.reverse
end
puts reversed_name
=> "racsO"
We used exactly the same method (do_with_name
) - it is just a different block.
This example is trivial. More interesting usages are to filter all the elements in an array:
days = ["monday", "tuesday", "wednesday", "thursday", "friday"]
# select those which start with 't'
days.select do | item |
item.match /^t/
end
=> ["tuesday", "thursday"]
Or, we can also provide a custom sort algorithm, for instance based on the string size:
days.sort do |x,y|
x.size <=> y.size
end
=> ["monday", "friday", "tuesday", "thursday", "wednesday"]
I hope this helps you to understand it better.
BTW, if the block is optional you should call it like:
yield(value) if block_given?
If is not optional, just invoke it.
EDIT
@hmak created a repl.it for these examples: https://repl.it/@makstaks/blocksandyieldsrubyexample
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
TortoiseSVN has a command-line interface that can be used for TortoiseSVN GUI automation and it's different from the normal Subversion one.
You can find information about the command-line options of TortoiseSVN in the documentation:
Appendix D. Automating TortoiseSVN. The main program to work with here is TortoiseProc.exe
.
But a note pretty much at the top there already says:
Remember that TortoiseSVN is a GUI client, and this automation guide shows you how to make the TortoiseSVN dialogs appear to collect user input. If you want to write a script which requires no input, you should use the official Subversion command line client instead.
Another option would be that you install the Subversion binaries. Slik SVN is a nice build (and doesn't require a registration like Collabnet). Recent versions of TortoiseSVN also include the command-line client if you choose to install it.
In windows server 2012, even after installing asp.net you might run into this issue.
Check for "Http activation" feature. This feature is present under Web services as well.
Make sure you add the above and everything should be awesome for you !!!
With respect to the String class:
The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.
On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".
As with any explanation, let it sink in.
I hope this clears things up a bit.
It is probably more idiomatic jQuery to use the statusCode property of the parameter object passed to the the $.ajax function:
$.ajax({
statusCode: {
500: function(xhr) {
if(window.console) console.log(xhr.responseText);
}
}
});
However, as Livingston Samuel said, it is not possible to catch 301 status codes in javascript.
According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*)
.
PY_SSIZE_T_MAX
is defined in pyport.h to be ((size_t) -1)>>1
On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912.
Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.
As long as the number of elements you have is equal or below this, all list functions should operate correctly.
For Mac EI caption/Mac Sierra, Chrome extension folders were located at
/Users/$USER/Library/Application\ Support/Google/Chrome/Profile*/Extensions/
It occurred to me that you may have actually be asking how to implement the +
operator for dictionaries, the following seems to work:
>>> class Dict(dict):
... def __add__(self, other):
... copy = self.copy()
... copy.update(other)
... return copy
... def __radd__(self, other):
... copy = other.copy()
... copy.update(self)
... return copy
...
>>> default_data = Dict({'item1': 1, 'item2': 2})
>>> default_data + {'item3': 3}
{'item2': 2, 'item3': 3, 'item1': 1}
>>> {'test1': 1} + Dict(test2=2)
{'test1': 1, 'test2': 2}
Note that this is more overhead then using dict[key] = value
or dict.update()
, so I would recommend against using this solution unless you intend to create a new dictionary anyway.
Decimal has a fixed precision while float has variable precision.
EDIT (failed to read entire question): Float(53) (aka real) is a double-precision (64-bit) floating point number in SQL Server. Regular Float is a single-precision (32-bit) floating point number. Double is a good combination of precision and simplicty for a lot of calculations. You can create a very high precision number with decimal -- up to 136-bit -- but you also have to be careful that you define your precision and scale correctly so that it can contain all your intermediate calculations to the necessary number of digits.
With Bootstrap 4, the responsible css configuration in bootstrap.css
for .table-striped
is:
.table-striped tbody tr:nth-of-type(odd) {
background-color: rgba(0, 0, 0, 0.05);
}
For a very simple solution, I just copied it into my custom.css
file, and changed the values of background-color
, so that now I have a fancier light blue shade:
.table-striped tbody tr:nth-of-type(odd) {
background-color: rgba(72, 113, 248, 0.068);
}
RPC is C based, and as such it has structured programming semantics, on the other side, RMI is a Java based technology and it's object oriented.
With RPC you can just call remote functions exported into a server, in RMI you can have references to remote objects and invoke their methods, and also pass and return more remote object references that can be distributed among many JVM instances, so it's much more powerful.
RMI stands out when the need to develop something more complex than a pure client-server architecture arises. It's very easy to spread out objects over a network enabling all the clients to communicate without having to stablish individual connections explicitly.
Try this..
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#CABBBBBB"/>
<corners android:radius="2dp" />
</shape>
</item>
<item
android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="@android:color/white"/>
<corners android:radius="2dp" />
</shape>
</item>
</layer-list>
Yes you can convert it back. You can try:
date("Y-m-d H:i:s", 1388516401);
The logic behind this conversion from date to an integer is explained in strtotime in PHP:
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
For example, strtotime("1970-01-01 00:00:00")
gives you 0 and strtotime("1970-01-01 00:00:01")
gives you 1.
This means that if you are printing strtotime("2014-01-01 00:00:01")
which will give you output 1388516401
, so the date 2014-01-01 00:00:01
is 1,388,516,401 seconds after January 1 1970 00:00:00 UTC.
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
Try this one
UPDATE employee
set EMPLOYEE.MAIDEN_NAME =
(SELECT ADD1
FROM EMPS
WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
WHERE EMPLOYEE.EMP_CODE >='00'
AND EMPLOYEE.EMP_CODE <='ZZ';
I have add this input tag into form tag..
<form id="form_data">
<input type="file" id="file_data" name="browse"
(change)="handleFileInput($event, dataFile, f)" />
</form>
I angular typescript, I have added below lines, get your form id in document forms and make that value as null.
for(let i=0; i<document.forms.length;i++){
if(document.forms[i].length > 0){
if(document.forms[i][0]['value']){ //document.forms[i][0] = "file_data"
document.forms[i][0]['value'] = "";
}
}
}
Print document.forms in console and you can get idea..
The Ctrl + F5 solusion didn't work for me in Chrome.
But I found How to Clear Chrome Cache for Specific Website Only (3 Steps):
- As the page is loaded, open Chrome Developer Tools (Right-Click > Inspect) or (Menu > More Tools > Developer Tools)
- Next, go to the Refresh button in Chrome browser, and Right-Click the Refresh button.
- Select "Empty Cache and Hard Refresh".
Hope this answer helps someone!
Easy to do with json if you trust your keys to be sane:
JSON.pretty_generate(a: 1, 2 => 3, 3 => nil).
gsub(": null", ": nil").
gsub(/(^\s*)"([a-zA-Z][a-zA-Z\d_]*)":/, "\\1\\2:"). # "foo": 1 -> foo: 1
gsub(/(^\s*)(".*?"):/, "\\1\\2 =>") # "123": 1 -> "123" => 1
{
a: 1,
"2" => 3,
"3" => nil
}
This isn't exactly the issue I had, but if anyone is looking to convert a BindingList of any type to List of the same type, then this is how it is done:
var list = bindingList.ToDynamicList();
Also, if you're assigning BindingLists of dynamic types to a DataGridView.DataSource, then make sure you declare it first as IBindingList so the above works.
Actually, Laravel 4 does have a table rename function in Illuminate/Database/Schema/Builder.php, it's just undocumented at the moment: Schema::rename($from, $to);
.
You could add
cd /some/directory/somewhere/named/Foo
to your .bashrc
file (or .profile
or whatever you call it) at the other host. That way, no matter what you do or where you ssh
from, whenever you log onto that server, it will cd
to the proper directory for you, and all you have to do is use ssh
like normal.
Of curse, rogeriopvl's solution works too, but it's a tad bit more verbose, and you have to remember to do it every time (unless you make an alias) so it seems a bit less "fun".
You could try using Python's variable arguments feature:
def myfunction(*args):
for x in args:
# Do stuff with specific argument here
Try this:
public class Team
{
public int TeamId { get; set;}
public string Name { get; set; }
public virtual ICollection<Match> HomeMatches { get; set; }
public virtual ICollection<Match> AwayMatches { get; set; }
}
public class Match
{
public int MatchId { get; set; }
public int HomeTeamId { get; set; }
public int GuestTeamId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
public class Context : DbContext
{
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Match>()
.HasRequired(m => m.HomeTeam)
.WithMany(t => t.HomeMatches)
.HasForeignKey(m => m.HomeTeamId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Match>()
.HasRequired(m => m.GuestTeam)
.WithMany(t => t.AwayMatches)
.HasForeignKey(m => m.GuestTeamId)
.WillCascadeOnDelete(false);
}
}
Primary keys are mapped by default convention. Team must have two collection of matches. You can't have single collection referenced by two FKs. Match is mapped without cascading delete because it doesn't work in these self referencing many-to-many.
Like explained in other answers you need to provide a comparison function. If
you would like to keep the definition of that function close to the sort
call (e.g. if it only makes sense for this sort) you can define it right there
with boost::lambda
. Use boost::lambda::bind
to call the member function.
To e.g. sort by member variable or function data1
:
#include <algorithm>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
using boost::lambda::bind;
using boost::lambda::_1;
using boost::lambda::_2;
std::vector<myclass> object(10000);
std::sort(object.begin(), object.end(),
bind(&myclass::data1, _1) < bind(&myclass::data1, _2));
It won't be efficient, as you need to walk the list checking every item in it (O(n)). If you want efficiency, you can use dict of dicts. On the question, here's one possible way to find it (though, if you want to stick to this data structure, it's actually more efficient to use a generator as Brent Newey has written in the comments; see also tokland's answer):
>>> L = [{'id':'1234','name':'Jason'},
... {'id':'2345','name':'Tom'},
... {'id':'3456','name':'Art'}]
>>> [i for i,_ in enumerate(L) if _['name'] == 'Tom'][0]
1
Note: This is the somewhat crude solution I posted myself, after not finding an answer here on Stack Overflow. It allows for only one array being passed, and it being the last element of the parameter list. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. Somewhat later Ken posted his solution, but I kept mine here for "historic" reference.
calling_function()
{
variable="a"
array=( "x", "y", "z" )
called_function "${variable}" "${array[@]}"
}
called_function()
{
local_variable="${1}"
shift
local_array=("${@}")
}
junit4
require that test classname should be use Test
as suffix.
In C# and VB the SqlCommand object implements the Parameter.AddWithValue method which handles this situation
private List<DataValue> datavalue=new ArrayList<Datavalue>;
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
datavalue.remove(position);
notifyDataSetChanged();
}
});
}
}
You could use stat() or the File::Stat module.
perldoc -f stat
Cast the operands to floats:
float ans = (float)a / (float)b;
Or you can use an arrow function to define it:
$(document).ready(() => {
$('#bfCaptchaEntry').click(()=>{
});
});
For better browser support:
$(document).ready(function() {
$('#bfCaptchaEntry').click(function (){
});
});
EDIT After some hunting around, this seems to be the best option:
https://github.com/googlemaps/js-info-bubble/blob/gh-pages/examples/example.html
You can see a customised version of this InfoBubble that I used on Dive Seven, a website for online scuba dive logging. It looks like this:
There are some more examples here. They definitely don't look as nice as the example in your screenshot, however.
ISLE (InstallShield Limited Edition) is the "replacement" of the Visual Studio Setup and Deploy project, but many users think Microsoft took wrong step with removing .vdproj support from Visual Studio 2012 (and later ones) and supporting third-party company software.
Many people asked for returning it back (Bring back the basic setup and deployment project type Visual Studio Installer), but Microsoft is deaf to our voices... really sad.
As WiX is really complicated, I think it is worth to try some free installation systems - NSIS or Inno Setup. Both are scriptable and easy to learn - but powerful as original SADP.
I have created a really nice Visual Studio extension for NSIS and Inno Setup with many features (intellisense, syntax highlighting, navigation bars, compilation directly from Visual Studio, etc.). You can try it at www.visual-installer.com (sorry for self promo :)
Download Inno Setup (jrsoftware.org/isdl.php) or NSIS (nsis.sourceforge.net/Download) and install V&I (unsigned-softworks.sk/visual-installer/downloads.html).
All installers are simple Next/Next/Next...
In Visual Studio, select menu File -> New -> Project, choose NSISProject or Inno Setup, and a new project will be created (with full sources).
If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:
-Wno-multichar
I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.
Here is another implementation that will operate safely to tokenize a string-literal matching the prototype requested in the question returning an allocated pointer-to-pointer to char (e.g. char **
). The delimiter string can contain multiple characters, and the input string can contain any number of tokens. All allocations and reallocations are handled by malloc
or realloc
without POSIX strdup
.
The initial number of pointers allocated is controlled by the NPTRS
constant and the only limitation is that it be greater than zero. The char **
returned contains a sentinel NULL
after the last token similar to *argv[]
and in the form usable by execv
, execvp
and execve
.
As with strtok()
multiple sequential delimiters are treated as a single delimiter, so "JAN,FEB,MAR,APR,MAY,,,JUN,JUL,AUG,SEP,OCT,NOV,DEC"
will be parsed as if only a single ','
separates "MAY,JUN"
.
The function below is commented in-line and a short main()
was added splitting the months. The initial number of pointers allocated was set at 2
to force three reallocation during tokenizing the input string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NPTRS 2 /* initial number of pointers to allocate (must be > 0) */
/* split src into tokens with sentinel NULL after last token.
* return allocated pointer-to-pointer with sentinel NULL on success,
* or NULL on failure to allocate initial block of pointers. The number
* of allocated pointers are doubled each time reallocation required.
*/
char **strsplit (const char *src, const char *delim)
{
int i = 0, in = 0, nptrs = NPTRS; /* index, in/out flag, ptr count */
char **dest = NULL; /* ptr-to-ptr to allocate/fill */
const char *p = src, *ep = p; /* pointer and end-pointer */
/* allocate/validate nptrs pointers for dest */
if (!(dest = malloc (nptrs * sizeof *dest))) {
perror ("malloc-dest");
return NULL;
}
*dest = NULL; /* set first pointer as sentinel NULL */
for (;;) { /* loop continually until end of src reached */
if (!*ep || strchr (delim, *ep)) { /* if at nul-char or delimiter char */
size_t len = ep - p; /* get length of token */
if (in && len) { /* in-word and chars in token */
if (i == nptrs - 1) { /* used pointer == allocated - 1? */
/* realloc dest to temporary pointer/validate */
void *tmp = realloc (dest, 2 * nptrs * sizeof *dest);
if (!tmp) {
perror ("realloc-dest");
break; /* don't exit, original dest still valid */
}
dest = tmp; /* assign reallocated block to dest */
nptrs *= 2; /* increment allocated pointer count */
}
/* allocate/validate storage for token */
if (!(dest[i] = malloc (len + 1))) {
perror ("malloc-dest[i]");
break;
}
memcpy (dest[i], p, len); /* copy len chars to storage */
dest[i++][len] = 0; /* nul-terminate, advance index */
dest[i] = NULL; /* set next pointer NULL */
}
if (!*ep) /* if at end, break */
break;
in = 0; /* set in-word flag 0 (false) */
}
else { /* normal word char */
if (!in) /* if not in-word */
p = ep; /* update start to end-pointer */
in = 1; /* set in-word flag 1 (true) */
}
ep++; /* advance to next character */
}
return dest;
}
int main (void) {
char *str = "JAN,FEB,MAR,APR,MAY,,,JUN,JUL,AUG,SEP,OCT,NOV,DEC",
**tokens; /* pointer to pointer to char */
if ((tokens = strsplit (str, ","))) { /* split string into tokens */
for (char **p = tokens; *p; p++) { /* loop over filled pointers */
puts (*p);
free (*p); /* don't forget to free allocated strings */
}
free (tokens); /* and pointers */
}
}
Example Use/Output
$ ./bin/splitinput
JAN
FEB
MAR
APR
MAY
JUN
JUL
AUG
SEP
OCT
NOV
DEC
Let me know if you have any further questions.
You don't need pip
for installing Beautiful Soup - you can just download it and run python setup.py install
from the directory that you have unzipped BeautifulSoup in (assuming that you have added Python to your system PATH
- if you haven't and you don't want to you can run C:\Path\To\Python27\python "C:\Path\To\BeautifulSoup\setup.py" install
)
However, you really should install pip
- see How to install pip on Windows for how to do that best (via @MartijnPieters comment)
CStr(45)
is all you need (the Convert String function)
I solved this by using 2 custom functions like so:
function slash_replace($query){
return str_replace('/','_', $query);
}
function slash_unreplace($query){
return str_replace('_','/', $query);
}
So to encode I could call:
rawurlencode(slash_replace($param))
and to decode I could call
slash_unreplace(rawurldecode($param);
Cheers!
You can set a control variable in vars files located in group_vars/
or directly in hosts file like this:
[vagrant:vars]
test_var=true
[location-1]
192.168.33.10 hostname=apollo
[location-2]
192.168.33.20 hostname=zeus
[vagrant:children]
location-1
location-2
And run tasks like this:
- name: "test"
command: "echo {{test_var}}"
when: test_var is defined and test_var
You can use this
function percentage(partialValue, totalValue) {
return (100 * partialValue) / totalValue;
}
Example to calculate the percentage of a course progress base in their activities.
const totalActivities = 10;
const doneActivities = 2;
percentage(doneActivities, totalActivities) // Will return 20 that is 20%
I linux this works too:
import sys
sys.path.extend(["/path/to/dotpy/file/"])
my error disappeared by adding this '()' at the end
(function(){
var home = angular.module('home',[]);
home.controller('QuestionsController',function(){
console.log("controller initialized");
this.addPoll = function(){
console.log("inside function");
};
});
})();
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
You can join the table with itself (on sensor id), and add left.timestamp < right.timestamp
as join condition. Then you pick the rows, where right.id
is null
. Voila, you got the latest entry per sensor.
http://sqlfiddle.com/#!9/45147/37
SELECT L.* FROM sensorTable L
LEFT JOIN sensorTable R ON
L.sensorID = R.sensorID AND
L.timestamp < R.timestamp
WHERE isnull (R.sensorID)
But please note, that this will be very resource intensive if you have a little amount of ids and many values! So, I wouldn't recommend this for some sort of Measuring-Stuff, where each Sensor collects a value every minute. However in a Use-Case, where you need to track "Revisions" of something that changes just "sometimes", it's easy going.
Reflection is slower, but works for a situation when you want to know whether that is of type Dog or a Cat and not an instance of Animal. So you'd do something like:
if(null != items.elementAt(1) && items.elementAt(1).getClass().toString().equals("Cat"))
{
//do whatever with cat.. not any other instance of animal.. eg. hideClaws();
}
Not saying the answer above does not work, except the null checking part is necessary.
Another way to answer that is use generics and you are guaranteed to have Double as any element of items.
List<Double> items = new ArrayList<Double>();
With angular4 we just need to organise routes together in hierarchy
const appRoutes: Routes = [
{
path: '',
component: MainPageComponent
},
{
path: 'car/details',
component: CarDetailsComponent
},
{
path: 'car/details/platforms-products',
component: CarProductsComponent
},
{
path: 'car/details/:id',
component: CadDetailsComponent
},
{
path: 'car/details/:id/platforms-products',
component: CarProductsComponent
}
];
This works for me . This way router know what is the next route based on option id parameters.