Lodash has a simple Dictionary implementation and has good TypeScript support
Install Lodash:
npm install lodash @types/lodash --save
Import and usage:
import { Dictionary } from "lodash";
let properties : Dictionary<string> = {
"key": "value"
}
console.log(properties["key"])
The command line arguments are separated by space. If you want provide an argument with a space in it, you should quote it. So use git commit -m "initial commit"
.
You need to set the parent element to 100%
as well
html, body {
height: 100%;
}
Demo (Changed the background
for demo purpose)
Also, when you want to cover entire screen, seems like you want to dim
, so in this case, you need to use position: fixed;
#dimScreen {
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
position: fixed;
top: 0;
left: 0;
z-index: 100; /* Just to keep it at the very top */
}
If that's the case, than you don't need html, body {height: 100%;}
I wrote recently a simple function which removes excess white space from string without regular expression implode(' ', array_filter(explode(' ', $str)))
.
What you have should work but can be reduced to:
select * from table where concat_ws(' ',first_name,last_name)
like '%$search_term%';
Can you provide an example name and search term where this doesn't work?
for MacOS, make sure you know where the GO install
export GOPATH=/usr/local/go
PATH=$PATH:$GOPATH/bin
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
SSH File
~/.ssh/config file
Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
LogLevel QUIET
ConnectTimeout=10
Host github.com
User git
AddKeystoAgent yes
UseKeychain yes
Identityfile ~/github_rsa
Edit reponame/.git/config
[remote "origin"]
url = [email protected]:username/repo.git
i start using npm package called react-html-parser
Rename multiple file extensions:
You want to change ringtone1.mp3
, ringtone2.mp3
to ringtone1.wav
, ringtone2.wav
Here is how to do that: I am in d drive on command prompt (CMD) so I use:
d:\>ren *.* *.wav
This is just an example of file extensions, you can use any type of file extension like WAV, MP3, JPG, GIF, bmp, PDF, DOC, DOCX, TXT this depends on what your operating system.
And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.
first Remove next add
for simple
public static IEnumerable UserIntakeFoodEdit(FoodIntaked data)
{
DBContext db = new DBContext();
var q = db.User_Food_UserIntakeFood.AsQueryable();
var item = q.Where(f => f.PersonID == data.PersonID)
.Where(f => f.DateOfIntake == data.DateOfIntake)
.Where(f => f.MealTimeID == data.MealTimeIDOld)
.Where(f => f.NDB_No == data.NDB_No).FirstOrDefault();
item.Amount = (decimal)data.Amount;
item.WeightSeq = data.WeightSeq.ToString();
item.TotalAmount = (decimal)data.TotalAmount;
db.User_Food_UserIntakeFood.Remove(item);
db.SaveChanges();
item.MealTimeID = data.MealTimeID;//is key
db.User_Food_UserIntakeFood.Add(item);
db.SaveChanges();
return "Edit";
}
In a multitable insert, you insert computed rows derived from the rows returned from the evaluation of a subquery into one or more tables.
Unconditional INSERT ALL:- To add multiple rows to a table at once, you use the following form of the INSERT statement:
INSERT ALL
INTO table_name (column_list) VALUES (value_list_1)
INTO table_name (column_list) VALUES (value_list_2)
INTO table_name (column_list) VALUES (value_list_3)
...
INTO table_name (column_list) VALUES (value_list_n)
SELECT 1 FROM DUAL; -- SubQuery
Specify ALL followed by multiple insert_into_clauses to perform an unconditional multitable insert. Oracle Database executes each insert_into_clause once for each row returned by the subquery.
INSERT INTO table_name (column_list)
VALUES
(value_list_1),
(value_list_2),
...
(value_list_n);
Single Row insert Query
INSERT INTO table_name (col1,col2) VALUES(val1,val2);
You can run this example directly.
aspx page:
<asp:GridView ID="grd" runat="server" DataKeyNames="PayScale" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Pay Scale">
<ItemTemplate>
<asp:TextBox ID="txtPayScale" runat="server" Text='<%# Eval("PayScale") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Increment Amount">
<ItemTemplate>
<asp:TextBox ID="txtIncrementAmount" runat="server" Text='<%# Eval("IncrementAmount") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Period">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" Text='<%# Eval("Period") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />
C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grd.DataSource = GetTableWithInitialData(); // get first initial data
grd.DataBind();
}
}
public DataTable GetTableWithInitialData() // this might be your sp for select
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
table.Rows.Add(1, "David", "1");
table.Rows.Add(2, "Sam", "2");
table.Rows.Add(3, "Christoff", "1.5");
return table;
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
DataTable dt = GetTableWithNoData(); // get select column header only records not required
DataRow dr;
foreach (GridViewRow gvr in grd.Rows)
{
dr = dt.NewRow();
TextBox txtPayScale = gvr.FindControl("txtPayScale") as TextBox;
TextBox txtIncrementAmount = gvr.FindControl("txtIncrementAmount") as TextBox;
TextBox txtPeriod = gvr.FindControl("txtPeriod") as TextBox;
dr[0] = txtPayScale.Text;
dr[1] = txtIncrementAmount.Text;
dr[2] = txtPeriod.Text;
dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
}
dr = dt.NewRow(); // add last empty row
dt.Rows.Add(dr);
grd.DataSource = dt; // bind new datatable to grid
grd.DataBind();
}
public DataTable GetTableWithNoData() // returns only structure if the select columns
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
return table;
}
<link rel="preload" href="mystyles.css" as="style" onload="this.rel='stylesheet'">
do adb pull \sdcard\log.txt C:Users\admin\Desktop
I think you would need to add something like PHP into the equation. PHP to interact with the database and then you could make AJAX calls with Javascript.
I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):
Sub getData()
Dim Movie As Object
Dim scriptControl As Object
Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
scriptControl.Language = "JScript"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
.send
Set Movie = scriptControl.Eval("(" + .responsetext + ")")
.abort
With Sheets(2)
.Cells(1, 1).Value = Movie.Title
.Cells(1, 2).Value = Movie.Year
.Cells(1, 3).Value = Movie.Rated
.Cells(1, 4).Value = Movie.Released
.Cells(1, 5).Value = Movie.Runtime
.Cells(1, 6).Value = Movie.Director
.Cells(1, 7).Value = Movie.Writer
.Cells(1, 8).Value = Movie.Actors
.Cells(1, 9).Value = Movie.Plot
.Cells(1, 10).Value = Movie.Language
.Cells(1, 11).Value = Movie.Country
.Cells(1, 12).Value = Movie.imdbRating
End With
End With
End Sub
((SelectionListViewController *)myEditController).list
More examples:
int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly
First of all, be sure that you have downloaded it or not. Open up your terminal application, and enter $ gcc
if you have not installed it you will get an alert. You can verify that you have installed it by
$ xcode-select -p
/Library/Developer/CommandLineTools
And to be sure then enter $ gcc --version
You can read more about the process here: Xcode command line tools for Mavericks
The "up" affordance indicator is provided by a drawable specified in the homeAsUpIndicator
attribute of the theme. To override it with your own custom version it would be something like this:
<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
<item name="android:homeAsUpIndicator">@drawable/my_fancy_up_indicator</item>
</style>
If you are supporting pre-3.0 with your application be sure you put this version of the custom theme in values-v11
or similar.
$objPHPExcel->getActiveSheet()->getStyle('1:1')->getFont()->setBold(true);
That way you get the complete first row
A MIME type is a label used to identify a type of data. It is used so software can know how to handle the data. It serves the same purpose on the Internet that file extensions do on Microsoft Windows.
So if a server says "This is text/html" the client can go "Ah, this is an HTML document, I can render that internally", while if the server says "This is application/pdf" the client can go "Ah, I need to launch the FoxIt PDF Reader plugin that the user has installed and that has registered itself as the application/pdf handler."
You'll most commonly find them in the headers of HTTP messages (to describe the content that an HTTP server is responding with or the formatting of the data that is being POSTed in a request) and in email headers (to describe the message format and attachments).
If you're using Bootstrap v3.0.1 or greater, you should use this solution instead. It doesn't override Bootstrap's styles with custom CSS, but instead uses a Bootstrap feature.
My original answer is shown below for posterity
This is a pleasantly easy fix. Because .img-responsive
from Bootstrap already sets display: block
, you can use margin: 0 auto
to center the image:
.product .img-responsive {
margin: 0 auto;
}
I created a little javascript tool to style elements on screen size without using media queries or recompiling bootstrap css:
https://github.com/Heras/Responsive-Breakpoints
Just add class responsive-breakpoints
to any element, and it will automagically add xs sm md lg xl
classes to those elements.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
OBSOLETE ANSWER - VERIFIED NOVEMBER 17, 2020
On Mac, I needed to go to Preferences > Accounts
, then add a new account as Bitbucket Server
and enter my company's bitbucket server URL. Then I had to choose HTTPS
as the protocol and enter my username (without @email) and password.
Also I set this new account as the default account by clicking the Set Default...
button in the bottom of the Preferences > Account
page.
Run server.js from a different command line and client.js from a different command line
A save method to determine the width and height unit of any element (no padding, no margin) is the following:
let div = document.querySelector("div");
let style = getComputedStyle(div);
let width = parseFloat(style.width.replace("px", ""));
let height = parseFloat(style.height.replace("px", ""));
Here is what I did, pure javascript and html. Did not test it but this should work in all browsers.
Javascript Function
var iframe = document.createElement('iframe');
iframe.id = "IFRAMEID";
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = 'SERVERURL'+'?' + $.param($scope.filtro);
iframe.addEventListener("load", function () {
console.log("FILE LOAD DONE.. Download should start now");
});
Using just components that is supported in all browsers no additional libraries.
Here is my server side JAVA Spring controller code.
@RequestMapping(value = "/rootto/my/xlsx", method = RequestMethod.GET)
public void downloadExcelFile(@RequestParam(value = "param1", required = false) String param1,
HttpServletRequest request, HttpServletResponse response)
throws ParseException {
Workbook wb = service.getWorkbook(param1);
if (wb != null) {
try {
String fileName = "myfile_" + sdf.format(new Date());
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + ".xlsx\"");
wb.write(response.getOutputStream());
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
A tad late, but here goes.
How about http://wiki.apache.org/tomcat/UsingPhp if you just want to run the real php on tomcat.
Concerning running tomcat on port 80 there's always jsvc, just google jsvc + tomcat.
os._exit()
:
exit(0)
:
exit(1)
:
sys.exit()
:
quit()
:
Basically they all do the same thing, however, it also depends on what you are doing it for.
I don't think you left anything out and I would recommend getting used to quit()
or exit()
.
You would use sys.exit()
and os._exit()
mainly if you are using big files or are using python to control terminal.
Otherwise mainly use exit()
or quit()
.
You can also try this:
scp -r /cygdrive/c/desktop/myfolder/deployments/ user@host:/path/to/whereyouwant/thefile
Selecting text in an element (akin to highlighting with your mouse)
:)
Using the accepted answer on that post, you can call the function like this:
$(function() {
$('#textareaId').click(function() {
SelectText('#textareaId');
});
});
If there are only two references to test and you are using Java 8, you could use
Object o = null;
Object p = "p";
Object r = Optional.ofNullable( o ).orElse( p );
System.out.println( r ); // p
If you import static Optional the expression is not too bad.
Unfortunately your case with "several variables" is not possible with an Optional-method. Instead you could use:
Object o = null;
Object p = null;
Object q = "p";
Optional<Object> r = Stream.of( o, p, q ).filter( Objects::nonNull ).findFirst();
System.out.println( r.orElse(null) ); // p
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
Apple recommends against relying on the fileExistAtPath: method. It's often better to just try to open a file and deal with the error if the file does not exist.
NSFileManager Class Reference
Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.
Source: Apple Developer API Reference
From the secure coding guide.
To prevent this, programs often check to make sure a temporary file with a specific name does not already exist in the target directory. If such a file exists, the application deletes it or chooses a new name for the temporary file to avoid conflict. If the file does not exist, the application opens the file for writing, because the system routine that opens a file for writing automatically creates a new file if none exists. An attacker, by continuously running a program that creates a new temporary file with the appropriate name, can (with a little persistence and some luck) create the file in the gap between when the application checked to make sure the temporary file didn’t exist and when it opens it for writing. The application then opens the attacker’s file and writes to it (remember, the system routine opens an existing file if there is one, and creates a new file only if there is no existing file). The attacker’s file might have different access permissions than the application’s temporary file, so the attacker can then read the contents. Alternatively, the attacker might have the file already open. The attacker could replace the file with a hard link or symbolic link to some other file (either one owned by the attacker or an existing system file). For example, the attacker could replace the file with a symbolic link to the system password file, so that after the attack, the system passwords have been corrupted to the point that no one, including the system administrator, can log in.
You have to differenciate between file size and disk usage. The main difference between the two comes from the fact that files are "cut into pieces" and stored in blocks.
Modern block size is 4KiB, so files will use disk space multiple of 4KiB, regardless of how small they are.
If you use the command stat
you can see both figures side by side.
stat file.c
If you want a more compact view for a directory, you can use ls -ls
, which will give you usage in 1KiB units.
ls -ls dir
Also du
will give you real disk usage, in 1KiB units, or dutree with the -u
flag.
Example: usage of a 1 byte file
$ echo "" > file.c
$ ls -l file.c
-rw-r--r-- 1 nacho nacho 1 Apr 30 20:42 file.c
$ ls -ls file.c
4 -rw-r--r-- 1 nacho nacho 1 Apr 30 20:42 file.c
$ du file.c
4 file.c
$ dutree file.c
[ file.c 1 B ]
$ dutree -u file.c
[ file.c 4.00 KiB ]
$ stat file.c
File: file.c
Size: 1 Blocks: 8 IO Block: 4096 regular file
Device: 2fh/47d Inode: 2185244 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/ nacho) Gid: ( 1000/ nacho)
Access: 2018-04-30 20:41:58.002124411 +0200
Modify: 2018-04-30 20:42:24.835458383 +0200
Change: 2018-04-30 20:42:24.835458383 +0200
Birth: -
In addition, in modern filesystems we can have snapshots, sparse files (files with holes in them) that further complicate the situation.
You can see more details in this article: understanding file size in Linux
You can simply cast to List and then check if every element can be casted to T.
public <T> List<T> asList(final Class<T> clazz) {
List<T> values = (List<T>) this.value;
values.forEach(clazz::cast);
return values;
}
What happens if you try android:gravity="center_horizontal"?
There is no direct way. You either export XML and then right an XSLT to format it properly (this is the hard way). An easier way is to write multiple reports with no explicit page breaks so each exports into one sheet only in excel and then write a script that would merge for you. Either way it requires a postprocessing step.
In Build: v22.6.2-1085508 ADT you need to add(select Android 4.4.2)
Goto project --> properties --> Android(This is second in listed item order leftPanel) and in the RightPanel Project Build Target, select Android 4.4.2 as Target name and apply changes It will rebuild the workspace.
In my case unable to resolve target 'android-17' eclipse was being shown as compile error and in code: import java.util.HashMap was not being referenced.
Private Function LoaderData(ByVal strSql As String) As DataTable
Dim cnn As SqlConnection
Dim dad As SqlDataAdapter
Dim dtb As New DataTable
cnn = New SqlConnection(My.Settings.mySqlConnectionString)
Try
cnn.Open()
dad = New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
cnn.Close()
dad.Dispose()
Catch ex As Exception
cnn.Close()
MsgBox(ex.Message)
End Try
Return dtb
End Function
Use the time package to work with time information in Go.
Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.
Play example:
package main
import (
"fmt"
"time"
)
func inTimeSpan(start, end, check time.Time) bool {
return check.After(start) && check.Before(end)
}
func main() {
start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")
in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")
if inTimeSpan(start, end, in) {
fmt.Println(in, "is between", start, "and", end, ".")
}
if !inTimeSpan(start, end, out) {
fmt.Println(out, "is not between", start, "and", end, ".")
}
}
document.getElementById('hello').classList.add('someClass');
The .add
method will only add the class if it doesn't already exist on the element. So no need to worry about duplicate class names.
Regarding your update (which probably should be another question). You should use an array of these objects instead an ArrayList, so you can simply check the value for null:
Object[] array = new Object[MAX_ENTRIES];
..
if ( array[ 8 ] == null ) {
// not available
}
else {
// do something
}
Best-Practice
If you don't have hundred of entries in your array you should consider organizing it as a class to get rid of the magic numbers 3,8 etc.
Control flow using exception is bad practice.
In the LLVM 3.0 compiler in Xcode 4.2 you can suppress the warning as follows:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self.ticketTarget performSelector: self.ticketAction withObject: self];
#pragma clang diagnostic pop
If you're getting the error in several places, and want to use the C macro system to hide the pragmas, you can define a macro to make it easier to suppress the warning:
#define SuppressPerformSelectorLeakWarning(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)
You can use the macro like this:
SuppressPerformSelectorLeakWarning(
[_target performSelector:_action withObject:self]
);
If you need the result of the performed message, you can do this:
id result;
SuppressPerformSelectorLeakWarning(
result = [_target performSelector:_action withObject:self]
);
Or with Prototype:
Event.observe(this, 'load', function() { new Ajax.Request(... ) );
Or better, define the function elsewhere rather than inline, then:
Event.observe(this, 'load', functionName );
You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();"
).
However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.
In windows 7, you may have to edit this file
C:\Users\<UserName>\AppData\Roaming\Subversion\servers
[global]
http-proxy-host = ip.add.re.ss
http-proxy-port = 3128
There is another alternative. Instead of manipulating the pseudo-classes directly, create real classes that model the same things, like a "hover" class or a "visited" class. Style the classes with the usual "." syntax and then you can use JavaScript to add or remove classes from an element when the appropriate event fires.
Right click on the project file -> Add -> New Item -> Application Configuration File. This will add an app.config
(or web.config
) file to your project.
The ConfigurationManager
class would be a good start. You can use it to read different configuration values from the configuration file.
I suggest you start reading the MSDN document about Configuration Files.
I don't know about JSON.NET, but it works fine with JavaScriptSerializer
from System.Web.Extensions.dll
(.NET 3.5 SP1):
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
public string OBJECT_NAME { get; set; }
public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
public int id { get; set; }
}
public class SubObject
{
public NameTypePair attributes { get; set; }
public Position position { get; set; }
}
public class Position
{
public int x { get; set; }
public int y { get; set; }
}
public class Foo
{
public Foo() { objects = new List<SubObject>(); }
public string displayFieldName { get; set; }
public NameTypePair fieldAliases { get; set; }
public PositionType positionType { get; set; }
public Ref reference { get; set; }
public List<SubObject> objects { get; set; }
}
static class Program
{
const string json = @"{
""displayFieldName"" : ""OBJECT_NAME"",
""fieldAliases"" : {
""OBJECT_NAME"" : ""OBJECT_NAME"",
""OBJECT_TYPE"" : ""OBJECT_TYPE""
},
""positionType"" : ""point"",
""reference"" : {
""id"" : 1111
},
""objects"" : [
{
""attributes"" : {
""OBJECT_NAME"" : ""test name"",
""OBJECT_TYPE"" : ""test type""
},
""position"" :
{
""x"" : 5,
""y"" : 7
}
}
]
}";
static void Main()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
Foo foo = ser.Deserialize<Foo>(json);
}
}
Edit:
Json.NET works using the same JSON and classes.
Foo foo = JsonConvert.DeserializeObject<Foo>(json);
The getItem
method in the WebStorage specification, explicitly returns null
if the item does not exist:
... If the given key does not exist in the list associated with the object then this method must return null. ...
So, you can:
if (localStorage.getItem("infiniteScrollEnabled") === null) {
//...
}
See this related question:
In my case I wasn't sure what had caused this to happen, but I knew I just wanted the submodules to be reset to their latest remote commit and be done with it. This involved combining answers from a couple of different questions on here:
git submodule update --recursive --remote --init
Sources:
Each process has its own 4GB of virtual memory which maps to the physical memory through page tables. The virtual memory is mostly split in two parts: 3 GB for the use of the process and 1 GB for the use of the Kernel. Most of the variables you create lie in the first part of the address space. That part is called user space. The last part is where the kernel resides and is common for all the processes. This is called Kernel space and most of this space is mapped to the starting locations of physical memory where the kernel image is loaded at boot time.
They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.
As for your replacement, you haven't specified what language you're using, so here's the sketch:
someString.replace("\r\n", "\n").replace("\r", "\n")
Even then however, getting a user's real IP address is going to be unreliable. All they need to do is use an anonymous proxy server (one that doesn't honor the headers for http_x_forwarded_for
, http_forwarded
, etc) and all you get is their proxy server's IP address.
You can then see if there is a list of proxy server IP addresses that are anonymous, but there is no way to be sure that is 100% accurate as well and the most it'd do is let you know it is a proxy server. And if someone is being clever, they can spoof headers for HTTP forwards.
Let's say I don't like the local college. I figure out what IP addresses they registered, and get their IP address banned on your site by doing bad things, because I figure out you honor the HTTP forwards. The list is endless.
Then there is, as you guessed, internal IP addresses such as the college network I metioned before. A lot use a 10.x.x.x format. So all you would know is that it was forwarded for a shared network.
Then I won't start much into it, but dynamic IP addresses are the way of broadband anymore. So. Even if you get a user IP address, expect it to change in 2 - 3 months, at the longest.
So much code here, but I think this is the best answer
function resize() {
var input = $("#picture");
var maxWidth = 300;
var maxHeight = 300;
var width = input.width();
var height = input.height();
var ratioX = (maxWidth / width);
var ratioY = (maxHeight / height);
var ratio = Math.min(ratioX, ratioY);
var newWidth = (width * ratio);
var newHeight = (height * ratio);
input.css("width", newWidth);
input.css("height", newHeight);
};
I have tried all the solutions and this one worked for me
let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options:
.ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImage.image = decodedimage
You can create files in browser using Blob
and URL.createObjectURL
. All recent browsers support this.
You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download
attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though.
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an example that uses this technique to save arbitrary text from a textarea
.
If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique.
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
For your case, you may use regex:
boolean checkFormat;
if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
checkFormat=true;
else
checkFormat=false;
For a larger scope or if you want a flexible solution, refer to MadProgrammer's answer.
Almost 5 years after posting this answer, I realize that this is a stupid way to validate a date format. But i'll just leave this here to tell people that using regex to validate a date is unacceptable
Also after React v 16.8+ you have an ability to use hooks
import React, {useState} from 'react';
const ControlledInputs = () => {
const [firstName, setFirstName] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
if (firstName) {
console.log('firstName :>> ', firstName);
}
};
return (
<>
<form onSubmit={handleSubmit}>
<label htmlFor="firstName">Name: </label>
<input
type="text"
id="firstName"
name="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
<button type="submit">add person</button>
</form>
</>
);
};
I don't have found any solution on Internet, so I have implemented one.
The Autofilter code with criteria is then
iColNumber = 1
Dim aFilterValueArray() As Variant
Call ConstructFilterValueArray(aFilterValueArray, iColNumber, Array("A", "B", "C"))
ActiveSheet.range(sRange).AutoFilter Field:=iColNumber _
, Criteria1:=aFilterValueArray _
, Operator:=xlFilterValues
In fact, the ConstructFilterValueArray() method (not function) get all distinct values that it found in a specific column and remove all values present in last argument.
The VBA code of this method is
'************************************************************
'* ConstructFilterValueArray()
'************************************************************
Sub ConstructFilterValueArray(a() As Variant, iCol As Integer, aRemoveArray As Variant)
Dim aValue As New Collection
Call GetDistinctColumnValue(aValue, iCol)
Call RemoveValueList(aValue, aRemoveArray)
Call CollectionToArray(a, aValue)
End Sub
'************************************************************
'* GetDistinctColumnValue()
'************************************************************
Sub GetDistinctColumnValue(ByRef aValue As Collection, iCol As Integer)
Dim sValue As String
iEmptyValueCount = 0
iLastRow = ActiveSheet.UsedRange.Rows.Count
Dim oSheet: Set oSheet = Sheets("X")
Sheets("Data")
.range(Cells(1, iCol), Cells(iLastRow, iCol)) _
.AdvancedFilter Action:=xlFilterCopy _
, CopyToRange:=oSheet.range("A1") _
, Unique:=True
iRow = 2
Do While True
sValue = Trim(oSheet.Cells(iRow, 1))
If sValue = "" Then
If iEmptyValueCount > 0 Then
Exit Do
End If
iEmptyValueCount = iEmptyValueCount + 1
End If
aValue.Add sValue
iRow = iRow + 1
Loop
End Sub
'************************************************************
'* RemoveValueList()
'************************************************************
Sub RemoveValueList(ByRef aValue As Collection, aRemoveArray As Variant)
For i = LBound(aRemoveArray) To UBound(aRemoveArray)
sValue = aRemoveArray(i)
iMax = aValue.Count
For j = iMax To 0 Step -1
If aValue(j) = sValue Then
aValue.Remove (j)
Exit For
End If
Next j
Next i
End Sub
'************************************************************
'* CollectionToArray()
'************************************************************
Sub CollectionToArray(a() As Variant, c As Collection)
iSize = c.Count - 1
ReDim a(iSize)
For i = 0 To iSize
a(i) = c.Item(i + 1)
Next
End Sub
This code can certainly be improved in returning an Array of String but working with Array in VBA is not easy.
CAUTION: this code work only if you define a sheet named X because CopyToRange parameter used in AdvancedFilter() need an Excel Range !
It's a shame that Microfsoft doesn't have implemented this solution in adding simply a new enum as xlNotFilterValues ! ... or xlRegexMatch !
you can use vbscript instead of batch(cmd.exe)
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
str1 = objArgs(0)
s=Split(str1," ")
For i=LBound(s) To UBound(s)
WScript.Echo s(i)
WScript.Echo s(9) ' get the 10th element
Next
usage:
c:\test> cscript /nologo test.vbs "AAA BBB CCC"
Have a look at
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array
for documentation on JavaScript Arrays.
jQuery is a library which adds some magic to JavaScript which is a capable and featurefull scripting language. The libraries just fill in the gaps - get to know the core!
just do this , you need to remove char other than "numeric" and "." form your string will do work for you
yourString = yourString.replace ( /[^\d.]/g, '' );
your final code will be
str1 = "test123.00".replace ( /[^\d.]/g, '' );
str2 = "yes50.00".replace ( /[^\d.]/g, '' );
total = parseInt(str1, 10) + parseInt(str2, 10);
alert(total);
use lines
for the second one:
plot(density(MyData$Column1))
lines(density(MyData$Column2))
make sure the limits of the first plot are suitable, though.
In 1985, individuals from companies throughout the computer industry joined together to develop the POSIX (Portable Operating System Interface for Computer Environments) standard, which is based largely on the UNIX System V Interface Definition (SVID) and other earlier standardization efforts. These efforts were spurred by the U.S. government, which needed a standard computing environment to minimize its training and procurement costs. Released in 1988, POSIX is a group of IEEE standards that define the API, shell, and utility interfaces for an operating system. Although aimed at UNIX-like systems, the standards can apply to any compatible operating system. Now that these stan- dards have gained acceptance, software developers are able to develop applications that run on all conforming versions of UNIX, Linux, and other operating systems.
From the book: A Practical Guide To Linux
See ?read.table
. Basically, when you use read.table
, you specify a number indicating the column:
##Row names in the first column
read.table(filname.txt, row.names=1)
Give each xhr request a unique id and store the object reference in an object before sending. Delete the reference after an xhr request completes.
To cancel all request any time:
$.ajaxQ.abortAll();
Returns the unique ids of canceled request. Only for testing purposes.
Working function:
$.ajaxQ = (function(){
var id = 0, Q = {};
$(document).ajaxSend(function(e, jqx){
jqx._id = ++id;
Q[jqx._id] = jqx;
});
$(document).ajaxComplete(function(e, jqx){
delete Q[jqx._id];
});
return {
abortAll: function(){
var r = [];
$.each(Q, function(i, jqx){
r.push(jqx._id);
jqx.abort();
});
return r;
}
};
})();
Returns an object with single function which can be used to add more functionality when required.
First use
git pull https://github.com/username/repository master
and then try
git push -u origin master
I've been in a situation like you (JPA/Hibernate sequence for non @Id field) and I ended up creating a trigger in my db schema that add a unique sequence number on insert. I just never got it to work with JPA/Hibernate
If the variable you are checking would be in the global scope you could do:
array_key_exists('v', $GLOBALS)
I recently dealt with this problem, and the cause of the problem turned out to be that the root certificate on the SMTP server that I was connecting to was the Sectigo root certificate that recently expired.
If you're connecting to the SMTP server by SSL/TLS or STARTTLS, and you've not changed anything recently in the environment where your PHPMailer script is running, and this problem suddenly occurred - then you might want to check for an expired or invalid certificate somewhere in the certificate chain on the server.
You can view the server's certificate chain using openssl s_client
.
For SSL/TLS on port 465:
openssl s_client -connect server.domain.tld:465 | openssl x509 -text
For STARTTLS on port 587:
openssl s_client -starttls smtp -crlf -connect server.domain.tld:587 | openssl x509 -text
This is more of a important comment and that why implicitly unwrapped optionals can be deceptive when it comes to debugging nil
values.
Think of the following code: It compiles with no errors/warnings:
c1.address.city = c3.address.city
Yet at runtime it gives the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you tell me which object is nil
?
You can't!
The full code would be:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c3 = BadContact()
c1.address.city = c3.address.city // compiler hides the truth from you and then you sudden get a crash
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct BadContact {
var address : Address!
}
struct Address {
var city : String
}
Long story short by using var address : Address!
you're hiding the possibility that a variable can be nil
from other readers. And when it crashes you're like "what the hell?! my address
isn't an optional, so why am I crashing?!.
Hence it's better to write as such:
c1.address.city = c2.address!.city // ERROR: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you now tell me which object it is that was nil
?
This time the code has been made more clear to you. You can rationalize and think that likely it's the address
parameter that was forcefully unwrapped.
The full code would be :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c2 = GoodContact()
c1.address.city = c2.address!.city
c1.address.city = c2.address?.city // not compile-able. No deceiving by the compiler
c1.address.city = c2.address.city // not compile-able. No deceiving by the compiler
if let city = c2.address?.city { // safest approach. But that's not what I'm talking about here.
c1.address.city = city
}
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct GoodContact {
var address : Address?
}
struct Address {
var city : String
}
how about some open/close safety.
string = File.open('file.txt', 'rb') { |file| file.read }
When using INTEGER
columns (that can be NULL
) in MySQL, PDO has some (to me) unexpected behaviour.
If you use $stmt->execute(Array)
, you have to specify the literal NULL
and cannot give NULL
by variable reference.
So this won't work:
// $val is sometimes null, but sometimes an integer
$stmt->execute(array(
':param' => $val
));
// will cause the error 'incorrect integer value' when $val == null
But this will work:
// $val again is sometimes null, but sometimes an integer
$stmt->execute(array(
':param' => isset($val) ? $val : null
));
// no errors, inserts NULL when $val == null, inserts the integer otherwise
Tried this on MySQL 5.5.15 with PHP 5.4.1
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
Delete node_module and re-install again by command
rm -rf node_modules && npm i
The simple fix to your example is :
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
tv.append("Hello World");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
Or we can use normal thread for example (with original Runner) :
Thread thread = new Thread() {
@Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(this);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.
More details are here http://developer.android.com/reference/android/os/Handler.html
Suggested changes:
CopyFromRecordset
;Revised code:
Sub GetDataFromADO()
'Declare variables'
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyRecordset As ADODB.Recordset
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;User ID=abc;Password=abc;"
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = "select * from mytable"
objMyCmd.CommandType = adCmdText
'Open Recordset'
Set objMyRecordset.Source = objMyCmd
objMyRecordset.Open
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset objMyRecordset
End Sub
int cannot be null. If you are not assigning any value to int default value will be 0. If you want to check for null then make int as Integer in declaration. Then Integer object can be null. So, you can check where it is null or not. Even in javax bean validation you won't be able to get error for @NotNull annotation until the variable is declared as Integer.
Think of it like this: the List
interface has methods like add(int index, E element)
, set(int index, E element)
. The contract is that once you added an element at position X you will find it there unless you add or remove elements before it.
If any list implementation would store elements in some order other than based on the index, the above list methods would make no sense.
In my case, after opening the file with a text editor as @john-machin suggested, I realized the file is not encrypted as an Excel file is supposed to but it's in the CSV format and was saved as an Excel file. What I did was renamed the file and its extension and used read_csv
function instead:
os.rename('sample_file.xls', 'sample_file.csv')
csv = pd.read_csv("sample_file.csv", error_bad_lines=False)
If the main method would not be static, you would need to create an object of your main class from outside the program. How would you want to do that?
If you're not set on rolling your own solution, check out this jQuery plugin:
malsup.com/jquery/form/
It will do that and more for you. It's highly recommended.
man you can use the basic Bootstrap Datepicker this way:
<!DOCTYPE html>
<head runat="server">
<title>Test Zone</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Css/datepicker.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../Js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pickyDate').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
and inside body:
<body>
<div id="testDIV">
<div class="container">
<div class="hero-unit">
<input type="text" placeholder="click to show datepicker" id="pickyDate"/>
</div>
</div>
</div>
datepicker.css and bootstrap-datepicker.js you can download from here on the Download button below "About" on the left side. Hope this help someone, greetings.
element(by.model('parent_id')).sendKeys('BKN01');
For GCC, this is accomplished in two stages:
First compile the data but tell the compiler to separate the code into separate sections within the translation unit. This will be done for functions, classes, and external variables by using the following two compiler flags:
-fdata-sections -ffunction-sections
Link the translation units together using the linker optimization flag (this causes the linker to discard unreferenced sections):
-Wl,--gc-sections
So if you had one file called test.cpp that had two functions declared in it, but one of them was unused, you could omit the unused one with the following command to gcc(g++):
gcc -Os -fdata-sections -ffunction-sections test.cpp -o test -Wl,--gc-sections
(Note that -Os is an additional compiler flag that tells GCC to optimize for size)
You do it:
console.log('hi')_x000D_
let start = 1_x000D_
setTimeout(function(){_x000D_
let interval = setInterval(function(){_x000D_
if(start == 10) clearInterval(interval)_x000D_
start++_x000D_
console.log('hello')_x000D_
}, 3000)_x000D_
}, 3000)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
In my case, the problem was the protocol. I was trying to call a script url with http
instead of https
.
Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />
javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
var k = e.which;
/* numeric inputs can come from the keypad or the numeric row at the top */
if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
e.preventDefault();
return false;
}
};?
Another possibility not mentioned yet is to just chuck the SELECT
statement itself into a CTE and then update the CTE.
;WITH CTE
AS (SELECT T1.Col1,
T2.Col1 AS _Col1,
T1.Col2,
T2.Col2 AS _Col2
FROM T1
JOIN T2
ON T1.id = T2.id
/*Where clause added to exclude rows that are the same in both tables
Handles NULL values correctly*/
WHERE EXISTS(SELECT T1.Col1,
T1.Col2
EXCEPT
SELECT T2.Col1,
T2.Col2))
UPDATE CTE
SET Col1 = _Col1,
Col2 = _Col2
This has the benefit that it is easy to run the SELECT
statement on its own first to sanity check the results, but it does requires you to alias the columns as above if they are named the same in source and target tables.
This also has the same limitation as the proprietary UPDATE ... FROM
syntax shown in four of the other answers. If the source table is on the many side of a one-to-many join then it is undeterministic which of the possible matching joined records will be used in the Update
(an issue that MERGE
avoids by raising an error if there is an attempt to update the same row more than once).
I found a solution that is similar to the one with psexec but works without additional tools and survives a reboot.
Just add a sheduled task, insert "system" in the "run as" field and point the task to a batch file with the simple command
net use z: \servername\sharedfolder /persistent:yes
Then select "run at system startup" (or similar, I do not have an English version) and you are done.
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
I had the same problem and discovered that Pygame
doesn't work for Python3 at least on the Mac OS, but I also have Tython2
installed in my computer as you probably do too, so when I use Pygame
, I switch the path so that it uses python2 instead of python3. I use Sublime Text as my text editor so I just go to
Tools
> Build Systems
> New Build System
and enter the following:
{
"cmd": ["/usr/local/bin/python", "-u", "$file"],
}
instead of
{
"cmd": ["/usr/local/bin/python3", "-u", "$file"],
}
in my case. And when I'm not using pygame
, I simply change the path back so that I can use Python3.
If you need to use [(ngModel)]
first, you need to import FormsModule
in app.module.ts
and then add in a list of imports. Something like this:
import {FormsModule} from "@angular/forms";
imports: [ BrowserModule, FormsModule ],
<input type="text" [(ngModel)]="name" >
<h1>your name is: {{name}} </h1>
Install sshpass, then launch the command:
sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname
Variables in single-quotes are not evaluated. Use double quotes:
ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"
The shell will expand variables in double-quotes, but not in single-quotes. This will change into your desired string before being passed to the ssh
command.
Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Restrictions.eq("city", "TEST")))
.setResultTransformer(Transformers.aliasToBean(User.class))
.list();
I've never used the alaistToBean, but I just read about it. You could also just loop over the results..
List<Object> rows = criteria.list();
for(Object r: rows){
Object[] row = (Object[]) r;
Type t = ((<Type>) row[0]);
}
If you have to you can manually populate User yourself that way.
Its sort of hard to look into the issue without some more information to diagnose the issue.
In the world of web development, the device pixel ratio (also called CSS Pixel Ratio) is what determines how a device's screen resolution is interpreted by the CSS.
A browser's CSS calculates a device's logical (or interpreted) resolution by the formula:
For example:
Apple iPhone 6s
When viewing a web page, the CSS will think the device has a 375x667 resolution screen and Media Queries will respond as if the screen is 375x667. But the rendered elements on the screen will be twice as sharp as an actual 375x667 screen because there are twice as many physical pixels in the physical screen.
Some other examples:
Samsung Galaxy S4
iPhone 5s
The reason that CSS pixel ratio was created is because as phones screens get higher resolutions, if every device still had a CSS pixel ratio of 1 then webpages would render too small to see.
A typical full screen desktop monitor is a roughly 24" at 1920x1080 resolution. Imagine if that monitor was shrunk down to about 5" but had the same resolution. Viewing things on the screen would be impossible because they would be so small. But manufactures are coming out with 1920x1080 resolution phone screens consistently now.
So the device pixel ratio was invented by phone makers so that they could continue to push the resolution, sharpness and quality of phone screens, without making elements on the screen too small to see or read.
Here is a tool that also tells you your current device's pixel density:
This will output the number of lines that contain your search string.
grep -c "echo" FILE
This won't, however, count the number of occurrences in the file (ie, if you have echo multiple times on one line).
edit:
After playing around a bit, you could get the number of occurrences using this dirty little bit of code:
sed 's/echo/echo\n/g' FILE | grep -c "echo"
This basically adds a newline following every instance of echo so they're each on their own line, allowing grep to count those lines. You can refine the regex if you only want the word "echo", as opposed to "echoing", for example.
Add -L/opt/lib
to your compiler parameters, this makes the compiler and linker search that path for libcalc.so
in that folder.
I have written this helper class to create instances of ObjectContext objects when they are defined in a different project than the project using it. I parse the connection string in the config file and replace '*' by the full assembly name.
It is not perfect because it uses reflection to build the object, but it is the most generic way of doing it that I could find.
Hope it helps someone.
public static class EntityHelper<T> where T : ObjectContext
{
public static T CreateInstance()
{
// get the connection string from config file
string connectionString = ConfigurationManager.ConnectionStrings[typeof(T).Name].ConnectionString;
// parse the connection string
var csBuilder = new EntityConnectionStringBuilder(connectionString);
// replace * by the full name of the containing assembly
csBuilder.Metadata = csBuilder.Metadata.Replace(
"res://*/",
string.Format("res://{0}/", typeof(T).Assembly.FullName));
// return the object
return Activator.CreateInstance(typeof(T), csBuilder.ToString()) as T;
}
}
First off, it is perfectly feasible to use R successfully for years and not need to know the answer to this question. R handles the differences between the (usual) numerics and integers for you in the background.
> is.numeric(1)
[1] TRUE
> is.integer(1)
[1] FALSE
> is.numeric(1L)
[1] TRUE
> is.integer(1L)
[1] TRUE
(Putting capital 'L' after an integer forces it to be stored as an integer.)
As you can see "integer" is a subset of "numeric".
> .Machine$integer.max
[1] 2147483647
> .Machine$double.xmax
[1] 1.797693e+308
Integers only go to a little more than 2 billion, while the other numerics can be much bigger. They can be bigger because they are stored as double precision floating point numbers. This means that the number is stored in two pieces: the exponent (like 308 above, except in base 2 rather than base 10), and the "significand" (like 1.797693 above).
Note that 'is.integer' is not a test of whether you have a whole number, but a test of how the data are stored.
One thing to watch out for is that the colon operator, :
, will return integers if the start and end points are whole numbers. For example, 1:5
creates an integer
vector of numbers from 1 to 5. You don't need to append the letter L
.
> class(1:5)
[1] "integer"
Reference: https://www.quora.com/What-is-the-difference-between-numeric-and-integer-in-R
On Selenium >= 3.41 (C#) the rigth syntax is:
webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));
7.2 of Dive Into Python: Finding the Path.
import sys, os
print('sys.argv[0] =', sys.argv[0])
pathname = os.path.dirname(sys.argv[0])
print('path =', pathname)
print('full path =', os.path.abspath(pathname))
In 32 bit virtual address system we can have 2^32 unique address, since the page size given is 4KB = 2^12, we will need (2^32/2^12 = 2^20) entries in the page table, if each entry is 4Bytes then total size of the page table = 4 * 2^20 Bytes = 4MB
You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:
In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file"
field, ostensibly for backward compatibility reasons.
So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.
The problem appears to be that the global symbol clear
is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah
), it works just fine:
Live: Version using clear
which fails | Version using blah
which works
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function blah() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.
A corollary to that is to not use old-style onxyz=...
attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 id="the-header">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
// Scoping function makes the declarations within
// it *not* globals
(function(){
var header = document.getElementById("the-header");
header.onmouseover = function() {
go('The dog is in its shed');
};
header.onmouseout = clear;
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
})();
</script>
</body>
</html>
...and even better, use DOM2's addEventListener
(or attachEvent
on IE8 and earlier) so you can have multiple handlers for an event on an element.
Using Https is fine, run git config --global credential.helper wincred
to create a Github credential helper that stores your credentials for you. If this doesn't work, then you need to edit your config
file in your .git
directory and update the origin to the https url.
See this link for the github docs.
The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., UTF-8).
Because you also ticked Scala, a solution without regex which easily deals with multiple quoted strings:
val text = "some string with 'the data i want' inside 'and even more data'"
text.split("'").zipWithIndex.filter(_._2 % 2 != 0).map(_._1)
res: Array[java.lang.String] = Array(the data i want, and even more data)
I'd faced a similar problem. I ended up with a working solution after a lot of googling and trial and test. Here is my solution which would work for you.
I have two controllers - searchBoxController and stateResultController and a parameter named searchQuery to be passed from a view having a search box to a view showing the results fetched from a remote server. This is how you do it:
Below is the controller from which you call the next view using $state.go()
.controller('searchBoxController', function ($scope, $state) {
$scope.doSearch = function(){
var searchInputRaw = $scope.searchQueryInput;
$state.go('app.searchResults', { searchQuery: searchInput });
}
})
Below is the state that would be called when the $state.go()
gets executed:
.state('app.searchResults',
{
url: '/searchResults',
views:
{
'menuContent': { templateUrl: 'templates/searchResult.html', controller: 'stateResultController' }
},
params:
{
'searchQuery': ''
}
})
And finally, the controller associated with the app.searchResults
state:
.controller('stateResultController', function ($scope, $state, $stateParams, $http) {
$scope.searchQueryInput = $stateParams.searchQuery;
});
As other guys commented before you can write your own procedure with anonymous function to solve this issue.
I used two ways to solve it:
func Find(slice interface{}, f func(value interface{}) bool) int {
s := reflect.ValueOf(slice)
if s.Kind() == reflect.Slice {
for index := 0; index < s.Len(); index++ {
if f(s.Index(index).Interface()) {
return index
}
}
}
return -1
}
Uses example:
type UserInfo struct {
UserId int
}
func main() {
var (
destinationList []UserInfo
userId int = 123
)
destinationList = append(destinationList, UserInfo {
UserId : 23,
})
destinationList = append(destinationList, UserInfo {
UserId : 12,
})
idx := Find(destinationList, func(value interface{}) bool {
return value.(UserInfo).UserId == userId
})
if idx < 0 {
fmt.Println("not found")
} else {
fmt.Println(idx)
}
}
Second method with less computational cost:
func Search(length int, f func(index int) bool) int {
for index := 0; index < length; index++ {
if f(index) {
return index
}
}
return -1
}
Uses example:
type UserInfo struct {
UserId int
}
func main() {
var (
destinationList []UserInfo
userId int = 123
)
destinationList = append(destinationList, UserInfo {
UserId : 23,
})
destinationList = append(destinationList, UserInfo {
UserId : 123,
})
idx := Search(len(destinationList), func(index int) bool {
return destinationList[index].UserId == userId
})
if idx < 0 {
fmt.Println("not found")
} else {
fmt.Println(idx)
}
}
DECLARE @vchVAlue NVARCHAR(255) = 'SWP, Lettering Position 1: 4 ?, 2: 8 ?, 3: 16 ?, 4: , 5: , 6: , Voltage Selector, Solder, 6, Step switch, : w/o fuseholder '
WHILE PATINDEX('%?%' , CAST(@vchVAlue AS VARCHAR(255))) > 0
BEGIN
SELECT @vchVAlue = STUFF(@vchVAlue,PATINDEX('%?%' , CAST(@vchVAlue AS VARCHAR(255))),1,' ')
END
SELECT @vchVAlue
Mine was a TLS
version incompatible error.
Previously it was TLSv1
I changed it TLSV1.2
this solved my problem.
<body>
<div style=" display: table; margin: 250 auto;">
In center
</div>
</body>
If you want to change the vertical position, change the value of 250 and you can arrange the content as per your need. There is no need to give the width and other parameters.
You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.
You just need to re-open the image with IrfanView after changing the view color to white.
To change the viewing color in Irfanview go to:
Options > Properties/Settings > Viewing > Main window color
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
When you are inside an activity and need to go to a fragment use below
getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();
But when you are inside a fragment and need to go to a fragment then just add a getActivity().
before, so it would become
getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();
as simple as that.
The *TO_BE_REPLACED_LAYOUT_ID*
can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout
.
I forget where I first saw it mentioned but you can actually embed your labels in a container elsewhere as long as you have the for=
attribute set. So, let's check out a sample on SO:
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
background-color: #262626;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
.radio-button {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
#filter {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.filter-label {_x000D_
display: inline-block;_x000D_
border: 4px solid green;_x000D_
padding: 10px 20px;_x000D_
font-size: 1.4em;_x000D_
text-align: center;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
main {_x000D_
clear: left;_x000D_
}_x000D_
_x000D_
.content {_x000D_
padding: 3% 10%;_x000D_
display: none;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
font-size: 2em;_x000D_
}_x000D_
_x000D_
.date {_x000D_
padding: 5px 30px;_x000D_
font-style: italic;_x000D_
}_x000D_
_x000D_
.filter-label:hover {_x000D_
background-color: #505050;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~#filter .featured,_x000D_
#personal-radio:checked~#filter .personal,_x000D_
#tech-radio:checked~#filter .tech {_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~main .featured {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#personal-radio:checked~main .personal {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#tech-radio:checked~main .tech {_x000D_
display: block;_x000D_
}
_x000D_
<input type="radio" id="featured-radio" class="radio-button" name="content-filter" checked="checked">_x000D_
<input type="radio" id="personal-radio" class="radio-button" name="content-filter" value="Personal">_x000D_
<input type="radio" id="tech-radio" class="radio-button" name="content-filter" value="Tech">_x000D_
_x000D_
<header id="filter">_x000D_
<label for="featured-radio" class="filter-label featured" id="feature-label">Featured</label>_x000D_
<label for="personal-radio" class="filter-label personal" id="personal-label">Personal</label>_x000D_
<label for="tech-radio" class="filter-label tech" id="tech-label">Tech</label>_x000D_
</header>_x000D_
_x000D_
<main>_x000D_
<article class="content featured tech">_x000D_
<header>_x000D_
<h1>Cool Stuff</h1>_x000D_
<h3 class="date">Today</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
I'm showing cool stuff in this article!_x000D_
</p>_x000D_
</article>_x000D_
_x000D_
<article class="content personal">_x000D_
<header>_x000D_
<h1>Not As Cool</h1>_x000D_
<h3 class="date">Tuesday</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
This stuff isn't nearly as cool for some reason :(;_x000D_
</p>_x000D_
</article>_x000D_
_x000D_
<article class="content tech">_x000D_
<header>_x000D_
<h1>Cool Tech Article</h1>_x000D_
<h3 class="date">Last Monday</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
This article has awesome stuff all over it!_x000D_
</p>_x000D_
</article>_x000D_
_x000D_
<article class="content featured personal">_x000D_
<header>_x000D_
<h1>Cool Personal Article</h1>_x000D_
<h3 class="date">Two Fridays Ago</h3>_x000D_
</header>_x000D_
_x000D_
<p>_x000D_
This article talks about how I got a job at a cool startup because I rock!_x000D_
</p>_x000D_
</article>_x000D_
</main>
_x000D_
Whew. That was a lot for a "sample" but I feel it really drives home the effect and point: we can certainly select a label for a checked input control without it being a sibling. The secret lies in keeping the input
tags a child to only what they need to be (in this case - only the body
element).
Since the label
element doesn't actually utilize the :checked
pseudo selector, it doesn't matter that the labels are stored in the header
. It does have the added benefit that since the header
is a sibling element we can use the ~
generic sibling selector to move from the input[type=radio]:checked
DOM element to the header
container and then use descendant/child selectors to access the label
s themselves, allowing the ability to style them when their respective radio boxes/checkboxes are selected.
Not only can we style the labels, but also style other content that may be descendants of a sibling container relative to all of the input
s. And now for the moment you've all been waiting for, the JSFIDDLE! Go there, play with it, make it work for you, find out why it works, break it, do what you do!
Hopefully that all makes sense and fully answers the question and possibly any follow ups that may crop up.
If you want to use If, else if, and else then use this method
{this.state.value === 0 ? (
<Component1 />
) : this.state.value === 1 ? (
<Component2 />
) : (
<Component3 />
)}
cond? statementA: statementB
Equals to:
if (cond)
statementA
else
statementB
For your case, you may just delete all "if". If you totally use if-else instead of ?:. Don't mix them together.
Just need:
string stringName = EnumDisplayStatus.Visible.ToString("f");
// stringName == "Visible"
On Mac OS X Mojave
python
stands for python of version 2.7 and python3
for python of version 3. The same is pip
and pip3
. So, to upgrade pip
for python 3
do this:
~$ sudo pip3 install --upgrade pip
you should remove last comma and as nrodic said your command is not correct.
you should change it like this :
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);
Though The above answers are right, I found something more user-friendly approach while using ternary operator.
{{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
If someone need to work through foreach then,
{% for attachment in attachments %}
{{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
{% endfor %}
You can avoid the loop and cut etc by using:
awk -F ':' '{system("ping " $1);}' config.txt
However it would be better if you post a snippet of your config.txt
In my case it was concurrent access to one Hibernate Session from several threads. I had the Spring Boot Batch and RepositoryItemReader implementation where I fetched entities by page request with size 10.
For example my entities are:
@Entity
class JobEntity {
@ManyToOne(fetch = FetchType.LAZY)
private GroupEntity group;
}
@Entity
class GroupEntity {
@OneToMany(mappedBy = "group", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private Set<Config> configs;
}
Batch process: reader -> processor -> writer
in one transaction.
In that entities configuration, GroupEntity can escapes to other threads:
First thread that entered to read section fetches the page of JobEntity with size 10 (RepositoryItemReader#doRead), this items contain one shared GroupEntity object (because all of them pointed to the same group id). Then it takes the first entity. Next threads that come to read section take JobEntity from this page one by one, until this page will be exhausted.
So now threads have access to the same GroupEntity instance thought the JobEntity instances, that is unsafe multi thread access to the one Hibernate Session.
Array can only be used for specific types, whereas lists can be used for any object.
Arrays can also only data of one type, whereas a list can have entries of various object types.
Arrays are also more efficient for some numerical computation.
I had the same problem after changing the domain of my site. Altough I properly changed the request_uri parameter and updated my app settings with the new domain, the error kept showing up. Then I realized that the ID and the SECRET ID of my Facebook APP had automatically changed with no warning!! The whole thing started working again using the new ID.
As simple as this
x = "some data you want to return"
return x, 200, {'Content-Type': 'text/css; charset=utf-8'}
Hope it helps
Update: Use this method because it will work with both python 2.x and python 3.x
and secondly it also eliminates multiple header problem.
from flask import Response
r = Response(response="TEST OK", status=200, mimetype="application/xml")
r.headers["Content-Type"] = "text/xml; charset=utf-8"
return r
I'm using ▐ ▌
HTML: ▐ ▌
CSS: \2590\A0\258C
When you say the 'GUI Tool', I assume you're using Git For Windows.
IMPORTANT, I would highly recommend creating a new branch to do this on if you haven't already. That way your master can remain the same while you test out your changes.
With the GUI you need to 'roll back this commit' like you have with the history on the right of your view. Then you will notice you have all the unwanted files as changes to commit on the left. Now you need to right click on the grey title above all the uncommited files and select 'disregard changes'. This will set your files back to how they were in this version.
You can try max-height: 70px; See if that works.
It depends on the JUnit version and what assert libraries you use.
The original answer for JUnit <= 4.12
was:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.
Reference :
I had this problem when I was trying to run commands through CLI.
It was a problem with system looking at the JRE folder i.e.
D:\Program Files\Java\jre8\bin
. If we look in there, there is no Tools.jar
, hence the error.
You need to find where the JDK
is, in my case: D:\Program Files\Java\jdk1.8.0_11
, and if you look in the lib
directory, you will see Tools.jar
.
What I did I created a new environment variable JAVA_HOME
:
And then you need to edit your PATH variable to include JAVA_HOME, i.e. %JAVA_HOME%/bin;
Re-open command prompt and should run.
In Java, char is technically a "16-bit integer", so you can simply cast it to int and you'll get it's code. From Oracle:
The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
So you can simply cast it to int.
char registered = '®';
System.out.println(String.format("This is an int-code: %d", (int) registered));
System.out.println(String.format("And this is an hexa code: %x", (int) registered));
double quotes worked in oracle when I had the keyword as one of the column name.
eg:
select t."size" from table t
If you're using Python 3, or appropriate Python 2.x version with from __future__ import print_function
then:
data = [7, 7, 7, 7]
print(*data, sep='')
Otherwise, you'll need to convert to string and print:
print ''.join(map(str, data))
When running Nginx in a Docker container, be aware that a volume mounted over the log dir defeats the purpose of creating a softlink between the log files and stdout/stderr in your Dockerfile, as described in @Boeboe 's answer.
In that case you can either create the softlink in your entrypoint (executed after volumes are mounted) or not use a volume at all (e.g. when logs are already collected by a central logging system).
Here's the trick:
First, set your Vi(m) session to allow pattern matching with special characters (i.e.: newline). It's probably worth putting this line in your .vimrc or .exrc file:
:set magic
Next, do:
:s/,/,^M/g
To get the ^M
character, type Ctrl + V and hit Enter. Under Windows, do Ctrl + Q, Enter. The only way I can remember these is by remembering how little sense they make:
A: What would be the worst control-character to use to represent a newline?
B: Either
q
(because it usually means "Quit") orv
because it would be so easy to type Ctrl + C by mistake and kill the editor.A: Make it so.
just use following code
c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Then it will give you
you can check shape and dimension of matrix by using following code
c.shape
c.ndim
Default values cannot be supplied for parameters that are not declared 'optional
'
Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)
In your WebApiConfig
config.Routes.MapHttpRoute( _
name:="books", _
routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
)
Created the Data frame:
import pandas as pd
dk=pd.DataFrame({"BrandName":['A','B','ABC','D','AB'],"Specialty":['H','I','J','K','L']})
Now use DataFrame.replace()
function:
dk.BrandName.replace(to_replace=['ABC','AB'],value='A')
Typescript version:
export class Utility {
public static convertModelToFormData(model: any, form: FormData = null, namespace = ''): FormData {
let formData = form || new FormData();
let formKey;
for (let propertyName in model) {
if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
let formKey = namespace ? `${namespace}[${propertyName}]` : propertyName;
if (model[propertyName] instanceof Date)
formData.append(formKey, model[propertyName].toISOString());
else if (model[propertyName] instanceof Array) {
model[propertyName].forEach((element, index) => {
const tempFormKey = `${formKey}[${index}]`;
this.convertModelToFormData(element, formData, tempFormKey);
});
}
else if (typeof model[propertyName] === 'object' && !(model[propertyName] instanceof File))
this.convertModelToFormData(model[propertyName], formData, formKey);
else
formData.append(formKey, model[propertyName].toString());
}
return formData;
}
}
Using:
let formData = Utility.convertModelToFormData(model);
in your tsconfig you have to add: "esModuleInterop": true - it should help.
float
in SQL Server actually has [edit:almost] the precision of a "double" (in a C# sense).
float
is a synonym for float(53)
. 53 is the bits of the mantissa.
.NET double
uses 54 bits for the mantissa.
To use the hex
encoding in Python 3, use
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
In legacy Python, there are several other ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'
As far as I'm aware in order to format a date value you have to handle it in parameterMap,
$('#listDiv').kendoGrid({
dataSource: {
type: 'json',
serverPaging: true,
pageSize: 10,
transport: {
read: {
url: '@Url.Action("_ListMy", "Placement")',
data: refreshGridParams,
type: 'POST'
},
parameterMap: function (options, operation) {
if (operation != "read") {
var d = new Date(options.StartDate);
options.StartDate = kendo.toString(new Date(d), "dd/MM/yyyy");
return options;
}
else { return options; }
}
},
schema: {
model: {
id: 'Id',
fields: {
Id: { type: 'number' },
StartDate: { type: 'date', format: 'dd/MM/yyyy' },
Area: { type: 'string' },
Length: { type: 'string' },
Display: { type: 'string' },
Status: { type: 'string' },
Edit: { type: 'string' }
}
},
data: "Data",
total: "Count"
}
},
scrollable: false,
columns:
[
{
field: 'StartDate',
title: 'Start Date',
format: '{0:dd/MM/yyyy}',
width: 100
},
If you follow the above example and just renames objects like 'StartDate' then it should work (ignore 'data: refreshGridParams,')
For further details check out below link or just search for kendo grid parameterMap ans see what others have done.
http://docs.kendoui.com/api/framework/datasource#configuration-transport.parameterMap
I would suggest using NVM to keep different versions of node and npm and then install the compatible angular-cli
Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class
myObj:any = {
doSomething: function () { console.log('doing something'); return 'doing something'; },
};
myArray:any;
constructor() { }
ngOnInit() {
this.myArray = [this.myObj];
}
You can use it in template html file as following:
<div>test-1: {{ myObj?.doSomething()}}</div>
<div>test-2: {{ myArray[0].doSomething()}}</div>
<div>test-3: {{ myArray[2]?.doSomething()}}</div>
If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.
val uri = myUriString.toUri()
To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
It's the other way around: =
and ==
are for string comparisons, -eq
is for numeric ones. -eq
is in the same family as -lt
, -le
, -gt
, -ge
, and -ne
, if that helps you remember which is which.
==
is a bash-ism, by the way. It's better to use the POSIX =
. In bash the two are equivalent, and in plain sh =
is the only one guaranteed to work.
$ a=foo
$ [ "$a" = foo ]; echo "$?" # POSIX sh
0
$ [ "$a" == foo ]; echo "$?" # bash specific
0
$ [ "$a" -eq foo ]; echo "$?" # wrong
-bash: [: foo: integer expression expected
2
(Side note: Quote those variable expansions! Do not leave out the double quotes above.)
If you're writing a #!/bin/bash
script then I recommend using [[
instead. The doubled form has more features, more natural syntax, and fewer gotchas that will trip you up. Double quotes are no longer required around $a
, for one:
$ [[ $a == foo ]]; echo "$?" # bash specific
0
See also:
You can use the following function:
function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {_x000D_
const roundedNumber = number.toFixed(decimals);_x000D_
let integerPart = '',_x000D_
fractionalPart = '';_x000D_
if (decimals == 0) {_x000D_
integerPart = roundedNumber;_x000D_
decimalSeparator = '';_x000D_
} else {_x000D_
let numberParts = roundedNumber.split('.');_x000D_
integerPart = numberParts[0];_x000D_
fractionalPart = numberParts[1];_x000D_
}_x000D_
integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);_x000D_
return `${integerPart}${decimalSeparator}${fractionalPart}`;_x000D_
}_x000D_
_x000D_
// Use Example_x000D_
_x000D_
let min = 1556454.0001;_x000D_
let max = 15556982.9999;_x000D_
_x000D_
console.time('number format');_x000D_
for (let i = 0; i < 15; i++) {_x000D_
let randomNumber = Math.random() * (max - min) + min;_x000D_
let formated = format(randomNumber, 4, ',', '.'); // formated number_x000D_
_x000D_
console.log('number: ', randomNumber, '; formated: ', formated);_x000D_
}_x000D_
console.timeEnd('number format');
_x000D_
This isn't really briefer but might be a more flexible way (credit):
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
This is an old question, but here's the approach I use ...
function getCookie(name) {
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
return match ? match[1] : null;
}
This returns null
either when the cookie doesn't exist, or when it doesn't contain the requested name.
Otherwise, the value (of the requested name) is returned.
A cookie should never exist without a value -- because, in all fairness, what's the point of that?
If it's no longer needed, it's best to just get rid of it all together.
function deleteCookie(name) {
document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
I just had the same problem and all I did was delete the user log in credentials in sql server using another user id and adding them back.
SQL injection: when user has the chance to input something that could be part of the sql statement
For example:
String query = “INSERT INTO students VALUES(‘” + user + “‘)”
when user input “Robert’); DROP TABLE students; –” as the input, it causes SQL injection
How prepared statement prevents this?
String query = “INSERT INTO students VALUES(‘” + “:name” + “‘)”
parameters.addValue(“name”, user);
=> when user input again “Robert’); DROP TABLE students; –“, the input string is precompiled on the driver as literal values and I guess it may be casted like:
CAST(‘Robert’); DROP TABLE students; –‘ AS varchar(30))
So at the end, the string will be literally inserted as the name to the table.
http://blog.linguiming.com/index.php/2018/01/10/why-prepared-statement-avoids-sql-injection/
Check out Math.Round. You can then cast the result to an int
.
According to PHPMailer Manual, full answer would be :
$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');
Use Case :
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';
If you want to display an image with a remote URL :
$mail->addStringAttachment(file_get_contents("url"), "filename");
From psql command line:
\COPY my_table TO 'filename' CSV HEADER
no semi-colon at the end.
This is the same method I have been using for a couple of years now and I haven't seen or found anything better. As people have said, PHP is single threaded, so there isn't much else you can do.
I have actually added one extra level to this and that's getting and storing the process id. This allows me to redirect to another page and have the user sit on that page, using AJAX to check if the process is complete (process id no longer exists). This is useful for cases where the length of the script would cause the browser to timeout, but the user needs to wait for that script to complete before the next step. (In my case it was processing large ZIP files with CSV like files that add up to 30 000 records to the database after which the user needs to confirm some information.)
I have also used a similar process for report generation. I'm not sure I'd use "background processing" for something such as an email, unless there is a real problem with a slow SMTP. Instead I might use a table as a queue and then have a process that runs every minute to send the emails within the queue. You would need to be warry of sending emails twice or other similar problems. I would consider a similar queueing process for other tasks as well.
You could use a Common Table Expression to create the SUM first, join it to the table, and then use the WHEN to to get the value from the CTE or the original table as necessary.
WITH PercentageOfTotal (Id, Percentage)
AS
(
SELECT Id, (cnt / SUM(AreaId)) FROM dbo.MyTable GROUP BY Id
)
SELECT
CASE
WHEN o.TotalType = 'Average' THEN r.avgscore
WHEN o.TotalType = 'PercentOfTot' THEN pt.Percentage
ELSE o.cnt
END AS [displayscore]
FROM PercentageOfTotal pt
JOIN dbo.MyTable t ON pt.Id = t.Id
Assuming that you have your data in a 2d array, this should work:
import numpy
import pylab
xy = numpy.zeros((2, 1000))
xy[0] = range(1000)
xy[1] = range(1000)
colors = [int(i % 23) for i in xy[0]]
pylab.scatter(xy[0], xy[1], c=colors)
pylab.show()
You can also set a cmap
attribute to control which colors will appear through use of a colormap; i.e. replace the pylab.scatter
line with:
pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool)
A list of color maps can be found here
Try this:
"0x" + BitConverter.ToString(arraytoinsert).Replace("-", "")
Although you should really be using a parameterised query rather than string concatenation of course...
Here is the one command to install python3 on Amazon linux ec2 instance:
Python 3.7.6
To completely remove the ul
default style:
list-style-type: none;
margin: 0;
margin-block-start: 0;
margin-block-end: 0;
margin-inline-start: 0;
margin-inline-end: 0;
padding-inline-start: 0;
This is a simple solution to that question. The vertical scroll will be activated only when the text overflows.
<TextBox Text="Try typing some text here " ScrollViewer.VerticalScrollBarVisibility="Auto" TextWrapping="WrapWithOverflow" />
1)event.stopPropagation():
=>It is used to stop executions of its corresponding parent handler only.
2) event.stopImmediatePropagation():
=> It is used to stop the execution of its corresponding parent handler and also handler or function attached to itself except the current handler.
=> It also stops all the handler attached to the current element of entire DOM.
Here is the example: Jsfiddle!
Thanks, -Sahil
It would probably be better if you added:
export PATH=/usr/local/git/bin:/usr/local/sbin:$PATH
to a file named .bashrc in your home folder. This way any other software that you might install in /usr/local/git/bin
will also be found first.
For an easy way to do this just type:
echo "export PATH=/usr/local/git/bin:/usr/local/sbin:$PATH" >> ~/.bashrc
into the Terminal and it will do it for you.
Try this:
DECLARE @COMBINED_STRINGS AS VARCHAR(50); -- Allocate just enough length for the two strings.
SET @COMBINED_STRINGS = 'rupesh''s' + 'malviya';
SELECT @COMBINED_STRINGS; -- Print your combined strings.
Or you can put your strings into variables. Such that:
DECLARE @COMBINED_STRINGS AS VARCHAR(50),
@STRING1 AS VARCHAR(20),
@STRING2 AS VARCHAR(20);
SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SELECT @COMBINED_STRINGS;
Output:
rupesh'smalviya
Just add a space in your string as a separator.
Rather than changing ${user}
in eclipse, it is advisable to introduce
-Duser.name=Whateverpleaseyou
in eclipse.ini
which is present in your eclipse folder.
The jQuery way to click a link is
$('#LinkID').click();
For mailTo link, you have to write the following code
$('#LinkID')[0].click();
When divided by zero
If you divide double by 0, JVM will show Infinity.
public static void main(String [] args){ double a=10.00; System.out.println(a/0); }
Console:
Infinity
If you divide int by 0, then JVM will throw Arithmetic Exception.
public static void main(String [] args){
int a=10;
System.out.println(a/0);
}
Console: Exception in thread "main" java.lang.ArithmeticException: / by zero
Filezilla is available for Linux. If you are using Ubuntu:
sudo apt-get install filezilla
Otherwise, you can download it from the Filezilla website.
One way to do that is to make all your users' devices subscribe to a topic. That way when you target a message to a specific topic, all devices will get it. I think this how the Notifications section in the Firebase console does it.
You can't (usefully) compare strings using !=
or ==
, you need to use strcmp
:
while (strcmp(check,input) != 0)
The reason for this is because !=
and ==
will only compare the base addresses of those strings. Not the contents of the strings themselves.
I had the same issue and I fixed removing the library that were unnecessary
compile fileTree(dir: 'libs', include: ['*.jar'])
I removed that library and I could run the project without any problem.
Try this, it also handles the single quote which is failed to parse by JSON.parse() method and also supports the UTF-8 character code.
parseJSON = function() {
var data = {};
var reader = new FileReader();
reader.onload = function() {
try {
data = JSON.parse(reader.result.replace(/'/g, "\""));
} catch (ex) {
console.log('error' + ex);
}
};
reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}
Assuming GroupDetails as in orid's answer have you tried JPA 2.1 @ConstructorResult?
@SqlResultSetMapping(
name="groupDetailsMapping",
classes={
@ConstructorResult(
targetClass=GroupDetails.class,
columns={
@ColumnResult(name="GROUP_ID"),
@ColumnResult(name="USER_ID")
}
)
}
)
@NamedNativeQuery(name="getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")
and use following in repository interface:
GroupDetails getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId);
According to Spring Data JPA documentation, spring will first try to find named query matching your method name - so by using @NamedNativeQuery
, @SqlResultSetMapping
and @ConstructorResult
you should be able to achieve that behaviour
I've been using following codes since ES5.
Promise.wait = function(promiseQueue){
if( !Array.isArray(promiseQueue) ){
return Promise.reject('Given parameter is not an array!');
}
if( promiseQueue.length === 0 ){
return Promise.resolve([]);
}
return new Promise((resolve, reject) =>{
let _pQueue=[], _rQueue=[], _readyCount=false;
promiseQueue.forEach((_promise, idx) =>{
// Create a status info object
_rQueue.push({rejected:false, seq:idx, result:null});
_pQueue.push(Promise.resolve(_promise));
});
_pQueue.forEach((_promise, idx)=>{
let item = _rQueue[idx];
_promise.then(
(result)=>{
item.resolved = true;
item.result = result;
},
(error)=>{
item.resolved = false;
item.result = error;
}
).then(()=>{
_readyCount++;
if ( _rQueue.length === _readyCount ) {
let result = true;
_rQueue.forEach((item)=>{result=result&&item.resolved;});
(result?resolve:reject)(_rQueue);
}
});
});
});
};
The usage signature is just like Promise.all
. The major difference is that Promise.wait
will wait for all the promises to finish their jobs.
I've created a little Powershell function to emulate MSDOS pause
. This handles whether running Powershell ISE or non ISE. (ReadKey
does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox
. This can sometimes be confusing, because the MessageBox
does not always come to the forefront. Anyway, here it goes:
Usage:
pause "Press any key to continue"
Function definition:
Function pause ($message)
{
# Check if running Powershell ISE
if ($psISE)
{
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("$message")
}
else
{
Write-Host "$message" -ForegroundColor Yellow
$x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
}
Here's the script, rewritten to use the suggestions above and a change to your no-cache method.
<?php
// Simpler way of making sure all no-cache headers get sent
// and understood by all browsers, including IE.
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
// set to return response=error
$arr = array ('response'=>'error','comment'=>'test comment here');
echo json_encode($arr);
?>
//the script above returns this:
{"response":"error","comment":"test comment here"}
<script type="text/javascript">
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
dataType: "json",
success: function (data) {
if (data.response == 'captcha') {
alert('captcha');
} else if (data.response == 'success') {
alert('success');
} else {
alert('sorry there was an error');
}
}
}); // Semi-colons after all declarations, IE is picky on these things.
</script>
The main issue here was that you had a typo in the JSON you were returning ("resonse" instead of "response". This meant that you were looking for the wrong property in the JavaScript code. One way of catching these problems in the future is to console.log
the value of data
and make sure the property you are looking for is there.
Learning how to use the Chrome debugger tools (or similar tools in Firefox/Safari/Opera/etc.) will also be invaluable.
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003
Young generation garbage collection algorithms
The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.
The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.
The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).
From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't.
Just for completeness and because it was asked in the comments - there's also the CSS audit tool in Chrome now for the same purpose. Some details here:
http://meeech.amihod.com/very-useful-find-unused-css-rules-with-google
You can solve this problem by placing XML in the same directory in which your main python file (from where you tried to include this file) was placed. Now the next step is to use full path. For example
This will not work
front_cascade = cv2.CascadeClassifier('./haarcascade_eye.xml')
Use full path, now it will work fine
front_cascade = cv2.CascadeClassifier('/Users/xyz/Documents/project/haarcascade_eye.xml')
I needed to do the same thing as you and landed on your question. I ended up taking finding about the steps function which I read about from here.
JSFiddle of my solution in action (Note it currently works in Firefox, I'll let you add the crossbrowser lines, trying to keep the solution clean of clutter)
First I created a sprite sheet that had two frames. Then I created the div and put that as the background, but my div is only the size of my sprite (100px).
<div id="cyclist"></div>
#cyclist {
animation: cyclist 1s infinite steps(2);
display: block;
width: 100px;
height: 100px;
background-image: url('../images/cyclist-test.png');
background-repeat: no-repeat;
background-position: top left;
}
The animation is set to have 2 steps and have the whole process take 1 second.
@keyframes cyclist {
0% {
background-position: 0 0;
}
100% {
background-position: 0 -202px; //this should be cleaned up, my sprite sheet is 202px by accident, it should be 200px
}
}
Thiago above mentioned the steps function but I thought I'd elaborate more on it. Pretty simple and awesome stuff.
A simple solution I frequently use:
arr = ['remove me',3,4,2,45]
arr[1..-1]
=> [3,4,2,45]
git checkout --[ours/theirs] .
will do what you want, as long as you're at the root of all conflicts. ours/theirs only affects unmerged files so you shouldn't have to grep/find/etc conflicts specifically.
Yes, It's deprecated. Spent yesterday rewriting code to use Window.open and PostMessage instead.
It depends on where the files reside. For instance, if they are all supposed to be in the same directory, you can read all the directory entries into a hash table and then check all the names against the hash table. This might be faster on some systems than checking each file individually. The fastest way to check each file individually depends on your system ... if you're writing ANSI C, the fastest way is fopen
because it's the only way (a file might exist but not be openable, but you probably really want openable if you need to "do something on it"). C++, POSIX, Windows all offer additional options.
While I'm at it, let me point out some problems with your question. You say that you want the fastest way, and that you have thousands of files, but then you ask for the code for a function to test a single file (and that function is only valid in C++, not C). This contradicts your requirements by making an assumption about the solution ... a case of the XY problem. You also say "in standard c++11(or)c++(or)c" ... which are all different, and this also is inconsistent with your requirement for speed ... the fastest solution would involve tailoring the code to the target system. The inconsistency in the question is highlighted by the fact that you accepted an answer that gives solutions that are system-dependent and are not standard C or C++.