First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:
I would use an anonymous type filled with your results
type:
string json = JsonConvert.SerializeObject(new
{
results = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" }
}
});
Also, note that the generated JSON has result items with id
s of type Number
instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id
to string
in the C#.
I'd also tweak your results
type and get rid of the backing fields:
public class Result
{
public int id { get ;set; }
public string value { get; set; }
public string info { get; set; }
}
Furthermore, classes conventionally are PascalCased
and not camelCased
.
Here's the generated JSON from the code above:
{
"results": [
{
"id": 1,
"value": "ABC",
"info": "ABC"
},
{
"id": 2,
"value": "JKL",
"info": "JKL"
}
]
}
int?
is shorthand for Nullable<int>
. The two forms are interchangeable.
Nullable<T>
is an operator that you can use with a value type T
to make it accept null
.
In case you don't know it: value types are types that accepts values as int
, bool
, char
etc...
They can't accept references to values: they would generate a compile-time error if you assign them a null
, as opposed to reference types, which can obviously accept it.
Why would you need that? Because sometimes your value type variables could receive null references returned by something that didn't work very well, like a missing or undefined variable returned from a database.
I suggest you to read the Microsoft Documentation because it covers the subject quite well.
The accepted answer is great. I am making a table that helps in quick comprehension of the topic. The explanation involves a simple variable a
as well as an indexed array arr
.
If we set
a=apple # a simple variable
arr=(apple) # an indexed array with a single element
and then echo
the expression in the second column, we would get the result / behavior shown in the third column. The fourth column explains the behavior.
# | Expression | Result | Comments |
---|---|---|---|
1 | "$a" |
apple |
variables are expanded inside "" |
2 | '$a' |
$a |
variables are not expanded inside '' |
3 | "'$a'" |
'apple' |
'' has no special meaning inside "" |
4 | '"$a"' |
"$a" |
"" is treated literally inside '' |
5 | '\'' |
invalid | can not escape a ' within '' ; use "'" or $'\'' (ANSI-C quoting) |
6 | "red$arocks" |
red |
$arocks does not expand $a ; use ${a}rocks to preserve $a |
7 | "redapple$" |
redapple$ |
$ followed by no variable name evaluates to $ |
8 | '\"' |
\" |
\ has no special meaning inside '' |
9 | "\'" |
\' |
\' is interpreted inside "" but has no significance for ' |
10 | "\"" |
" |
\" is interpreted inside "" |
11 | "*" |
* |
glob does not work inside "" or '' |
12 | "\t\n" |
\t\n |
\t and \n have no special meaning inside "" or '' ; use ANSI-C quoting |
13 | "`echo hi`" |
hi |
`` and $() are evaluated inside "" (backquotes are retained in actual output) |
14 | '`echo hi`' |
echo hi | `` and $() are not evaluated inside '' (backquotes are retained in actual output) |
15 | '${arr[0]}' |
${arr[0]} |
array access not possible inside '' |
16 | "${arr[0]}" |
apple |
array access works inside "" |
17 | $'$a\'' |
$a' |
single quotes can be escaped inside ANSI-C quoting |
18 | "$'\t'" |
$'\t' |
ANSI-C quoting is not interpreted inside "" |
19 | '!cmd' |
!cmd |
history expansion character '!' is ignored inside '' |
20 | "!cmd" |
cmd args |
expands to the most recent command matching "cmd" |
21 | $'!cmd' |
!cmd |
history expansion character '!' is ignored inside ANSI-C quotes |
See also:
I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5
This makes me happy.
Try this: Live Demo
display: table
is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>
.
CSS:
#container {
background: #ccc;
display: table
}
#left, #right {
display: table-cell
}
#left {
width: 150px;
background: #f0f;
border: 5px dotted blue;
}
#right {
background: #aaa;
border: 3px solid #000
}
The lambda you are passing to forEach()
is evaluated for each element received from the stream. The iteration itself is not visible from within the scope of the lambda, so you cannot continue
it as if forEach()
were a C preprocessor macro. Instead, you can conditionally skip the rest of the statements in it.
If you are using VS Code, you can rename the .ts, .html, .css/.scss, .spec.ts
files and the IDE will take care of the imports for you. Therefore there will be no complaints from the files that import files from your component (such as app.module.ts
). However, you will still have to rename the component name everywhere it is being used.
I am using JsonProperty attributes when serializing but ignoring them when deserializing using this ContractResolver
:
public class IgnoreJsonPropertyContractResolver: DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
foreach (var p in properties) { p.PropertyName = p.UnderlyingName; }
return properties;
}
}
The ContractResolver
just sets every property back to the class property name (simplified from Shimmy's solution). Usage:
var airplane= JsonConvert.DeserializeObject<Airplane>(json,
new JsonSerializerSettings { ContractResolver = new IgnoreJsonPropertyContractResolver() });
>>> for i, s in enumerate(S):
I solved my problem using this code, is a somewhat replacement for the missing splice.
let str = "I need to remove a character from this";
let pos = str.indexOf("character")
if(pos>-1){
let result = str.slice(0, pos-2) + str.slice(pos, str.length);
console.log(result) //I need to remove character from this
}
I needed to remove a character before/after a certain word, after you get the position the string is split in two and then recomposed by flexibly removing characters using an offset along pos
It is also worth taking a look at:
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \
to a line to explicitly break it:
x = (tuples_first_value,
second_value)
y = 1 + \
2
This problem happened for me only in special cases, when I called website from some internet providers,
I've configured only ip v4 in VirtualHost configuration of apache, but some of router use ip v6, and when I added ip v6 to apache config the problem solved.
$(option).removeAttr('selected') //replace 'option' with selected option's selector
You have to put this as root:
GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'IP' IDENTIFIED BY 'PASSWORD' with grant option;
;
where IP is the IP you want to allow access, USERNAME is the user you use to connect, and PASSWORD is the relevant password.
If you want to allow access from any IP just put %
instead of your IP
and then you only have to put
FLUSH PRIVILEGES;
Or restart mysql server and that's it.
You can always use the stl:
auto min_value = *std::min_element(v.begin(),v.end());
The print function in python adds itself \n
You could use
import sys
sys.stdout.write(a)
instead
You can define this during datatable initialization
"aoColumns": [{"bVisible": false},null,null,null]
The proper way would be to use $_SERVER["PHP_SELF"]
(in conjunction with htmlspecialchars
to avoid possible exploits). You can also just skip the action=
part empty, which is not W3C valid, but currently works in most (all?) browsers - the default is to submit to self if it's empty.
Here is an example form that takes a name and email, and then displays the values you have entered upon submit:
<?php if (!empty($_POST)): ?>
Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br>
Your email is <?php echo htmlspecialchars($_POST["email"]); ?>.<br>
<?php else: ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit">
</form>
<?php endif; ?>
To make use of regular expressions directly in Excel formulas the following UDF (user defined function) can be of help. It more or less directly exposes regular expression functionality as an excel function.
It takes 2-3 parameters.
$0
, $1
, $2
, and so on. $0
is the entire match, $1
and up correspond to the respective match groups in the regular expression. Defaults to $0
.Extracting an email address:
=regex("Peter Gordon: [email protected], 47", "\w+@\w+\.\w+")
=regex("Peter Gordon: [email protected], 47", "\w+@\w+\.\w+", "$0")
Results in: [email protected]
Extracting several substrings:
=regex("Peter Gordon: [email protected], 47", "^(.+): (.+), (\d+)$", "E-Mail: $2, Name: $1")
Results in: E-Mail: [email protected], Name: Peter Gordon
To take apart a combined string in a single cell into its components in multiple cells:
=regex("Peter Gordon: [email protected], 47", "^(.+): (.+), (\d+)$", "$" & 1)
=regex("Peter Gordon: [email protected], 47", "^(.+): (.+), (\d+)$", "$" & 2)
Results in: Peter Gordon
[email protected]
...
To use this UDF do the following (roughly based on this Microsoft page. They have some good additional info there!):
ALT+F11
to open the Microsoft Visual Basic for Applications Editor.Click on Insert Module. If you give your module a different name make sure the Module does not have the same name as the UDF below (e.g. naming the Module Regex
and the function regex
causes #NAME! errors).
In the big text window in the middle insert the following:
Function regex(strInput As String, matchPattern As String, Optional ByVal outputPattern As String = "$0") As Variant
Dim inputRegexObj As New VBScript_RegExp_55.RegExp, outputRegexObj As New VBScript_RegExp_55.RegExp, outReplaceRegexObj As New VBScript_RegExp_55.RegExp
Dim inputMatches As Object, replaceMatches As Object, replaceMatch As Object
Dim replaceNumber As Integer
With inputRegexObj
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = matchPattern
End With
With outputRegexObj
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = "\$(\d+)"
End With
With outReplaceRegexObj
.Global = True
.MultiLine = True
.IgnoreCase = False
End With
Set inputMatches = inputRegexObj.Execute(strInput)
If inputMatches.Count = 0 Then
regex = False
Else
Set replaceMatches = outputRegexObj.Execute(outputPattern)
For Each replaceMatch In replaceMatches
replaceNumber = replaceMatch.SubMatches(0)
outReplaceRegexObj.Pattern = "\$" & replaceNumber
If replaceNumber = 0 Then
outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).Value)
Else
If replaceNumber > inputMatches(0).SubMatches.Count Then
'regex = "A to high $ tag found. Largest allowed is $" & inputMatches(0).SubMatches.Count & "."
regex = CVErr(xlErrValue)
Exit Function
Else
outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).SubMatches(replaceNumber - 1))
End If
End If
Next
regex = outputPattern
End If
End Function
Save and close the Microsoft Visual Basic for Applications Editor window.
I found the easiest way is to use the colormap
parameter in .plot()
with one of the preset color gradients:
df.plot(kind='bar', stacked=True, colormap='Paired')
You can find a large list of preset colormaps here.
The NuGet package Pdf2Png is available for free and is only protected by the MIT License, which is very open.
I've tested around a bit and this is the code to get it to convert a PDF file to an image (tt does save the image in the debug folder).
using cs_pdf_to_image;
using PdfToImage;
private void BtnConvert_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
string PdfFile = openFileDialog1.FileName;
string PngFile = "Convert.png";
List<string> Conversion = cs_pdf_to_image.Pdf2Image.Convert(PdfFile, PngFile);
Bitmap Output = new Bitmap(PngFile);
PbConversion.Image = Output;
}
catch(Exception E)
{
MessageBox.Show(E.Message);
}
}
}
I usually use the overflow: auto
trick; although that's not, strictly speaking, the intended use for overflow, it is kinda related - enough to make it easy to remember, certainly. The meaning of float: left
itself has been extended for various uses more significantly than overflow is in this example, IMO.
Simple popup window by using html5 and javascript.
html:-
<dialog id="window">
<h3>Sample Dialog!</h3>
<p>Lorem ipsum dolor sit amet</p>
<button id="exit">Close Dialog</button>
</dialog>
<button id="show">Show Dialog</button>
JavaScript:-
(function() {
var dialog = document.getElementById('window');
document.getElementById('show').onclick = function() {
dialog.show();
};
document.getElementById('exit').onclick = function() {
dialog.close();
};
})();
Please use the below kotlin code
webview.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return false
}
})
For more info click here
If you change the ManagementObjectSearcher to the following:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%""");
So the "GetUSBDevices() looks like this"
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%"""))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
}
Your results will be limited to USB devices (as opposed to all types on your system)
If you want to use the toDF
method, you have to convert your RDD
of Array[String]
into a RDD
of a case class. For example, you have to do:
case class Test(id:String,filed2:String)
val myFile = sc.textFile("file.txt")
val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()
Just Go to Model file of the corresponding Controller and check the primary key filed name
such as
protected $primaryKey = 'info_id';
here info id is field name available in database table
More info can be found at "Primary Keys" section of the docs.
download java-json.jar from Java2s then use the JSONArray constructor
List myList = new ArrayList<>();
JSONArray jsonArray = new JSONArray(myList);
System.out.println(jsonArray);
No doubt that NLTK is the most suitable for the purpose. But getting started with NLTK is quite painful (But once you install it - you just reap the rewards)
So here is simple re based code available at http://pythonicprose.blogspot.com/2009/09/python-split-paragraph-into-sentences.html
# split up a paragraph into sentences
# using regular expressions
def splitParagraphIntoSentences(paragraph):
''' break a paragraph into sentences
and return a list '''
import re
# to split by multile characters
# regular expressions are easiest (and fastest)
sentenceEnders = re.compile('[.!?]')
sentenceList = sentenceEnders.split(paragraph)
return sentenceList
if __name__ == '__main__':
p = """This is a sentence. This is an excited sentence! And do you think this is a question?"""
sentences = splitParagraphIntoSentences(p)
for s in sentences:
print s.strip()
#output:
# This is a sentence
# This is an excited sentence
# And do you think this is a question
hey guys i think what you are looking for is this one using select command. With this you can specify a RANGE GREATER THAN(>) OR LESSER THAN(<) IN MySQL WITH THIS:::::
select* from <**TABLE NAME**> where year(**COLUMN NAME**) > **DATE** OR YEAR(COLUMN NAME )< **DATE**;
FOR EXAMPLE:
select name, BIRTH from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+------------+
| name | BIRTH |
+----------+------------+
| bowser | 1979-09-11 |
| chirpy | 1998-09-11 |
| whistler | 1999-09-09 |
+----------+------------+
FOR SIMPLE RANGE LIKE USE ONLY GREATER THAN / LESSER THAN
mysql> select COLUMN NAME from <TABLE NAME> where year(COLUMN NAME)> 1996;
FOR EXAMPLE mysql>
select name from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+
| name |
+----------+
| bowser |
| chirpy |
| whistler |
+----------+
3 rows in set (0.00 sec)
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
I've had the same error and I solve it with: git merge -s recursive -X theirs origin/master
You need to do a deep copy from user to usercopy, and then after your login you can reassign your userCopy reference to user.
User userCopy = new User();
userCopy.Age = user.Age
userCopy.ID = user.ID
foreach(...)
{
user.Age = 1;
user.ID = -1;
UserDao.Update(user)
user = userCopy;
}
This should work:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");
Electricity went down and got this error. Solution was to double click your .ppk (Putty Private Key) and enter your password.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
There is now a handy guide for configuring PHP debugging in Visual Studio Code at http://blogs.msdn.com/b/nicktrog/archive/2016/02/11/configuring-visual-studio-code-for-php-development.aspx
From the link, the steps are:
Note there are specific details in the linked article, including the PHP values for your VS Code user config, and so on.
Suppose you want to set a pop-up text box for clicking a button lets say bt whose id is button, then code using Toast will somewhat look like this:
Button bt;
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"The text you want to display",Toast.LENGTH_LONG)
}
The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel
. The basic idea is to use QScrollArea
as a container for the QLabel
and if needed use label.setScaledContents(bool)
and scrollarea.setWidgetResizable(bool)
to fill available space and/or ensure QLabel inside is resizable.
Additionally, to resize QLabel while honoring aspect ratio use:
label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));
The width
and height
can be set based on scrollarea.width()
and scrollarea.height()
.
In this way there is no need to subclass QLabel.
Actually you don't even need the block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open(playlist_name, 'w').puts(music)
So I've gone ahead and answered my own question :)
@True's answer regarded transforming an element to a specific height. The problem with this is I don't know the height of the element (it can fluctuate).
I found other solutions around which used max-height as the transition but this produced a very jerky animation for me.
My solution below works only in WebKit browsers.
Although not purely CSS, it involves transitioning the height, which is determined by some JS.
$('#click-me').click(function() {_x000D_
var height = $("#this").height();_x000D_
if (height > 0) {_x000D_
$('#this').css('height', '0');_x000D_
} else {_x000D_
$("#this").css({_x000D_
'position': 'absolute',_x000D_
'visibility': 'hidden',_x000D_
'height': 'auto'_x000D_
});_x000D_
var newHeight = $("#this").height();_x000D_
$("#this").css({_x000D_
'position': 'static',_x000D_
'visibility': 'visible',_x000D_
'height': '0'_x000D_
});_x000D_
$('#this').css('height', newHeight + 'px');_x000D_
}_x000D_
});
_x000D_
#this {_x000D_
width: 500px;_x000D_
height: 0;_x000D_
max-height: 9999px;_x000D_
overflow: hidden;_x000D_
background: #BBBBBB;_x000D_
-webkit-transition: height 1s ease-in-out;_x000D_
}_x000D_
_x000D_
#click-me {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>_x000D_
_x000D_
<p id="click-me">click me</p>_x000D_
<div id="this">here<br />is<br />a<br />bunch<br />of<br />content<br />sdf</div>_x000D_
<div>always shows</div>
_x000D_
I've had a lot of trouble over the years trying to get QApplication::processEvents to work, as is used in some of the top answers. IIRC, if multiple locations end up calling it, it can end up causing some signals to not get processed (https://doc.qt.io/archives/qq/qq27-responsive-guis.html). My usual preferred option is to utilize a QEventLoop (https://doc.qt.io/archives/qq/qq27-responsive-guis.html#waitinginalocaleventloop).
inline void delay(int millisecondsWait)
{
QEventLoop loop;
QTimer t;
t.connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
t.start(millisecondsWait);
loop.exec();
}
lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
'Set the initial value:
lstDepartment.SelectedValue = depID;
lstDepartment.Attributes.Remove("InitialValue");
lstDepartment.Attributes.Add("InitialValue", depID);
And in your cancel method:
lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");
And in your update method:
lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;
I have used below code in my custom library
call that from my controller like below,
function __construct() {<br />
parent::__construct();<br />
$this->load->library('CommonMethods');<br />
}<br />
$config = array();<br />
$config['upload_path'] = 'assets/upload/images/';<br />
$config['allowed_types'] = 'gif|jpg|png|jpeg';<br />
$config['max_width'] = 150;<br />
$config['max_height'] = 150;<br />
$config['encrypt_name'] = TRUE;<br />
$config['overwrite'] = FALSE;<br />
// upload multiplefiles<br />
$fileUploadResponse = $this->commonmethods->do_upload_multiple_files('profile_picture', $config);
/**
* do_upload_multiple_files - Multiple Methods
* @param type $fieldName
* @param type $options
* @return type
*/
public function do_upload_multiple_files($fieldName, $options) {
$response = array();
$files = $_FILES;
$cpt = count($_FILES[$fieldName]['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES[$fieldName]['name']= $files[$fieldName]['name'][$i];
$_FILES[$fieldName]['type']= $files[$fieldName]['type'][$i];
$_FILES[$fieldName]['tmp_name']= $files[$fieldName]['tmp_name'][$i];
$_FILES[$fieldName]['error']= $files[$fieldName]['error'][$i];
$_FILES[$fieldName]['size']= $files[$fieldName]['size'][$i];
$this->CI->load->library('upload');
$this->CI->upload->initialize($options);
//upload the image
if (!$this->CI->upload->do_upload($fieldName)) {
$response['erros'][] = $this->CI->upload->display_errors();
} else {
$response['result'][] = $this->CI->upload->data();
}
}
return $response;
}
I would use the operator[].
map <char, int> m1;
m1['G'] ++; // If the element 'G' does not exist then it is created and
// initialized to zero. A reference to the internal value
// is returned. so that the ++ operator can be applied.
// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'
So using this technique it becomes really easy to read all the character from a stream and count them:
map <char, int> m1;
std::ifstream file("Plop");
std::istreambuf_iterator<char> end;
for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
++m1[*loop]; // prefer prefix increment out of habbit
}
Use stringi
package and stri_length
function
> stri_length(c("ala ma kota","ABC",NA))
[1] 11 3 NA
Why? Because it is the FASTEST among presented solutions :)
require(microbenchmark)
require(stringi)
require(stringr)
x <- c(letters,NA,paste(sample(letters,2000,TRUE),collapse=" "))
microbenchmark(nchar(x),str_length(x),stri_length(x))
Unit: microseconds
expr min lq median uq max neval
nchar(x) 11.868 12.776 13.1590 13.6475 41.815 100
str_length(x) 30.715 33.159 33.6825 34.1360 173.400 100
stri_length(x) 2.653 3.281 4.0495 4.5380 19.966 100
and also works fine with NA's
nchar(NA)
## [1] 2
stri_length(NA)
## [1] NA
I was able to accomplish this by using bind()
. I wanted to click a button in index.jsx
, post some data to the server, evaluate the response, and redirect to success.jsx
. Here's how I worked that out...
index.jsx
:
import React, { Component } from "react"
import { postData } from "../../scripts/request"
class Main extends Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
this.postData = postData.bind(this)
}
handleClick() {
const data = {
"first_name": "Test",
"last_name": "Guy",
"email": "[email protected]"
}
this.postData("person", data)
}
render() {
return (
<div className="Main">
<button onClick={this.handleClick}>Test Post</button>
</div>
)
}
}
export default Main
request.js
:
import { post } from "./fetch"
export const postData = function(url, data) {
// post is a fetch() in another script...
post(url, data)
.then((result) => {
if (result.status === "ok") {
this.props.history.push("/success")
}
})
}
success.jsx
:
import React from "react"
const Success = () => {
return (
<div className="Success">
Hey cool, got it.
</div>
)
}
export default Success
So by binding this
to postData
in index.jsx
, I was able to access this.props.history
in request.js
... then I can reuse this function in different components, just have to make sure I remember to include this.postData = postData.bind(this)
in the constructor()
.
Procedurally insert "element script" after "element body" is "parse error" by recommended process by W3C. In "Tree Construction" create error and run "tokenize again" to process that content. So it's like additional step. Only then can be runned "Script Execution" - see scheme process.
Anything else "parse error". Switch the "insertion mode" to "in body" and reprocess the token.
Technically by browser it's internal process, how they mark and optimize it.
I hope I helped somebody.
You may also try the following code with exception handling. Here you have a method removeLast(String s, int n)
(it is actually an modified version of masud.m's answer). You have to provide the String
s and how many char
you want to remove from the last to this removeLast(String s, int n)
function. If the number of char
s have to remove from the last is greater than the given String
length then it throws a StringIndexOutOfBoundException
with a custom message -
public String removeLast(String s, int n) throws StringIndexOutOfBoundsException{
int strLength = s.length();
if(n>strLength){
throw new StringIndexOutOfBoundsException("Number of character to remove from end is greater than the length of the string");
}
else if(null!=s && !s.isEmpty()){
s = s.substring(0, s.length()-n);
}
return s;
}
Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:
Subject: Claiming (?P...) regex syntax extensions
From: Guido van Rossum ([email protected])
Date: Dec 10, 1997 3:36:19 pm
I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.
You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)
As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:
(?P<foo>...)
Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".
(?P=foo)
Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)
to which Larry Wall replied:
[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)
Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]
So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.
You can use the blade template engine:
@include('view.name')
'view.name' would live in your main views folder:
// for laravel 4.X
app/views/view/name.blade.php
// for laravel 5.X
resources/views/view/name.blade.php
Another example
@include('hello.world');
would display the following view
// for laravel 4.X
app/views/hello/world.blade.php
// for laravel 5.X
resources/views/hello/world.blade.php
Another example
@include('some.directory.structure.foo');
would display the following view
// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php
// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php
So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views
folder for laravel 4.x or your resources/views
folder in laravel 5.x
ADDITIONAL
If you want to pass parameters: @include('view.name', array('paramName' => 'value'))
You can then use the value in your views like so <p>{{$paramName}}</p>
If you didn't publish changes, to remove latest commit, you can do
$ git reset --hard HEAD^
(note that this would also remove all uncommitted changes; use with care).
If you already published to-be-deleted commit, use git revert
$ git revert HEAD
I have tried to use AjaxableResponseMixin in my project, but had ended up with the following error message:
ImproperlyConfigured: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
That is because the CreateView will return a redirect response instead of returning a HttpResponse when you to send JSON request to the browser. So I have made some changes to the AjaxableResponseMixin
. If the request is an ajax request, it will not call the super.form_valid
method, just call the form.save()
directly.
from django.http import JsonResponse
from django import forms
from django.db import models
class AjaxableResponseMixin(object):
success_return_code = 1
error_return_code = 0
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
form.errors.update({'result': self.error_return_code})
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
if self.request.is_ajax():
self.object = form.save()
data = {
'result': self.success_return_code
}
return JsonResponse(data)
else:
response = super(AjaxableResponseMixin, self).form_valid(form)
return response
class Product(models.Model):
name = models.CharField('product name', max_length=255)
class ProductAddForm(forms.ModelForm):
'''
Product add form
'''
class Meta:
model = Product
exclude = ['id']
class PriceUnitAddView(AjaxableResponseMixin, CreateView):
'''
Product add view
'''
model = Product
form_class = ProductAddForm
Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.
It does however need a simple modification to work from within a batch file:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
If you really want a bruteforce algorithm, don't save any big list in the memory of your computer, unless you want a slow algorithm that crashes with a MemoryError.
You could try to use itertools.product like this :
from string import ascii_lowercase
from itertools import product
charset = ascii_lowercase # abcdefghijklmnopqrstuvwxyz
maxrange = 10
def solve_password(password, maxrange):
for i in range(maxrange+1):
for attempt in product(charset, repeat=i):
if ''.join(attempt) == password:
return ''.join(attempt)
solved = solve_password('solve', maxrange) # This worked for me in 2.51 sec
itertools.product(*iterables)
returns the cartesian products of the iterables you entered.
[i for i in product('bar', (42,))]
returns e.g. [('b', 42), ('a', 42), ('r', 42)]
The repeat
parameter allows you to make exactly what you asked :
[i for i in product('abc', repeat=2)]
Returns
[('a', 'a'),
('a', 'b'),
('a', 'c'),
('b', 'a'),
('b', 'b'),
('b', 'c'),
('c', 'a'),
('c', 'b'),
('c', 'c')]
Note:
You wanted a brute-force algorithm so I gave it to you. Now, it is a very long method when the password starts to get bigger because it grows exponentially (it took 62 sec to find the word 'solved').
You can easily write a bit code that will read in a file. You can either assume one sql statement per line, or assume the ;
So, assuming you have a text file such as:
insert into tblTest (t1) values ('2000');
update tbltest set t1 = '2222'
where id = 5;
insert into tblTest (t1,t2,t3)
values ('2001','2002','2003');
Note the in the above text file we free to have sql statements on more then one line.
the code you can use to read + run the above script is:
Sub SqlScripts()
Dim vSql As Variant
Dim vSqls As Variant
Dim strSql As String
Dim intF As Integer
intF = FreeFile()
Open "c:\sql.txt" For Input As #intF
strSql = input(LOF(intF), #intF)
Close intF
vSql = Split(strSql, ";")
On Error Resume Next
For Each vSqls In vSql
CurrentDb.Execute vSqls
Next
End Sub
You could expand on placing some error msg if the one statement don't work, such as
if err.number <> 0 then
debug.print "sql err" & err.Descripiton & "-->" vSqls
end dif
Regardless, the above split() and string read does alow your sql to be on more then one line...
You can use display: table-cell and vertical-align: bottom, on the 2 columns that you want to be aligned bottom, like so:
.bottom-column
{
float: none;
display: table-cell;
vertical-align: bottom;
}
Working example here.
Also, this might be a possible duplicate question.
Just a supplement here.
The following question is that what if I want more subplots in the figure?
As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2)
to set a group of subplots with grid(2,2) in one figure object.
Then as we know, the fig, ax = plt.subplots()
returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2)
firstly.
ValueError: not enough values to unpack (expected 4, got 2)
It raises a error, but no worry, because we now see that plt.subplots()
actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.
So let's try this again:
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)
and check the type:
type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>
Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:
fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)
So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.
Hope this would be helpful for you.
Working code, I have used Java Mail 1.4.7 jar
import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
public class MailProjectClass {
public static void main(String[] args) {
final String username = "[email protected]";
final String password = "your.password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
String file = "path of file to be attached";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
This method nicely does it all in one go.
from glob import glob
subd = [s.rstrip("/") for s in glob(parent_dir+"*/")]
For the main logfile/appender, set up a .Threshold = INFO
to limit what is actually logged in the appender to INFO and above, regardless of whether or not the loggers have DEBUG, TRACE, etc, enabled.
As for catching DEBUG and nothing above that... you'd probably have to write a custom appender.
However I'd recommend not doing this, as it sounds like it would make troubleshooting and analysis pretty hard:
Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
actually it's not that simple, see the peer-review in the comments, especially:
=
(@AndrewF)+
(added by me)For further details, see MDN article and RFC 3986.
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
This function can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
Have you tried the Generate Scripts
(Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?
Just adding that using the first approach it can be done as -
pd.DataFrame(list(map(list, zip(lst1,lst2,lst3))))
Your shell_exec is executed by www-data user, from its directory. You can try
putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");
Where your script is located in /home/user/bin Later on you can
$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;
To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh
To create list of lists, you need to separate them with commas, like this
coin_args = [
["pennies", '2.5', '50.0', '.01'],
["nickles", '5.0', '40.0', '.05'],
["dimes", '2.268', '50.0', '.1'],
["quarters", '5.67', '40.0', '.25']
]
Try this:
string callbackurl = Request.Url.Host != "localhost"
? Request.Url.Host : Request.Url.Authority;
This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.
In the View, modify the current view or create a new view and make a filter change, select the radio button "Show items only when the following is true", in the below columns type "Created" and in the next dropdown select "is less than" and fill the next column [Today]-7.
The keyword [Today] denotes the current day for the calculation and this view will show as per your requirement
For me implementing a new library just because Safari cannot do it correctly is too much and a regex is overkill. Here is the oneliner:
console.log (new Date('2011-04-12'.replace(/-/g, "/")));
Like this:
>>> s='1\t2\t3\t4\t5'
>>> [x for x in s.split('\t')]
['1', '2', '3', '4', '5']
For a file:
# create test file:
>>> with open('tabs.txt','w') as o:
... s='\n'.join(['\t'.join(map(str,range(i,i+10))) for i in [0,10,20,30]])
... print >>o, s
#read that file:
>>> with open('tabs.txt','r') as f:
... LoL=[x.strip().split('\t') for x in f]
...
>>> LoL
[['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
['10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
['20', '21', '22', '23', '24', '25', '26', '27', '28', '29'],
['30', '31', '32', '33', '34', '35', '36', '37', '38', '39']]
>>> LoL[2][3]
23
If you want the input transposed:
>>> with open('tabs.txt','r') as f:
... LoT=zip(*(line.strip().split('\t') for line in f))
...
>>> LoT[2][3]
'32'
Or (better still) use the csv module in the default distribution...
Here is sample code that might help you coping Column A to Column B:
UPDATE YourTable
SET ColumnB = ColumnA
WHERE
ColumnB IS NULL
AND ColumnA IS NOT NULL;
You can put a meta refresh Tag in the irc_online.php
<meta http-equiv="refresh" content="30">
OR you can use Javascript with setInterval to refresh the src of the Source...
<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
document.frames["frameNameHere"].location.reload();
}
</script>
I prefer this implementation:
class APIClient {
}
var sharedAPIClient: APIClient = {
return APIClient()
}()
extension APIClient {
class func sharedClient() -> APIClient {
return sharedAPIClient
}
}
You can also check for socket output stream error while writing to client socket.
out.println(output);
if(out.checkError())
{
throw new Exception("Error transmitting data.");
}
There are multiple ways to do this, one way is mentioned below. Just assume you have .js file like this.
let add = function (a, b) {
console.log(a + b);
};
let sub = function (a, b) {
console.log(a - b);
};
You can export these functions using the following code snippet,
module.exports.add = add;
module.exports.sub = sub;
And you can use the exported functions using this code snippet,
var add = require('./counter').add;
var sub = require('./counter').sub;
add(1,2);
sub(1,2);
I know this is a late reply, but hope this helps!
INNER JOIN gets all records that are common between both tables based on the supplied ON clause.
LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.
RIGHT JOIN is like the above but gets all records in the RIGHT table.
FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.
// YCombinator_x000D_
function anonymous(fnc) {_x000D_
return function() {_x000D_
fnc.apply(fnc, arguments);_x000D_
return fnc;_x000D_
}_x000D_
}_x000D_
_x000D_
// Invoking the first time:_x000D_
setInterval(anonymous(function() {_x000D_
console.log("bar");_x000D_
})(), 4000);_x000D_
_x000D_
// Not invoking the first time:_x000D_
setInterval(anonymous(function() {_x000D_
console.log("foo");_x000D_
}), 4000);_x000D_
// Or simple:_x000D_
setInterval(function() {_x000D_
console.log("baz");_x000D_
}, 4000);
_x000D_
Ok this is so complex, so, let me put it more simple:
function hello(status ) { _x000D_
console.log('world', ++status.count);_x000D_
_x000D_
return status;_x000D_
}_x000D_
_x000D_
setInterval(hello, 5 * 1000, hello({ count: 0 }));
_x000D_
Softwares run on the OS on a very simple premise - they require memory. The device OS provides it in the form of RAM. The amount of memory required may vary - some softwares need huge memory, some require paltry memory. Most (if not all) users run multiple applications on the OS simultaneously, and given that memory is expensive (and device size is finite), the amount of memory available is always limited. So given that all softwares require a certain amount of RAM, and all of them can be made to run at the same time, OS has to take care of two things:
Now the main question boils down to how the memory is being managed. What exactly governs where in the memory will the data belonging to a given software reside?
Possible solution 1: Let individual softwares specify explicitly the memory address they will use in the device. Suppose Photoshop declares that it will always use memory addresses ranging from
0
to1023
(imagine the memory as a linear array of bytes, so first byte is at location0
,1024
th byte is at location1023
) - i.e. occupying1 GB
memory. Similarly, VLC declares that it will occupy memory range1244
to1876
, etc.
Advantages:
Disadvantages:
This does not scale. Theoretically, an app may require a huge amount of memory when it is doing something really heavy-duty. So to ensure that it never runs out of memory, the memory area allocated to it must always be more than or equal to that amount of memory. What if a software, whose maximal theoretical memory usage is 2 GB
(hence requiring 2 GB
memory allocation from RAM), is installed in a machine with only 1 GB
memory? Should the software just abort on startup, saying that the available RAM is less than 2 GB
? Or should it continue, and the moment the memory required exceeds 2 GB
, just abort and bail out with the message that not enough memory is available?
It is not possible to prevent memory mangling. There are millions of softwares out there, even if each of them was allotted just 1 kB
memory, the total memory required would exceed 16 GB
, which is more than most devices offer. How can, then, different softwares be allotted memory slots that do not encroach upon each other's areas? Firstly, there is no centralized software market which can regulate that when a new software is being released, it must assign itself this much memory from this yet unoccupied area, and secondly, even if there were, it is not possible to do it because the no. of softwares is practically infinite (thus requiring infinite memory to accommodate all of them), and the total RAM available on any device is not sufficient to accommodate even a fraction of what is required, thus making inevitable the encroaching of the memory bounds of one software upon that of another. So what happens when Photoshop is assigned memory locations 1
to 1023
and VLC is assigned 1000
to 1676
? What if Photoshop stores some data at location 1008
, then VLC overwrites that with its own data, and later Photoshop accesses it thinking that it is the same data is had stored there previously? As you can imagine, bad things will happen.
So clearly, as you can see, this idea is rather naive.
Possible solution 2: Let's try another scheme - where OS will do majority of the memory management. Softwares, whenever they require any memory, will just request the OS, and the OS will accommodate accordingly. Say OS ensures that whenever a new process is requesting for memory, it will allocate the memory from the lowest byte address possible (as said earlier, RAM can be imagined as a linear array of bytes, so for a
4 GB
RAM, the addresses range for a byte from0
to2^32-1
) if the process is starting, else if it is a running process requesting the memory, it will allocate from the last memory location where that process still resides. Since the softwares will be emitting addresses without considering what the actual memory address is going to be where that data is stored, OS will have to maintain a mapping, per software, of the address emitted by the software to the actual physical address (Note: that is one of the two reasons we call this conceptVirtual Memory
. Softwares are not caring about the real memory address where their data are getting stored, they just spit out addresses on the fly, and the OS finds the right place to fit it and find it later if required).
Say the device has just been turned on, OS has just launched, right now there is no other process running (ignoring the OS, which is also a process!), and you decide to launch VLC. So VLC is allocated a part of the RAM from the lowest byte addresses. Good. Now while the video is running, you need to start your browser to view some webpage. Then you need to launch Notepad to scribble some text. And then Eclipse to do some coding.. Pretty soon your memory of 4 GB
is all used up, and the RAM looks like this:
Problem 1: Now you cannot start any other process, for all RAM is used up. Thus programs have to be written keeping the maximum memory available in mind (practically even less will be available, as other softwares will be running parallelly as well!). In other words, you cannot run a high-memory consuming app in your ramshackle
1 GB
PC.
Okay, so now you decide that you no longer need to keep Eclipse and Chrome open, you close them to free up some memory. The space occupied in RAM by those processes is reclaimed by OS, and it looks like this now:
Suppose that closing these two frees up 700 MB
space - (400
+ 300
) MB. Now you need to launch Opera, which will take up 450 MB
space. Well, you do have more than 450 MB
space available in total, but...it is not contiguous, it is divided into individual chunks, none of which is big enough to fit 450 MB
. So you hit upon a brilliant idea, let's move all the processes below to as much above as possible, which will leave the 700 MB
empty space in one chunk at the bottom. This is called compaction
. Great, except that...all the processes which are there are running. Moving them will mean moving the address of all their contents (remember, OS maintains a mapping of the memory spat out by the software to the actual memory address. Imagine software had spat out an address of 45
with data 123
, and OS had stored it in location 2012
and created an entry in the map, mapping 45
to 2012
. If the software is now moved in memory, what used to be at location 2012
will no longer be at 2012
, but in a new location, and OS has to update the map accordingly to map 45
to the new address, so that the software can get the expected data (123
) when it queries for memory location 45
. As far as the software is concerned, all it knows is that address 45
contains the data 123
!)! Imagine a process that is referencing a local variable i
. By the time it is accessed again, its address has changed, and it won't be able to find it any more. The same will hold for all functions, objects, variables, basically everything has an address, and moving a process will mean changing the address of all of them. Which leads us to:
Problem 2: You cannot move a process. The values of all variables, functions and objects within that process have hardcoded values as spat out by the compiler during compilation, the process depends on them being at the same location during its lifetime, and changing them is expensive. As a result, processes leave behind big "
holes
" when they exit. This is calledExternal Fragmentation
.
Fine. Suppose somehow, by some miraculous manner, you do manage to move the processes up. Now there is 700 MB
of free space at the bottom:
Opera smoothly fits in at the bottom. Now your RAM looks like this:
Good. Everything is looking fine. However, there is not much space left, and now you need to launch Chrome again, a known memory-hog! It needs lots of memory to start, and you have hardly any left...Except.. you now notice that some of the processes, which were initially occupying large space, now is not needing much space. May be you have stopped your video in VLC, hence it is still occupying some space, but not as much as it required while running a high resolution video. Similarly for Notepad and Photos. Your RAM now looks like this:
Holes
, once again! Back to square one! Except, previously, the holes occurred due to processes terminating, now it is due to processes requiring less space than before! And you again have the same problem, the holes
combined yield more space than required, but they are scattered around, not much of use in isolation. So you have to move those processes again, an expensive operation, and a very frequent one at that, since processes will frequently reduce in size over their lifetime.
Problem 3: Processes, over their lifetime, may reduce in size, leaving behind unused space, which if needed to be used, will require the expensive operation of moving many processes. This is called
Internal Fragmentation
.
Fine, so now, your OS does the required thing, moves processes around and start Chrome and after some time, your RAM looks like this:
Cool. Now suppose you again resume watching Avatar in VLC. Its memory requirement will shoot up! But...there is no space left for it to grow, as Notepad is snuggled at its bottom. So, again, all processes has to move below until VLC has found sufficient space!
Problem 4: If processes needs to grow, it will be a very expensive operation
Fine. Now suppose, Photos is being used to load some photos from an external hard disk. Accessing hard-disk takes you from the realm of caches and RAM to that of disk, which is slower by orders of magnitudes. Painfully, irrevocably, transcendentally slower. It is an I/O operation, which means it is not CPU bound (it is rather the exact opposite), which means it does not need to occupy RAM right now. However, it still occupies RAM stubbornly. If you want to launch Firefox in the meantime, you can't, because there is not much memory available, whereas if Photos was taken out of memory for the duration of its I/O bound activity, it would have freed lot of memory, followed by (expensive) compaction, followed by Firefox fitting in.
Problem 5: I/O bound jobs keep on occupying RAM, leading to under-utilization of RAM, which could have been used by CPU bound jobs in the meantime.
So, as we can see, we have so many problems even with the approach of virtual memory.
There are two approaches to tackle these problems - paging
and segmentation
. Let us discuss paging
. In this approach, the virtual address space of a process is mapped to the physical memory in chunks - called pages
. A typical page
size is 4 kB
. The mapping is maintained by something called a page table
, given a virtual address, all now we have to do is find out which page
the address belong to, then from the page table
, find the corresponding location for that page
in actual physical memory (known as frame
), and given that the offset of the virtual address within the page
is same for the page
as well as the frame
, find out the actual address by adding that offset to the address returned by the page table
. For example:
On the left is the virtual address space of a process. Say the virtual address space requires 40 units of memory. If the physical address space (on the right) had 40 units of memory as well, it would have been possible to map all location from the left to a location on the right, and we would have been so happy. But as ill luck would have it, not only does the physical memory have less (24 here) memory units available, it has to be shared between multiple processes as well! Fine, let's see how we make do with it.
When the process starts, say a memory access request for location 35
is made. Here the page size is 8
(each page
contains 8
locations, the entire virtual address space of 40
locations thus contains 5
pages). So this location belongs to page no. 4
(35/8
). Within this page
, this location has an offset of 3
(35%8
). So this location can be specified by the tuple (pageIndex, offset)
= (4,3)
. This is just the starting, so no part of the process is stored in the actual physical memory yet. So the page table
, which maintains a mapping of the pages on the left to the actual pages on the right (where they are called frames
) is currently empty. So OS relinquishes the CPU, lets a device driver access the disk and fetch the page no. 4
for this process (basically a memory chunk from the program on the disk whose addresses range from 32
to 39
). When it arrives, OS allocates the page somewhere in the RAM, say first frame itself, and the page table
for this process takes note that page 4
maps to frame 0
in the RAM. Now the data is finally there in the physical memory. OS again queries the page table for the tuple (4,3)
, and this time, page table says that page 4
is already mapped to frame 0
in the RAM. So OS simply goes to the 0
th frame in RAM, accesses the data at offset 3
in that frame (Take a moment to understand this. The entire page
, which was fetched from disk, is moved to frame
. So whatever the offset of an individual memory location in a page was, it will be the same in the frame as well, since within the page
/frame
, the memory unit still resides at the same place relatively!), and returns the data! Because the data was not found in memory at first query itself, but rather had to be fetched from disk to be loaded into memory, it constitutes a miss.
Fine. Now suppose, a memory access for location 28
is made. It boils down to (3,4)
. Page table
right now has only one entry, mapping page 4
to frame 0
. So this is again a miss, the process relinquishes the CPU, device driver fetches the page from disk, process regains control of CPU again, and its page table
is updated. Say now the page 3
is mapped to frame 1
in the RAM. So (3,4)
becomes (1,4)
, and the data at that location in RAM is returned. Good. In this way, suppose the next memory access is for location 8
, which translates to (1,0)
. Page 1
is not in memory yet, the same procedure is repeated, and the page
is allocated at frame 2
in RAM. Now the RAM-process mapping looks like the picture above. At this point in time, the RAM, which had only 24 units of memory available, is filled up. Suppose the next memory access request for this process is from address 30
. It maps to (3,6)
, and page table
says that page 3
is in RAM, and it maps to frame 1
. Yay! So the data is fetched from RAM location (1,6)
, and returned. This constitutes a hit, as data required can be obtained directly from RAM, thus being very fast. Similarly, the next few access requests, say for locations 11
, 32
, 26
, 27
all are hits, i.e. data requested by the process is found directly in the RAM without needing to look elsewhere.
Now suppose a memory access request for location 3
comes. It translates to (0,3)
, and page table
for this process, which currently has 3 entries, for pages 1
, 3
and 4
says that this page is not in memory. Like previous cases, it is fetched from disk, however, unlike previous cases, RAM is filled up! So what to do now? Here lies the beauty of virtual memory, a frame from the RAM is evicted! (Various factors govern which frame is to be evicted. It may be LRU
based, where the frame which was least recently accessed for a process is to be evicted. It may be first-come-first-evicted
basis, where the frame which allocated longest time ago, is evicted, etc.) So some frame is evicted. Say frame 1 (just randomly choosing it). However, that frame
is mapped to some page
! (Currently, it is mapped by the page table to page 3
of our one and only one process). So that process has to be told this tragic news, that one frame
, which unfortunate belongs to you, is to be evicted from RAM to make room for another pages
. The process has to ensure that it updates its page table
with this information, that is, removing the entry for that page-frame duo, so that the next time a request is made for that page
, it right tells the process that this page
is no longer in memory, and has to be fetched from disk. Good. So frame 1
is evicted, page 0
is brought in and placed there in the RAM, and the entry for page 3
is removed, and replaced by page 0
mapping to the same frame 1
. So now our mapping looks like this (note the colour change in the second frame
on the right side):
Saw what just happened? The process had to grow, it needed more space than the available RAM, but unlike our earlier scenario where every process in the RAM had to move to accommodate a growing process, here it happened by just one page
replacement! This was made possible by the fact that the memory for a process no longer needs to be contiguous, it can reside at different places in chunks, OS maintains the information as to where they are, and when required, they are appropriately queried. Note: you might be thinking, huh, what if most of the times it is a miss
, and the data has to be constantly loaded from disk into memory? Yes, theoretically, it is possible, but most compilers are designed in such a manner that follows locality of reference
, i.e. if data from some memory location is used, the next data needed will be located somewhere very close, perhaps from the same page
, the page
which was just loaded into memory. As a result, the next miss will happen after quite some time, most of the upcoming memory requirements will be met by the page just brought in, or the pages already in memory which were recently used. The exact same principle allows us to evict the least recently used page
as well, with the logic that what has not been used in a while, is not likely to be used in a while as well. However, it is not always so, and in exceptional cases, yes, performance may suffer. More about it later.
Solution to Problem 4: Processes can now grow easily, if space problem is faced, all it requires is to do a simple
page
replacement, without moving any other process.
Solution to Problem 1: A process can access unlimited memory. When more memory than available is needed, the disk is used as backup, the new data required is loaded into memory from the disk, and the least recently used data
frame
(orpage
) is moved to disk. This can go on infinitely, and since disk space is cheap and virtually unlimited, it gives an illusion of unlimited memory. Another reason for the nameVirtual Memory
, it gives you illusion of memory which is not really available!
Cool. Earlier we were facing a problem where even though a process reduces in size, the empty space is difficult to be reclaimed by other processes (because it would require costly compaction). Now it is easy, when a process becomes smaller in size, many of its pages
are no longer used, so when other processes need more memory, a simple LRU
based eviction automatically evicts those less-used pages
from RAM, and replaces them with the new pages from the other processes (and of course updating the page tables
of all those processes as well as the original process which now requires less space), all these without any costly compaction operation!
Solution to Problem 3: Whenever processes reduce in size, its
frames
in RAM will be less used, so a simpleLRU
based eviction can evict those pages out and replace them withpages
required by new processes, thus avoidingInternal Fragmentation
without need forcompaction
.
As for problem 2, take a moment to understand this, the scenario itself is completely removed! There is no need to move a process to accommodate a new process, because now the entire process never needs to fit at once, only certain pages of it need to fit ad hoc, that happens by evicting frames
from RAM. Everything happens in units of pages
, thus there is no concept of hole
now, and hence no question of anything moving! May be 10 pages
had to be moved because of this new requirement, there are thousands of pages
which are left untouched. Whereas, earlier, all processes (every bit of them) had to be moved!
Solution to Problem 2: To accommodate a new process, data from only less recently used parts of other processes have to be evicted as required, and this happens in fixed size units called
pages
. Thus there is no possibility ofhole
orExternal Fragmentation
with this system.
Now when the process needs to do some I/O operation, it can relinquish CPU easily! OS simply evicts all its pages
from the RAM (perhaps store it in some cache) while new processes occupy the RAM in the meantime. When the I/O operation is done, OS simply restores those pages
to the RAM (of course by replacing the pages
from some other processes, may be from the ones which replaced the original process, or may be from some which themselves need to do I/O now, and hence can relinquish the memory!)
Solution to Problem 5: When a process is doing I/O operations, it can easily give up RAM usage, which can be utilized by other processes. This leads to proper utilization of RAM.
And of course, now no process is accessing the RAM directly. Each process is accessing a virtual memory location, which is mapped to a physical RAM address and maintained by the page-table
of that process. The mapping is OS-backed, OS lets the process know which frame is empty so that a new page for a process can be fitted there. Since this memory allocation is overseen by the OS itself, it can easily ensure that no process encroaches upon the contents of another process by allocating only empty frames from RAM, or upon encroaching upon the contents of another process in the RAM, communicate to the process to update it page-table
.
Solution to Original Problem: There is no possibility of a process accessing the contents of another process, since the entire allocation is managed by the OS itself, and every process runs in its own sandboxed virtual address space.
So paging
(among other techniques), in conjunction with virtual memory, is what powers today's softwares running on OS-es! This frees the software developer from worrying about how much memory is available on the user's device, where to store the data, how to prevent other processes from corrupting their software's data, etc. However, it is of course, not full-proof. There are flaws:
Paging
is, ultimately, giving user the illusion of infinite memory by using disk as secondary backup. Retrieving data from secondary storage to fit into memory (called page swap
, and the event of not finding the desired page in RAM is called page fault
) is expensive as it is an IO operation. This slows down the process. Several such page swaps happen in succession, and the process becomes painfully slow. Ever seen your software running fine and dandy, and suddenly it becomes so slow that it nearly hangs, or leaves you with no option that to restart it? Possibly too many page swaps were happening, making it slow (called thrashing
).So coming back to OP,
Why do we need the virtual memory for executing a process? - As the answer explains at length, to give softwares the illusion of the device/OS having infinite memory, so that any software, big or small, can be run, without worrying about memory allocation, or other processes corrupting its data, even when running in parallel. It is a concept, implemented in practice through various techniques, one of which, as described here, is Paging. It may also be Segmentation.
Where does this virtual memory stand when the process (program) from the external hard drive is brought to the main memory (physical memory) for the execution? - Virtual memory doesn't stand anywhere per se, it is an abstraction, always present, when the software/process/program is booted, a new page table is created for it, and it contains the mapping from the addresses spat out by that process to the actual physical address in RAM. Since the addresses spat out by the process are not real addresses, in one sense, they are, actually, what you can say, the virtual memory
.
Who takes care of the virtual memory and what is the size of the virtual memory? - It is taken care of by, in tandem, the OS and the software. Imagine a function in your code (which eventually compiled and made into the executable that spawned the process) which contains a local variable - an int i
. When the code executes, i
gets a memory address within the stack of the function. That function is itself stored as an object somewhere else. These addresses are compiler generated (the compiler which compiled your code into the executable) - virtual addresses. When executed, i
has to reside somewhere in actual physical address for duration of that function at least (unless it is a static variable!), so OS maps the compiler generated virtual address of i
into an actual physical address, so that whenever, within that function, some code requires the value of i
, that process can query the OS for that virtual address, and OS in turn can query the physical a
An easy way to do this with some jQuery and straight JavaScript, just view your console in Chrome or Firefox to see the output...
var queries = {};
$.each(document.location.search.substr(1).split('&'),function(c,q){
var i = q.split('=');
queries[i[0].toString()] = i[1].toString();
});
console.log(queries);
You should be able to specify the number of digits you want to round to using Math.Round(YourNumber, 2)
You can read more here.
For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.
jar xf myFile.jar
change myFile to name of your file
this will save the contents in the current folder of .jar file
that should do :)
with open('input.json','r') as f:
s = f.read()
s = s.replace('\'','\"')
data = json.loads(s)
This worked perfectly well for me. Thanks.
I want to share my solution for those who are using react-router-dom v5
since none of these v4 solutions did the work for me.
What solved my problem was installing react-router-scroll-top and put the wrapper in the <App />
like this:
const App = () => (
<Router>
<ScrollToTop>
<App/>
</ScrollToTop>
</Router>
)
and that's it! it worked!
Keep it simple
dataGridView1.Columns.Add("newColumnName", "Column Name in Text");
To add rows
dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]
return $this->output
->set_content_type('application/json')
->set_status_header(500)
->set_output(json_encode(array(
'text' => 'Error 500',
'type' => 'danger'
)));
Use Except
:
var firstNotSecond = list1.Except(list2).ToList();
var secondNotFirst = list2.Except(list1).ToList();
I suspect there are approaches which would actually be marginally faster than this, but even this will be vastly faster than your O(N * M) approach.
If you want to combine these, you could create a method with the above and then a return statement:
return !firstNotSecond.Any() && !secondNotFirst.Any();
One point to note is that there is a difference in results between the original code in the question and the solution here: any duplicate elements which are only in one list will only be reported once with my code, whereas they'd be reported as many times as they occur in the original code.
For example, with lists of [1, 2, 2, 2, 3]
and [1]
, the "elements in list1 but not list2" result in the original code would be [2, 2, 2, 3]
. With my code it would just be [2, 3]
. In many cases that won't be an issue, but it's worth being aware of.
Here is the code you need to ensure that only one instance is running. This is the method of using a named mutex.
public class Program
{
static System.Threading.Mutex singleton = new Mutex(true, "My App Name");
static void Main(string[] args)
{
if (!singleton.WaitOne(TimeSpan.Zero, true))
{
//there is already another instance running!
Application.Exit();
}
}
}
In android studio, You can use bellow process to create & Read QR Code &image look like bellw
Add library in app.gradle
compile 'com.google.zxing:core:3.2.1'
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
In activity.main xml use bellow..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.enamul.qrcode.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Enter Text Here" />
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/editText"
android:text="Click Here TO generate qr code"
android:textAllCaps="false"
android:textSize="16sp" />
<Button
android:id="@+id/btnScan"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/editText"
android:text="Scan Your QR Code"
android:textAllCaps="false"
android:textSize="16sp" />
<TextView
android:id="@+id/tv_qr_readTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="@+id/button"
android:src="@android:drawable/ic_dialog_email" />
</LinearLayout>
</LinearLayout>
In MainActivity you can use bellow code
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button button;
Button btnScan;
EditText editText;
String EditTextValue ;
Thread thread ;
public final static int QRcodeWidth = 350 ;
Bitmap bitmap ;
TextView tv_qr_readTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView);
editText = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
btnScan = (Button)findViewById(R.id.btnScan);
tv_qr_readTxt = (TextView) findViewById(R.id.tv_qr_readTxt);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!editText.getText().toString().isEmpty()){
EditTextValue = editText.getText().toString();
try {
bitmap = TextToImageEncode(EditTextValue);
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
else{
editText.requestFocus();
Toast.makeText(MainActivity.this, "Please Enter Your Scanned Test" , Toast.LENGTH_LONG).show();
}
}
});
btnScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
Bitmap TextToImageEncode(String Value) throws WriterException {
BitMatrix bitMatrix;
try {
bitMatrix = new MultiFormatWriter().encode(
Value,
BarcodeFormat.DATA_MATRIX.QR_CODE,
QRcodeWidth, QRcodeWidth, null
);
} catch (IllegalArgumentException Illegalargumentexception) {
return null;
}
int bitMatrixWidth = bitMatrix.getWidth();
int bitMatrixHeight = bitMatrix.getHeight();
int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];
for (int y = 0; y < bitMatrixHeight; y++) {
int offset = y * bitMatrixWidth;
for (int x = 0; x < bitMatrixWidth; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ?
getResources().getColor(R.color.QRCodeBlackColor):getResources().getColor(R.color.QRCodeWhiteColor);
}
}
Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);
bitmap.setPixels(pixels, 0, 350, 0, 0, bitMatrixWidth, bitMatrixHeight);
return bitmap;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.e("Scan*******", "Cancelled scan");
} else {
Log.e("Scan", "Scanned");
tv_qr_readTxt.setText(result.getContents());
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
}
You can download full source code from GitHub. GitHub link is : https://github.com/enamul95/QRCode
You will need to know if the REST API you are calling supports GET
or POST
, or both methods. The code below is something that works for me, I'm calling my own web service API, so I already know what the API takes and what it will return. It supports both GET
and POST
methods, so the less sensitive info goes into the URL (GET)
, and the info like username and password is submitted as POST
variables. Also, everything goes over the HTTPS
connection.
Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable
to make that json string availabe to the client.
So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.
This is how I connect to the API from the client side:
$processed = FALSE;
$ERROR_MESSAGE = '';
// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass"); // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);
// returned json string will look like this: {"code":1,"data":"OK"}
// "code" may contain an error code and "data" may contain error string instead of "OK"
$obj = json_decode($json);
if ($obj->{'code'} == '1')
{
$processed = TRUE;
}else{
$ERROR_MESSAGE = $obj->{'data'};
}
...
if (!$processed && $ERROR_MESSAGE != '') {
echo $ERROR_MESSAGE;
}
BTW, I also tried to use file_get_contents()
method as some of the users here suggested, but that din't work well for me. I found out the curl
method to be faster and more reliable.
If eclipse (none of them) doesn't launch at all and there's not even an error message, uninstall Java 8 Updater and reinstall Java 8 from scratch, this should work. Have luck!
In my case I was doing this:
double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));
Instead of the "correct" :
double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);
Take attention with the parentheses !
I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer
in this mailinglist post).
For example, numpy seems to use buffer for efficient data storage:
import numpy
a = numpy.ndarray(1000000)
the a.data
is a:
<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
@Chris Doggett makes perfect sense.
Although, I found one funny trick on lvsys.com, and it actually works on firefox and chrome. Just put this comment anywhere you want the page-break to be inserted. You can also replace the <p>
tag with any block element.
<p><!-- pagebreak --></p>
Try the unload event. The unload event is sent to the window element when the user navigates away from the page.
$( window ).unload(function() {
//do something
});
This functionality is now supported by Python 3.8+ :)
https://github.com/python/cpython/commit/4959c33d2555b89b494c678d99be81a65ee864b0
I contribute with my settings for buttons: view, edit and delete. The last column has data: null At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.
//...
columns: [
{ title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
{ title: "Id", "data": "id", defaultContent: '', "visible":false },
{ title: "Nombre", "data": "nombre" },
{ title: "Apellido", "data": "apellido" },
{ title: "Documento", "data": "tipo_documento.siglas" },
{ title: "Numero", "data": "numero_documento" },
{ title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
{ title: "Teléfono", "data": "telefono1" },
{ title: "Email", "data": "email1" }
, { title: "", "data": null }
],
columnDefs: [
{
"searchable": false,
"orderable": false,
"targets": 0
},
{
width: '3%',
targets: 0 //la primer columna tendra una anchura del 20% de la tabla
},
{
targets: -1, //-1 es la ultima columna y 0 la primera
data: null,
defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button> <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
},
{ orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
],
//...
I just created a CodePen that shows how this can be done pretty easily using ES6.
http://codepen.io/travist/pen/GWRBQV
Basically, here is the class that does this.
let getPropertyValue = function(style, prop) {
let value = style.getPropertyValue(prop);
value = value ? value.replace(/[^0-9.]/g, '') : '0';
return parseFloat(value);
}
let getElementRect = function(element) {
let style = window.getComputedStyle(element, null);
return {
x: getPropertyValue(style, 'left'),
y: getPropertyValue(style, 'top'),
width: getPropertyValue(style, 'width'),
height: getPropertyValue(style, 'height')
}
}
class Resizer {
constructor(wrapper, element, options) {
this.wrapper = wrapper;
this.element = element;
this.options = options;
this.offsetX = 0;
this.offsetY = 0;
this.handle = document.createElement('div');
this.handle.setAttribute('class', 'drag-resize-handlers');
this.handle.setAttribute('data-direction', 'br');
this.wrapper.appendChild(this.handle);
this.wrapper.style.top = this.element.style.top;
this.wrapper.style.left = this.element.style.left;
this.wrapper.style.width = this.element.style.width;
this.wrapper.style.height = this.element.style.height;
this.element.style.position = 'relative';
this.element.style.top = 0;
this.element.style.left = 0;
this.onResize = this.resizeHandler.bind(this);
this.onStop = this.stopResize.bind(this);
this.handle.addEventListener('mousedown', this.initResize.bind(this));
}
initResize(event) {
this.stopResize(event, true);
this.handle.addEventListener('mousemove', this.onResize);
this.handle.addEventListener('mouseup', this.onStop);
}
resizeHandler(event) {
this.offsetX = event.clientX - (this.wrapper.offsetLeft + this.handle.offsetLeft);
this.offsetY = event.clientY - (this.wrapper.offsetTop + this.handle.offsetTop);
let wrapperRect = getElementRect(this.wrapper);
let elementRect = getElementRect(this.element);
this.wrapper.style.width = (wrapperRect.width + this.offsetX) + 'px';
this.wrapper.style.height = (wrapperRect.height + this.offsetY) + 'px';
this.element.style.width = (elementRect.width + this.offsetX) + 'px';
this.element.style.height = (elementRect.height + this.offsetY) + 'px';
}
stopResize(event, nocb) {
this.handle.removeEventListener('mousemove', this.onResize);
this.handle.removeEventListener('mouseup', this.onStop);
}
}
class Dragger {
constructor(wrapper, element, options) {
this.wrapper = wrapper;
this.options = options;
this.element = element;
this.element.draggable = true;
this.element.setAttribute('draggable', true);
this.element.addEventListener('dragstart', this.dragStart.bind(this));
}
dragStart(event) {
let wrapperRect = getElementRect(this.wrapper);
var x = wrapperRect.x - parseFloat(event.clientX);
var y = wrapperRect.y - parseFloat(event.clientY);
event.dataTransfer.setData("text/plain", this.element.id + ',' + x + ',' + y);
}
dragStop(event, prevX, prevY) {
var posX = parseFloat(event.clientX) + prevX;
var posY = parseFloat(event.clientY) + prevY;
this.wrapper.style.left = posX + 'px';
this.wrapper.style.top = posY + 'px';
}
}
class DragResize {
constructor(element, options) {
options = options || {};
this.wrapper = document.createElement('div');
this.wrapper.setAttribute('class', 'tooltip drag-resize');
if (element.parentNode) {
element.parentNode.insertBefore(this.wrapper, element);
}
this.wrapper.appendChild(element);
element.resizer = new Resizer(this.wrapper, element, options);
element.dragger = new Dragger(this.wrapper, element, options);
}
}
document.body.addEventListener('dragover', function (event) {
event.preventDefault();
return false;
});
document.body.addEventListener('drop', function (event) {
event.preventDefault();
var dropData = event.dataTransfer.getData("text/plain").split(',');
var element = document.getElementById(dropData[0]);
element.dragger.dragStop(event, parseFloat(dropData[1]), parseFloat(dropData[2]));
return false;
});
It doesn't work because it doesn't make sense (so little sense that HTML 5 explicitly forbids it).
To fix it, decide if you want a link or a submit button and use whichever one you actually want (Hint: You don't have a form, so a submit button is nonsense).
netstat -ano | findstr 8080
taskkill /pid 21424 /F
execute the above command in command prompt first command will find the pid of the processes which are using port 8080 or any other port you are using. And in second command write the pid of instead of 21424.
The usual cause IF you are using lazy loading and function form import statements is importing the routing module instead of the page module. So:
Incorrect:
loadChildren: () => import('./../home-routing.module').then(m => m.HomePageRoutingModule)
Correct:
loadChildren: () => import('./../home.module').then(m => m.HomePageModule)
You might get away with this for a while, but eventually it will cause problems.
Something none of the other answers touch on is that your first loop is indexing though the list. Whereas the for-each loop is using an Iterator
. Some lists like LinkedList
will iterate faster with an Iterator
versus get(i)
. This is because because link list's iterator keeps track of the current pointer. Whereas each get
in your for i=0 to 9 has to recompute the offset into the linked list. In general, its better to use for-each or an Iterator
because it will be using Collection
s iterator, which in theory is optimized for the collection type.
I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).
Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)
The above link says,
ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so
What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).
How to Update your ADT to Latest Version
Help
Install New Software
---> Add
Add Repository
write the Name: ADT
(or whatever you want)https://dl-ssl.google.com/android/eclipse/
Developer Tools
and NDK Plugins
Developer Tool
onlyNext
Finish
I like this:
if (wlocation !== undefined)
But if you prefer the second way wouldn't be as you posted. It would be:
if (typeof wlocation !== "undefined")
The difference between a data flow diagram (DFD) and a flow chart (FC) are that a data flow diagram typically describes the data flow within a system and the flow chart usually describes the detailed logic of a business process.
file:///
is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://
.
It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www
has a file called index.html
located in the assets
folder in the root of the project".
That is how assets are loaded at runtime, for example, a WebView
widget would know exactly where to load the embedded resource file by specifying the file:///
URI.
Consider the code example:
WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");
A very easy mistake to make here is this, some would infer it to as file:///android_assets
, notice the plural of assets in the URI and wonder why the embedded resource is not working!
You have written like
@Html.RadioButtonFor(model => model.gender, "Male", new { @checked = true }) and
@Html.RadioButtonFor(model => model.gender, "Female", new { @checked = true })
Here you have taken gender as a Enum
type and you have written the value for the radio button as a string
type- change "Male" to 0 and "Female" to 1.
Print only selected element on codepen
HTML:
<div class="print">
<p>Print 1</p>
<a href="#" class="js-print-link">Click Me To Print</a>
</div>
<div class="print">
<p>Print 2</p>
<a href="#" class="js-print-link">Click Me To Print</a>
</div>
JQuery:
$('.js-print-link').on('click', function() {
var printBlock = $(this).parents('.print').siblings('.print');
printBlock.hide();
window.print();
printBlock.show();
});
Use the HttpClient
class from HttpClientModule
if you're using Angular 4.3.x and above:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
...
class MyService() {
constructor(http: HttpClient) {...}
It's an upgraded version of http
from @angular/http
module with the following improvements:
- Interceptors allow middleware logic to be inserted into the pipeline
- Immutable request/response objects
- Progress events for both request upload and response download
You can read about how it works in Insider’s guide into interceptors and HttpClient mechanics in Angular.
- Typed, synchronous response body access, including support for JSON body types
- JSON is an assumed default and no longer needs to be explicitly parsed
- Post-request verification & flush based testing framework
Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.
Also pay attention that old http was injected using Http
class token instead of the new HttpClient
:
import { HttpModule } from '@angular/http';
@NgModule({
imports: [
BrowserModule,
HttpModule
],
...
class MyService() {
constructor(http: Http) {...}
Also, new HttpClient
seem to require tslib
in runtime, so you have to install it npm i tslib
and update system.config.js
if you're using SystemJS
:
map: {
...
'tslib': 'npm:tslib/tslib.js',
And you need to add another mapping if you use SystemJS:
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
Update
Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.
He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.
He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.
The demos can be found on his GitHub Account.
The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.
Original Answer
Well go ahead and built it yourself then.
Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.
One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.
Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.
What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.
I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.
Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).
Rome (or RoR) wasn't built over night, and neither will Node.js be.
Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)
SingleOrDefault
method throws an Exception
if there is more than one element in the sequence.
Apparently, your query in GetCustomer
is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.
On Windows 10 this worked for me for VIM and VI using git bash
"Esc" + ":wq!"
or
"Esc" + ":q!"
Here is a Javascript solution (for folks like me who were looking for an answer to the title):
function SaveToDisk(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
source: http://muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html
Unfortunately the working for me with IE11, which is not accepting new MouseEvent. I use the following in that case:
//...
try {
var evt = new MouseEvent(...);
} catch (e) {
window.open(fileURL, fileName);
}
//...
I know that this question is 3 years old but the problem still persists for current browsers and folks are still coming here. The solution for now is calc():
input {
width: calc(100% - 12px); /* IE 9,10 , Chrome, Firefox */
width: -webkit-calc(100% - 12px); /*For safari 6.0*/
}
It is supported by most modern browsers.
UPDATE a
SET a.column1 = b.column2
FROM myTable a
INNER JOIN myTable b
on a.myID = b.myID
in order for both "a" and "b" to work, both aliases must be defined
concat
also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe
df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column
review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame
# Gets rows in df where IDs match in the userID column and combines them
dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])
My answer is inspired by Jeffrey's answer. Where that answer gives a more abstract solution, I try to provide more concrete steps on how to potentially implement it. This is simply a guide, one that can be implemented more elegantly. For a more detailed example check out this tutorial by MDN web docs.
HTML:
<div id="zoom_here">....</div>
JS
<script>
var dist1=0;
function start(ev) {
if (ev.targetTouches.length == 2) {//check if two fingers touched screen
dist1 = Math.hypot( //get rough estimate of distance between two fingers
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY);
}
}
function move(ev) {
if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
// Check if the two target touches are the same ones that started
var dist2 = Math.hypot(//get rough estimate of new distance between fingers
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY);
//alert(dist);
if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching
alert('zoom out');
}
if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture
alert('zoom in');
}
}
}
document.getElementById ('zoom_here').addEventListener ('touchstart', start, false);
document.getElementById('zoom_here').addEventListener('touchmove', move, false);
</script>
While many options above function well, I found coercion of non-target variables to chr
problematic. Using ifelse
and grepl
within lapply
resolves this off-target effect (in limited testing). Using slarky's regular expression in grepl
:
set.seed(42)
x1 <- sample(c("a","b"," ", "a a", NA), 10, TRUE)
x2 <- sample(c(rnorm(length(x1),0, 1), NA), length(x1), TRUE)
df <- data.frame(x1, x2, stringsAsFactors = FALSE)
The problem of coercion to character class:
df2 <- lapply(df, function(x) gsub("^$|^ $", NA, x))
lapply(df2, class)
$x1
[1] "character"
$x2 [1] "character"
Resolution with use of ifelse:
df3 <- lapply(df, function(x) ifelse(grepl("^$|^ $", x)==TRUE, NA, x))
lapply(df3, class)
$x1
[1] "character"
$x2 [1] "numeric"
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
Using data.frame
instead of cbind
should be helpful
x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
col1 col2 col3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
sapply(x, class) # looking into x to see the class of each element
col1 col2 col3
"numeric" "factor" "factor"
As you can see elements from col1 are numeric
as you wish.
data.frame
can have variables of different class
: numeric
, factor
and character
but matrix
doesn't, once you put a character
element into a matrix all the other will become into this class no matter what clase they were before.
I think this is pretty obvious :
Keep in mind : both the function has two arguments,
$observe/$watch(value : string, callback : function);
function (oldValue, newValue)
I have made a plunker, so you can actually get a grasp on both their utilization. I have used the Chameleon analogy as to make it easier to picture.
Using the accepted answer I create a helper class so you could use it in a similar way you would use the Lock statement. Just thought I'd share.
Use:
using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock
{
//Only 1 of these runs at a time
RunSomeStuff();
}
And the helper class:
class SingleGlobalInstance : IDisposable
{
//edit by user "jitbit" - renamed private fields to "_"
public bool _hasHandle = false;
Mutex _mutex;
private void InitMutex()
{
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
string mutexId = string.Format("Global\\{{{0}}}", appGuid);
_mutex = new Mutex(false, mutexId);
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
_mutex.SetAccessControl(securitySettings);
}
public SingleGlobalInstance(int timeOut)
{
InitMutex();
try
{
if(timeOut < 0)
_hasHandle = _mutex.WaitOne(Timeout.Infinite, false);
else
_hasHandle = _mutex.WaitOne(timeOut, false);
if (_hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
}
catch (AbandonedMutexException)
{
_hasHandle = true;
}
}
public void Dispose()
{
if (_mutex != null)
{
if (_hasHandle)
_mutex.ReleaseMutex();
_mutex.Close();
}
}
}
You're probably trying to convert to a UNIX-like timestamp, which are in UTC:
yourDateTime.ToUniversalTime().Subtract(
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
).TotalMilliseconds
This also avoids summertime issues, since UTC doesn't have those.
<div class="wrapper">test test test</div>
.wrapper{
width:100px;
height:100px;
margin:0 auto;
}
In python 3, we can use below method.
Read from file and convert to JSON
import json
from pprint import pprint
# Considering "json_list.json" is a json file
with open('json_list.json') as fd:
json_data = json.load(fd)
pprint(json_data)
with statement automatically close the opened file descriptor.
String to JSON
import json
from pprint import pprint
json_data = json.loads('{"name" : "myName", "age":24}')
pprint(json_data)
I've found examples, where PyPy is slower than Python. But: Only on Windows.
C:\Users\User>python -m timeit -n10 -s"from sympy import isprime" "isprime(2**521-1);isprime(2**1279-1)"
10 loops, best of 3: 294 msec per loop
C:\Users\User>pypy -m timeit -n10 -s"from sympy import isprime" "isprime(2**521-1);isprime(2**1279-1)"
10 loops, best of 3: 1.33 sec per loop
So, if you think of PyPy, forget Windows. On Linux, you can achieve awesome accelerations. Example (list all primes between 1 and 1,000,000):
from sympy import sieve
primes = list(sieve.primerange(1, 10**6))
This runs 10(!) times faster on PyPy than on Python. But not on windows. There it is only 3x as fast.
Try to add domains without http://
and https://
e.g. example.com
i = [].concat(loves).pop(); //corn
icon cat loves popcorn
You can make the .navbar
fixed width, then set it's left and right margin to auto
.
.navbar{
width: 80%;
margin: 0 auto;
}?
SELECT FieldA
, GROUP_CONCAT(FieldB ORDER BY FieldB SEPARATOR ',') AS FieldBs
FROM TableName
GROUP BY FieldA
ORDER BY FieldA;
SELECT FieldA
, LISTAGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs
FROM TableName
GROUP BY FieldA
ORDER BY FieldA;
SELECT FieldA
, STRING_AGG(FieldB, ',' ORDER BY FieldB) AS FieldBs
FROM TableName
GROUP BY FieldA
ORDER BY FieldA;
SQL Server ≥ 2017 & Azure SQL
SELECT FieldA
, STRING_AGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs
FROM TableName
GROUP BY FieldA
ORDER BY FieldA;
SQL Server ≤ 2016 (CTE included to encourage the DRY principle)
WITH CTE_TableName AS (
SELECT FieldA, FieldB
FROM TableName)
SELECT t0.FieldA
, STUFF((
SELECT ',' + t1.FieldB
FROM CTE_TableName t1
WHERE t1.FieldA = t0.FieldA
ORDER BY t1.FieldB
FOR XML PATH('')), 1, LEN(','), '') AS FieldBs
FROM CTE_TableName t0
GROUP BY t0.FieldA
ORDER BY FieldA;
Ordering requires a CTE or subquery
WITH CTE_TableName AS (
SELECT FieldA, FieldB
FROM TableName
ORDER BY FieldA, FieldB)
SELECT FieldA
, GROUP_CONCAT(FieldB, ',') AS FieldBs
FROM CTE_TableName
GROUP BY FieldA
ORDER BY FieldA;
Without ordering
SELECT FieldA
, GROUP_CONCAT(FieldB, ',') AS FieldBs
FROM TableName
GROUP BY FieldA
ORDER BY FieldA;
if (android.os.Build.VERSION.SDK_INT >= 21) {
storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position], context.getTheme()));
} else {
storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position]));
}
This answer is for the first question, why it takes so much time and it offers an alternative solution for exporting the DataGridView to Excel.
MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to export large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.
Interop saves Excel files in XLS file format (old Excel 97-2003 file format) and the support for Office 2003 has ended. Microsoft Excel released XLSX file format with Office 2007 and recommends the usage of OpenXML SDK instead of Interop. But XLSX files are not really so fast and doesn’t handle very well large Excel files because they are based on XML file format. This is why Microsoft also released XLSB file format with Office 2007, file format that is recommended for large Excel files. It is a binary format. So the best and fastest solution is to save XLSB files.
You can use this C# Excel library to save XLSB files, but it also supports XLS and XLSX file formats.
See the following code sample as alternative of exporting DataGridView to Excel:
// Create a DataSet and add the DataTable of DataGridView
DataSet dataSet = new DataSet();
dataSet.Tables.Add((DataTable)dataGridView);
//or ((DataTable)dataGridView.DataSource).Copy() to create a copy
// Export Excel file
ExcelDocument workbook = new ExcelDocument();
workbook.easy_WriteXLSBFile_FromDataSet(filePath, dataSet,
new EasyXLS.ExcelAutoFormat(EasyXLS.Constants.Styles.AUTOFORMAT_EASYXLS1),
"Sheet1");
If you also need to export the formatting of the DataGridView check this code sample on how to export datagridview to Excel in C#.
Use push_back()
:
std::string y("Hello worl");
y.push_back('d')
std::cout << y;
slicing operator. http://docs.python.org/tutorial/introduction.html#strings and scroll down a bit
I'd prefer to use [:punct:]
for that. Also, a-zA-Z09-9
could be just [:alnum:]
:
[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]
It is today possible to configure Safari to access local files.
- By default Safari doesn't allow access to local files.
- To enable this option: First you need to enable the develop menu.
- Click on the Develop menu Select Disable Local File Restrictions.
Source: http://ccm.net/faq/36342-safari-how-to-enable-local-file-access
I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/
Ive refactored the code to make it simpler for this.
// In your controller
var w = angular.element($window);
$scope.$watch(
function () {
return $window.innerWidth;
},
function (value) {
$scope.windowWidth = value;
},
true
);
w.bind('resize', function(){
$scope.$apply();
});
You can then reference to windowWidth from the html
<span ng-bind="windowWidth"></span>
<head>
<title>Site</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
etc...
</head>
I've used that very recently and it works fine on iPad. Haven't tested on Android or other devices (because the website will be displayed on iPad only).
I guess this is probably a non issue for most but I tried to solve it. I think I have a pretty decent solution. In case anyone else stumbles upon this issue.
function randomNums($gen, $trim, $low, $high)
{
$results_to_gen = $gen;
$low_range = $low;
$high_range = $high;
$trim_results_to= $trim;
$items = array();
$results = range( 1, $results_to_gen);
$i = 1;
foreach($results as $result)
{
$result = mt_rand( $low_range, $high_range);
$items[] = $result;
}
$unique = array_unique( $items, SORT_NUMERIC);
$countem = count( $unique);
$unique_counted = $countem -$trim_results_to;
$sum = array_slice($unique, $unique_counted);
foreach ($sum as $key)
{
$output = $i++.' : '.$key.'<br>';
echo $output;
}
}
randomNums(1100, 1000 ,890000, 899999);
There are good answers here, but maybe this one will also help somebody.
For me it happened just after i deleted .idea (with IntelliJ), and reimported the project.
then this issue started, i tried to run mvn compile (just via IDE Maven toolbar), once i fixed few compilation errors, issue disappeared
Java 7 introduced ThreadLocalRandom which is isolated to the current thread.
This is an another rendition of maerics's solution.
final byte[] bytes = new byte[20];
ThreadLocalRandom.current().nextBytes(bytes);
I am an Android novice and came across this question trying to get rid of a title bar.
I'm using an activity and displaying it as a dialog. I was poking around with themes and came across a useful bit of default theming.
Here's the code from my AndroidManifest.xml
that I was using when the title bar was showing:
<activity
android:name=".AlertDialog"
android:theme="@android:style/Theme.Holo.Dialog"
>
</activity>
Here's the change that got me my desired result:
<activity
android:name=".AlertDialog"
android:theme="@android:style/Theme.Holo.Dialog.NoActionBar"
>
</activity>
As I said, I'm still new to Android, so this may have undesirable side-effects, but it appears to have given me the outcome I wanted, which was just to remove the title bar from the dialog.
I have <M-DOWN>
(alt down arrow) mapped to <DOWN>.
so that I can repeat the last command on a series of lines very quickly. with this mapping I can:
A,<ESC>
And then hold alt while pressing down repeatedly to append the comma to the end of each line.
This works well for me because it allows very good control over what lines do and do not get the change.
(I also have the other arrows mapped similarly to allow for easy repeating of .
)
Here's the mapping line to paste into your vimrc:
map <M-DOWN> <DOWN>.
Nope, that is pretty much the best way to do it. As a machine could have several IP addresses you need to iterate the collection of them to find the proper one.
Edit: The only thing I would change would be to change this:
if (ip.AddressFamily.ToString() == "InterNetwork")
to this:
if (ip.AddressFamily == AddressFamily.InterNetwork)
There is no need to ToString
an enumeration for comparison.
"We have Google" cit. For properly use script inside wordpress just add hosted libraries. Like Google
After selected library that you need link it before your custom script: exmpl
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
and after your own script
<script type="text/javascript">
$(document).ready(function () {
$('.text_container').addClass("hidden");
});
</script>
$str = '<img border="0" src=\'/images/image.jpg\' alt="Image" width="100" height="100"/>';
preg_match('/(src=["\'](.*?)["\'])/', $str, $match); //find src="X" or src='X'
$split = preg_split('/["\']/', $match[0]); // split by quotes
$src = $split[1]; // X between quotes
echo $src;
Other regexp's can be used to determine if the pulled src tag is a picture like so:
if(preg_match('/([jpg]{3}$)|([gif]{3}$)|([jpeg]{3}$)|([bmp]{3}$)|([png]{3}$)/', $src) == 1) {
//its an image
}
The difference isn't in performance, but in capability. When using a reference directly you have more power over explicitly using a type of iterator (e.g. List.iterator() vs. List.listIterator(), although in most cases they return the same implementation). You also have the ability to reference the Iterator in your loop. This allows you to do things like remove items from your collection without getting a ConcurrentModificationException.
This is ok:
Set<Object> set = new HashSet<Object>();
// add some items to the set
Iterator<Object> setIterator = set.iterator();
while(setIterator.hasNext()){
Object o = setIterator.next();
if(o meets some condition){
setIterator.remove();
}
}
This is not, as it will throw a concurrent modification exception:
Set<Object> set = new HashSet<Object>();
// add some items to the set
for(Object o : set){
if(o meets some condition){
set.remove(o);
}
}
<table>
<tbody>
<tr>
<td>
<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
Use jQuery's beforeSend
callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
As option, if you need just default text in dropdown without default value, try add <option disabled value="null">default text here</option>
like this:
<select id="country" formControlName="country">
<option disabled value="null">default text here</option>
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
In Chrome and Firefox works fine.
You could try using HTML5s sessionStorage it lasts for the duration on the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
sessionStorage.setItem("username", "John");
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage
Browser Compatibility https://code.google.com/p/sessionstorage/ compatible with every A-grade browser, included iPhone or Android. http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
SCRUM :
SCRUM is a type of Agile approach. It is a Framework not a Methodology.
It does not provide detailed instructions to what needs to be done rather most of it is dependent on the team that is developing the software. Because the developing the project knows how the problem can be solved that is why much is left on them
Cross-functional and self-organizing teams are essential in case of scrum. There is no team leader in this case who will assign tasks to the team members rather the whole team addresses the issues or problems. It is cross-functional in a way that everyone is involved in the project right from the idea to the implementation of the project.
The advantage of scrum is that a project’s direction to be adjusted based on completed work, not on speculation or predictions.
Roles Involved : Product Owner, Scrum Master, Team Members
Agile Methodology :
Build Software applications that are unpredictable in nature
Iterative and incremental work cadences called sprints are used in this methodology.
Both Agile and SCRUM follows the system -- some of the features are developed as a part of the sprint and at the end of each sprint; the features are completed right from coding, testing and their integration into the product. A demonstration of the functionality is provided to the owner at the end of each sprint so that feedback can be taken which can be helpful for the next sprint.
Manifesto for Agile Development :
That is, while there is value in the items on the right, we value the items on the left more.
Simple Import os package and run below command.
import os
os.system("python test.py")
Yield can be used as nameless block to return a value in the method. Consider the following code:
Def Up(anarg)
yield(anarg)
end
You can create a method "Up" which is assigned one argument. You can now assign this argument to yield which will call and execute an associated block. You can assign the block after the parameter list.
Up("Here is a string"){|x| x.reverse!; puts(x)}
When the Up method calls yield, with an argument, it is passed to the block variable to process the request.
To install nodejs on ubuntu, you can type the following command in the terminal:
sudo apt-get install nodejs
To install nodejs on systems using yum, type the following in the terminal:
yum -y install nodejs
You can also use set
for this, which avoids the overhead of [.data.table
in loops:
dt <- data.table( a=letters, b=LETTERS, c=seq(26), d=letters, e=letters )
set( dt, j=c(1L,3L,5L), value=NULL )
> dt[1:5]
b d
1: A a
2: B b
3: C c
4: D d
5: E e
If you want to do it by column name, which(colnames(dt) %in% c("a","c","e"))
should work for j
.
I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.
//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
}, function(){alert(":(");});
Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.
How do I loop through rows with a data reader in C#?
IDataReader.Read()
advances the reader to the next row in the resultset.
while(reader.Read()){
/* do whatever you'd like to do for each row. */
}
So, for each iteration of your loop, you'd do another loop, 0 to reader.FieldCount
, and call reader.GetValue(i)
for each field.
The bigger question is what kind of structure do you want to use to hold that data?
My recommendation? Don't use jQuery at all. I had the same problem as you. I found that $('#my_input').val()
always return some weird result.
Try to use document.getElementById('my_input').valueAsNumber
instead of $("#my_input").val();
and then, use Number(your_value_retrieved)
to try to create a Number. If the value is NaN, you know certainly that that's not a number.
One thing to add is when you write a number on the input, the input will actually accept almost any character (I can write the euro sign, a dollar, and all of other special characters), so it is best to retrieve the value using .valueAsNumber
instead of using jQuery.
Oh, and BTW, that allows your users to add internationalization (i.e.: support commas instead of dots to create decimal numbers). Just let the Number()
object to create something for you and it will be decimal-safe, so to speak.
You should check with SMTP.
That means you have to connect to that email's SMTP server.
After connecting to the SMTP server you should send these commands:
HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>
If you get "<[email protected]> Relay access denied" that means this email is Invalid.
There is a simple PHP class. You can use it:
http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html
You can use this in your MySQL WHERE clause to return records that were created within the last 7 days/week:
created >= DATE_SUB(CURDATE(),INTERVAL 7 day)
Also use NOW() in the subtraction to give hh:mm:ss resolution. So to return records created exactly (to the second) within the last 24hrs, you could do:
created >= DATE_SUB(NOW(),INTERVAL 1 day)
FYI | ctrl + K, C is the comment shortcut in Visual Studio. ctrl + K, U uncomments.
Here is my method:
import re
# Compile
p = re.compile(r'hi')
# Match and print
print bool(p.match("abcdefghijkl"))
You can try the following:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.
div
has an ID.class
"collapse", this will hide your block by
default. If you want your div to be collapsible AND be shown by
default you need to add "in" class to the collapse. Otherwise the
toggle behavior will not work properly.data-toggle="collapse"
to instruct
Bootstrap to add an appropriate toggle script to this tag.Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
This div (Bar) is shown by default and can toggle
</div>
The ruby core itself has no support to convert a string from snake case to (upper) camel case (also known as pascal case).
So you need either to make your own implementation or use an existing gem.
There is a small ruby gem called lucky_case which allows you to convert a string from any of the 10+ supported cases to another case easily:
require 'lucky_case'
# to get upper camel case (pascal case) as string
LuckyCase.pascal_case('app_user') # => 'AppUser'
# to get the pascal case constant
LuckyCase.constantize('app_user') # => AppUser
# or the opposite way
LuckyCase.snake_case('AppUser') # => app_user
You can even monkey patch the String class if you want to:
require 'lucky_case/string'
'app_user'.pascal_case # => 'AppUser'
'app_user'.constantize # => AppUser
# ...
Have a look at the offical repository for more examples and documentation:
I needed to have some initialization code run after a chunk of html (template instance) was inserted, and of course I didn't have access to the code that manipulates the template and modifies the DOM. The same idea holds for any partial modification of the DOM by insertion of an html element, usually a <div>
.
Some time ago, I did a hack with the onload event of a nearly invisible <img>
contained in a <div>
, but discovered that a scoped, empty style will also do:
<div .... >
<style scoped="scoped" onload="dosomethingto(this.parentElement);" > </style>
.....
</div>
Update(Jul 15 2017) -
The <style>
onload is not supported in last version of IE. Edge does support it, but some users see this as a different browser and stick with IE. The <img>
element seems to work better across all browsers.
<div...>
<img onLoad="dosomthing(this.parentElement);" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />
...
</div>
To minimize the visual impact and resource usage of the image, use an inline src that keeps it small and transparent.
One comment I feel I need to make about using a <script>
is how much harder it is to determine which <div>
the script is near, especially in templating where you can't have an identical id in each instance that the template generates. I thought the answer might be document.currentScript, but this is not universally supported. A <script>
element cannot determine its own DOM location reliably; a reference to 'this' points to the main window, and is of no help.
I believe it is necessary to settle for using an <img>
element, despite being goofy. This might be a hole in the DOM/javascript framework that could use plugging.
I took a combo of all answers, and now have two ways of doing this with the ng-model attribute:
var app = angular.module('model', []);_x000D_
_x000D_
app.controller('MainCtrl', function($scope) {_x000D_
$scope.name = "Felipe";_x000D_
$scope.label = "The Label";_x000D_
});_x000D_
_x000D_
app.directive('myDirectiveWithScope', function() {_x000D_
return {_x000D_
restrict: 'E',_x000D_
scope: {_x000D_
ngModel: '=',_x000D_
},_x000D_
// Notice how label isn't copied_x000D_
template: '<div class="some"><label>{{label}}: <input ng-model="ngModel"></label></div>',_x000D_
replace: true_x000D_
};_x000D_
});_x000D_
app.directive('myDirectiveWithChildScope', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
scope: true,_x000D_
// Notice how label is visible in the scope_x000D_
template: '<div class="some"><label>{{label}}: <input></label></div>',_x000D_
replace: true,_x000D_
link: function ($scope, element) {_x000D_
// element will be the div which gets the ng-model on the original directive_x000D_
var model = element.attr('ng-model');_x000D_
$('input',element).attr('ng-model', model);_x000D_
return $compile(element)($scope);_x000D_
}_x000D_
};_x000D_
});_x000D_
app.directive('myDirectiveWithoutScope', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
template: '<div class="some"><label>{{$parent.label}}: <input></label></div>',_x000D_
replace: true,_x000D_
link: function ($scope, element) {_x000D_
// element will be the div which gets the ng-model on the original directive_x000D_
var model = element.attr('ng-model');_x000D_
return $compile($('input',element).attr('ng-model', model))($scope);_x000D_
}_x000D_
};_x000D_
});_x000D_
app.directive('myReplacedDirectiveIsolate', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
scope: {},_x000D_
template: '<input class="some">',_x000D_
replace: true_x000D_
};_x000D_
});_x000D_
app.directive('myReplacedDirectiveChild', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
scope: true,_x000D_
template: '<input class="some">',_x000D_
replace: true_x000D_
};_x000D_
});_x000D_
app.directive('myReplacedDirective', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
template: '<input class="some">',_x000D_
replace: true_x000D_
};_x000D_
});
_x000D_
.some {_x000D_
border: 1px solid #cacaca;_x000D_
padding: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>_x000D_
<div ng-app="model" ng-controller="MainCtrl">_x000D_
This scope value <input ng-model="name">, label: "{{label}}"_x000D_
<ul>_x000D_
<li>With new isolate scope (label from parent):_x000D_
<my-directive-with-scope ng-model="name"></my-directive-with-scope>_x000D_
</li>_x000D_
<li>With new child scope:_x000D_
<my-directive-with-child-scope ng-model="name"></my-directive-with-child-scope>_x000D_
</li>_x000D_
<li>Same scope:_x000D_
<my-directive-without-scope ng-model="name"></my-directive-without-scope>_x000D_
</li>_x000D_
<li>Replaced element, isolate scope:_x000D_
<my-replaced-directive-isolate ng-model="name"></my-replaced-directive-isolate>_x000D_
</li>_x000D_
<li>Replaced element, child scope:_x000D_
<my-replaced-directive-child ng-model="name"></my-replaced-directive-child>_x000D_
</li>_x000D_
<li>Replaced element, same scope:_x000D_
<my-replaced-directive ng-model="name"></my-replaced-directive>_x000D_
</li>_x000D_
</ul>_x000D_
<p>Try typing in the child scope ones, they copy the value into the child scope which breaks the link with the parent scope._x000D_
<p>Also notice how removing jQuery makes it so only the new-isolate-scope version works._x000D_
<p>Finally, note that the replace+isolate scope only works in AngularJS >=1.2.0_x000D_
</div>
_x000D_
I'm not sure I like the compiling at link time. However, if you're just replacing the element with another you don't need to do that.
All in all I prefer the first one. Simply set scope to {ngModel:"="}
and set ng-model="ngModel"
where you want it in your template.
Update: I inlined the code snippet and updated it for Angular v1.2. Turns out that isolate scope is still best, especially when not using jQuery. So it boils down to:
Are you replacing a single element: Just replace it, leave the scope alone, but note that replace is deprecated for v2.0:
app.directive('myReplacedDirective', function($compile) {
return {
restrict: 'E',
template: '<input class="some">',
replace: true
};
});
Otherwise use this:
app.directive('myDirectiveWithScope', function() {
return {
restrict: 'E',
scope: {
ngModel: '=',
},
template: '<div class="some"><input ng-model="ngModel"></div>'
};
});
I don't like casting primitives, who knows what may happen.
Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int
to a double
. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int
to double
is a widening primitive conversion.
You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:
double d = num / (double) denom;
$("input:text").focus(function(){$(this).val("")});
Simply change bg color
select {
background: #6ac17a;
color:#fff;
}
You can select the shapes within a slide (Word Art also) and right click on the selection and choose "Save As Picture". It will save as a transparent PNG.
This will happen when you doubleclick a JAR file in Windows explorer, but the JAR is by itself actually not an executable JAR. A real executable JAR should have at least a class with a main()
method and have it referenced in MANIFEST.MF
.
In Eclispe, you need to export the project as Runnable JAR file instead of as JAR file to get a real executable JAR.
Or, if your JAR is solely a container of a bunch of closely related classes (a library), then you shouldn't doubleclick it, but open it using some ZIP tool. Windows explorer namely by default associates JAR files with java.exe
, which won't work for those kind of libary JARs.
In Groovy, you can use trait instead of class. As they act similar to abstract classes (in the way that you can specify abstract methods, but you can still implement others), you can do something like:
trait EmployeeTrait {
int getId() {
return 1000 //Default value
}
abstract String getName() //Required
}
trait CustomerTrait {
String getCompany() {
return "Internal" // Default value
}
abstract String getAddress()
}
class InternalCustomer implements EmployeeTrait, CustomerTrait {
String getName() { ... }
String getAddress() { ... }
}
def internalCustomer = new InternalCustomer()
println internalCustomer.id // 1000
println internalCustomer.company //Internal
Just to point out, its not exactly the same as extending two classes, but in some cases (like the above example), it can solve the situation. I strongly suggest to analyze your design before jumping into using traits, usually they are not required and you won't be able to nicely implement inheritance (for example, you can't use protected methods in traits). Follow the accepted answer's recommendation if possible.
I easily solve this problem by right clicking on my solution and then clicking on the Enable NuGet Package Restore option
(P.S: Ensure that you have the Nuget Install From Tools--> Extensions and Update--> Nuget Package Manager for Visual Studio 2013. If not install this extention first)
Hope it helps.
With LINQ:
List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();
If you need foreach, then no need for ToList:
foreach (string s in l.Skip(1).Take(2)){}
Advantage of LINQ is that if you want to just skip some leading element,you can :
List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}
i.e. no need to take care of count/length, etc.
In C and C++ and many languages, %
is the remainder NOT the modulus operator.
For example in the operation -21 / 4
the integer part is -5
and the decimal part is -.25
. The remainder is the fractional part times the divisor, so our remainder is -1
. JavaScript uses the remainder operator and confirms this
console.log(-21 % 4 == -1);
_x000D_
The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.
Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.
You can try the below function to get value from JSON string,
public static String GetJSONValue(String JSONString, String Field)
{
return JSONString.substring(JSONString.indexOf(Field), JSONString.indexOf("\n", JSONString.indexOf(Field))).replace(Field+"\": \"", "").replace("\"", "").replace(",","");
}
It's a simple problem. When you are running from terminal, you are running the php file from terminal as a privileged user. When you go to the php from your web browser, the php script is being run as the web server user which does not have permissions to execute files in your home directory. In Ubuntu, the www-data user is the apache web server user. If you're on ubuntu you would have to do the following: chown yourusername:www-data /home/testuser/testscript chmod g+x /home/testuser/testscript
what the above does is transfers user ownership of the file to you, and gives the webserver group ownership of it. the next command gives the group executable permission to the file. Now the next time you go ahead and do it from the browser, it should work.
FWIW, in Boostrap 4.4, you can add .text-wrap
style to things like buttons:
<a href="#" class="btn btn-primary text-wrap">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
https://getbootstrap.com/docs/4.4/utilities/text/#text-wrapping-and-overflow
I don't think this DateTimePicker has been mentioned before:
A WPF DateTimePicker That Works Like the One in Winforms
That one is in VB and has some bugs. I converted it to C# and made a new version with bug fixes.
Note: I used the Calendar control in WPFToolkit so that I could use .NET 3.5 instead of .NET 4. If you are using .NET 4, just remove references to "wpftc" in the XAML.
The issue appears with parsing the JSON from request body, tipical for an invalid JSON. If you're using curl on windows, try escaping the json like -d "{"name":"value"}"
or even -d "{"""name""":"value"""}"
On the other hand you can ommit the content-type header in which case whetewer is sent will be converted to your String argument
If you want to turn off the warnings about the specific strings, you can use the following:
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--suppress MissingTranslation -->
<string name="some_string">ignore my translation</string>
...
</resources>
If you want to warn on specific strings instead of an error, you will need to build a custom Lint rule to adjust the severity status for a specific thing.
eval
and exec
are the correct solution, and they can be used in a safer manner.
As discussed in Python's reference manual and clearly explained in this tutorial, the eval
and exec
functions take two extra parameters that allow a user to specify what global and local functions and variables are available.
For example:
public_variable = 10
private_variable = 2
def public_function():
return "public information"
def private_function():
return "super sensitive information"
# make a list of safe functions
safe_list = ['public_variable', 'public_function']
safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
# add any needed builtins back in
safe_dict['len'] = len
>>> eval("public_variable+2", {"__builtins__" : None }, safe_dict)
12
>>> eval("private_variable+2", {"__builtins__" : None }, safe_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'private_variable' is not defined
>>> exec("print \"'%s' has %i characters\" % (public_function(), len(public_function()))", {"__builtins__" : None}, safe_dict)
'public information' has 18 characters
>>> exec("print \"'%s' has %i characters\" % (private_function(), len(private_function()))", {"__builtins__" : None}, safe_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'private_function' is not defined
In essence you are defining the namespace in which the code will be executed.
Use Immersive Full-Screen Mode
call fullScreen()
on ImageView
click.
public void fullScreen() {
// BEGIN_INCLUDE (get_current_ui_flags)
// The UI options currently enabled are represented by a bitfield.
// getSystemUiVisibility() gives us that bitfield.
int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
int newUiOptions = uiOptions;
// END_INCLUDE (get_current_ui_flags)
// BEGIN_INCLUDE (toggle_ui_flags)
boolean isImmersiveModeEnabled =
((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
if (isImmersiveModeEnabled) {
Log.i(TAG, "Turning immersive mode mode off. ");
} else {
Log.i(TAG, "Turning immersive mode mode on.");
}
// Navigation bar hiding: Backwards compatible to ICS.
if (Build.VERSION.SDK_INT >= 14) {
newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
// Status bar hiding: Backwards compatible to Jellybean
if (Build.VERSION.SDK_INT >= 16) {
newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
}
// Immersive mode: Backward compatible to KitKat.
// Note that this flag doesn't do anything by itself, it only augments the behavior
// of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this sample
// all three flags are being toggled together.
// Note that there are two immersive mode UI flags, one of which is referred to as "sticky".
// Sticky immersive mode differs in that it makes the navigation and status bars
// semi-transparent, and the UI flag does not get cleared when the user interacts with
// the screen.
if (Build.VERSION.SDK_INT >= 18) {
newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
//END_INCLUDE (set_ui_flags)
}
Read more
Example Download
$ git config --get-regexp alias
If you're fetching data using Wordpress, then you can access the number of rows returned using $wpdb->num_rows:
$wpdb->get_results( $wpdb->prepare('select * from mytable where foo = %s', $searchstring));
echo $wpdb->num_rows;
If you want a specific count based on a mysql count query then you do this:
$numrows = $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM mytable where foo = %s', $searchstring );
echo $numrows;
If you're running updates or deletes then the count of rows affected is returned directly from the function call:
$numrowsaffected = $wpdb->query($wpdb->prepare(
'update mytable set val=%s where myid = %d', $valuetoupdate, $myid));
This applies also to $wpdb->update and $wpdb->delete.
The accepted answer is best, but since there's more than one way to do it, here's another solution:
if [ "$string" != "${string/foo/}" ]; then
echo "It's there!"
fi
${var/search/replace}
is $var
with the first instance of search
replaced by replace
, if it is found (it doesn't change $var
). If you try to replace foo
by nothing, and the string has changed, then obviously foo
was found.
In reply to Dimitrys answer but using Ajax.BeginForm
the following works at least with MVC >5 (4 not tested).
write a model as shown in the other answers,
In the "parent view" you will probably use a table to show the data.
Model should be an ienumerable. I assume, the model has an id
-property. Howeverm below the template, a placeholder for the modal and corresponding javascript
<table>
@foreach (var item in Model)
{
<tr> <td id="[email protected]">
@Html.Partial("dataRowView", item)
</td> </tr>
}
</table>
<div class="modal fade" id="editor-container" tabindex="-1"
role="dialog" aria-labelledby="editor-title">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content" id="editor-content-container"></div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('.editor-container').click(function () {
var url = "/area/controller/MyEditAction";
var id = $(this).attr('data-id');
$.get(url + '/' + id, function (data) {
$('#editor-content-container').html(data);
$('#editor-container').modal('show');
});
});
});
function success(data,status,xhr) {
$('#editor-container').modal('hide');
$('#editor-content-container').html("");
}
function failure(xhr,status,error) {
$('#editor-content-container').html(xhr.responseText);
$('#editor-container').modal('show');
}
</script>
note the "editor-success-id" in data table rows.
The dataRowView
is a partial containing the presentation of an model's item.
@model ModelView
@{
var item = Model;
}
<div class="row">
// some data
<button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
</div>
Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ...
).
@model Model
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="editor-title">Title</h4>
</div>
@using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "editor-success-" + @Model.Id,
OnSuccess = "success",
OnFailure = "failure",
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
<div class="modal-body">
<div class="form-horizontal">
// Models input fields
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
}
This is where magic happens: in AjaxOptions
, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.
This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.
But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:
the corresponding controller action method for the partial edit modal
[HttpGet]
public async Task<ActionResult> EditPartData(Guid? id)
{
// Find the data row and return the edit form
Model input = await db.Models.FindAsync(id);
return PartialView("EditModel", input);
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> MyEditAction([Bind(Include =
"Id,Fields,...")] ModelView input)
{
if (TryValidateModel(input))
{
// save changes, return new data row
// status code is something in 200-range
db.Entry(input).State = EntityState.Modified;
await db.SaveChangesAsync();
return PartialView("dataRowView", (ModelView)input);
}
// set the "error status code" that will redisplay the modal
Response.StatusCode = 400;
// and return the edit form, that will be displayed as a
// modal again - including the modelstate errors!
return PartialView("EditModel", (Model)input);
}
This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.
Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js
(may be installed by NuGet):
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.js"));
Double brackets accesses a list element, while a single bracket gives you back a list with a single element.
lst <- list('one','two','three')
a <- lst[1]
class(a)
## returns "list"
a <- lst[[1]]
class(a)
## returns "character"
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
Java does have pointers. Any time you create an object in Java, you're actually creating a pointer to the object; this pointer could then be set to a different object or to null
, and the original object will still exist (pending garbage collection).
What you can't do in Java is pointer arithmetic. You can't dereference a specific memory address or increment a pointer.
If you really want to get low-level, the only way to do it is with the Java Native Interface; and even then, the low-level part has to be done in C or C++.