I would advise you to use pylibmc
instead.
It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.
And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.
Matching any text but those matching a pattern is usually achieved with splitting the string with the regex pattern.
Examples:
Regex.Split(text, @"red|green|blue")
or, to get rid of empty values, Regex.Split(text, @"red|green|blue").Where(x => !string.IsNullOrEmpty(x))
(see demo)Regex.Split(text, "red|green|blue")
or, to remove empty items, Regex.Split(text, "red|green|blue").Where(Function(s) Not String.IsNullOrWhitespace(s))
(see demo, or this demo where LINQ is supported)text.split(/red|green|blue/)
(no need to use g
modifier here!) (to get rid of empty values, use text.split(/red|green|blue/).filter(Boolean)
), see demotext.split("red|green|blue")
, or - to keep all trailing empty items - use text.split("red|green|blue", -1)
, or to remove all empty items use more code to remove them (see demo)text.split(/red|green|blue/)
, to get all trailing items use text.split(/red|green|blue/, -1)
and to remove all empty items use text.split(/red|green|blue/).findAll {it != ""})
(see demo)text.split(Regex("red|green|blue"))
or, to remove blank items, use text.split(Regex("red|green|blue")).filter{ !it.isBlank() }
, see demotext.split("red|green|blue")
, or to keep all trailing empty items, use text.split("red|green|blue", -1)
and to remove all empty items, use text.split("red|green|blue").filter(_.nonEmpty)
(see demo)text.split(/red|green|blue/)
, to get rid of empty values use .split(/red|green|blue/).reject(&:empty?)
(and to get both leading and trailing empty items, use -1
as the second argument, .split(/red|green|blue/, -1)
) (see demo)my @result1 = split /red|green|blue/, $text;
, or with all trailing empty items, my @result2 = split /red|green|blue/, $text, -1;
, or without any empty items, my @result3 = grep { /\S/ } split /red|green|blue/, $text;
(see demo)preg_split('~red|green|blue~', $text)
or preg_split('~red|green|blue~', $text, -1, PREG_SPLIT_NO_EMPTY)
to output no empty items (see demo)re.split(r'red|green|blue', text)
or, to remove empty items, list(filter(None, re.split(r'red|green|blue', text)))
(see demo)regexp.MustCompile("red|green|blue").Split(text, -1)
, and if you need to remove empty items, use this code. See Go demo.NOTE: If you patterns contain capturing groups, regex split functions/methods may behave differently, also depending on additional options. Please refer to the appropriate split method documentation then.
Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.
Each tab can be converted to a sequence non-breaking spaces which require no wrapping.
" "
This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.
You don't import methods in Java, only types:
import Dan.Vik;
class Kab
{
public static void main(String args[])
{
Vik Sam = new Vik();
Sam.disp();
}
}
The exception is so-called "static imports", which let you import class (static
) methods from other types.
I tried the standard library's calendar.timegm and it works quite well:
# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
return int(calendar.timegm(aDateTime.timetuple())*1000)
Ref: https://docs.python.org/2/library/calendar.html#calendar.timegm
If you are using XAMPP on Mac, this worked for me:
Moving the CSV/TXT file to /Applications/XAMPP/xamppfiles/htdocs/ as following
LOAD DATA LOCAL INFILE '/Applications/XAMPP/xamppfiles/htdocs/file.csv' INTO TABLE `tablename` FIELDS TERMINATED BY ',' LINES TERMINATED BY ';'
The code below will create an outlook message & keep the auto signature
Dim OApp As Object, OMail As Object, signature As String
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
With OMail
.Display
End With
signature = OMail.body
With OMail
'.To = "[email protected]"
'.Subject = "Type your email subject here"
'.Attachments.Add
.body = "Add body text here" & vbNewLine & signature
'.Send
End With
Set OMail = Nothing
Set OApp = Nothing
We're using OpenCV. It has lots of non-face-recognition stuff in there also, but, rest assured, it does do face-recognition.
Swift 5
To make it easy, create a file "DispatchQueue+Extensions.swift" with this content :
import Foundation
typealias Dispatch = DispatchQueue
extension Dispatch {
static func background(_ task: @escaping () -> ()) {
Dispatch.global(qos: .background).async {
task()
}
}
static func main(_ task: @escaping () -> ()) {
Dispatch.main.async {
task()
}
}
}
Usage :
Dispatch.background {
// do stuff
Dispatch.main {
// update UI
}
}
Thanks to many of the answers above and elsewhere, this was my solution to a similar problem to the OP. The problem for me was creating a button in Word that asks the user for a network address, and pulls up the LAN resources in an Explorer window.
Untouched, the code would take you to \\10.1.1.1\Test,
so edit as you see fit. I'm just a monkey on a keyboard, here, so all comments and suggestions are welcome.
Private Sub CommandButton1_Click()
Dim ipAddress As Variant
On Error GoTo ErrorHandler
ipAddress = InputBox("Please enter the IP address of the network resource:", "Explore a network resource", "\\10.1.1.1")
If ipAddress <> "" Then
ThisDocument.FollowHyperlink ipAddress & "\Test"
End If
ExitPoint:
Exit Sub
ErrorHandler:
If Err.Number = "4120" Then
GoTo ExitPoint
ElseIf Err.Number = "4198" Then
MsgBox "Destination unavailable"
GoTo ExitPoint
End If
MsgBox "Error " & Err.Number & vbCrLf & Err.Description
Resume ExitPoint
End Sub
This is how I solved clickable and Visible links in a TextView (by code)
private void setAsLink(TextView view, String url){
Pattern pattern = Pattern.compile(url);
Linkify.addLinks(view, pattern, "http://");
view.setText(Html.fromHtml("<a href='http://"+url+"'>http://"+url+"</a>"));
}
Check the complete
and naturalWidth
properties, in that order.
https://stereochro.me/ideas/detecting-broken-images-js
function IsImageOk(img) {
// During the onload event, IE correctly identifies any images that
// weren’t downloaded as not complete. Others should too. Gecko-based
// browsers act like NS4 in that they report this incorrectly.
if (!img.complete) {
return false;
}
// However, they do have two very useful properties: naturalWidth and
// naturalHeight. These give the true size of the image. If it failed
// to load, either of these should be zero.
if (img.naturalWidth === 0) {
return false;
}
// No other way of checking: assume it’s ok.
return true;
}
I might do something like the following. Of course, with the wealth of Collection classes, i can't imagine ever needing to use this in any practical code.
public class Shift {
public static <T> T[] left (final T... i) {
if (1 >= i.length) {
return i;
}
final T t = i[0];
int x = 0;
for (; x < i.length - 1; x++) {
i[x] = i[x + 1];
}
i[x] = t;
return i;
}
}
Called with two arguments, it's a swap.
It can be used as follows:
int x = 1;
int y = 2;
Integer[] yx = Shift.left(x,y);
Alternatively:
Integer[] yx = {x,y};
Shift.left(yx);
Then
x = yx[0];
y = yx[1];
Note: it auto-boxes primitives.
Source : Send email in ASP.NET C#
Below is a sample working code for sending in a mail using C#, in the below example I am using google’s smtp server.
The code is pretty self explanatory, replace email and password with your email and password values.
public void SendEmail(string address, string subject, string message)
{
string email = "[email protected]";
string password = "put-your-GMAIL-password-here";
var loginInfo = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.
This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html
(It also includes the drag/drop interface but that's easily ignored.)
Basically what it comes down to is this:
<input id="files" type="file" />
<script>
document.getElementById('files').addEventListener('change', function(e) {
var file = this.files[0];
var xhr = new XMLHttpRequest();
(xhr.upload || xhr).addEventListener('progress', function(e) {
var done = e.position || e.loaded
var total = e.totalSize || e.total;
console.log('xhr progress: ' + Math.round(done/total*100) + '%');
});
xhr.addEventListener('load', function(e) {
console.log('xhr upload complete', e, this.responseText);
});
xhr.open('post', '/URL-HERE', true);
xhr.send(file);
});
</script>
(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)
So basically what it comes down to is this =)
xhr.send(file);
Where file
is typeof Blob
: http://www.w3.org/TR/FileAPI/
Another (better IMO) way is to use FormData
. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.
var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);
FormData
makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).
All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.
This is how I handled the request (1 image per request) in PHP:
if ( isset($_FILES['file']) ) {
$filename = basename($_FILES['file']['name']);
$error = true;
// Only upload if on my home win dev machine
if ( isset($_SERVER['WINDIR']) ) {
$path = 'uploads/'.$filename;
$error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
}
$rsp = array(
'error' => $error, // Used in JS
'filename' => $filename,
'filepath' => '/tests/uploads/' . $filename, // Web accessible
);
echo json_encode($rsp);
exit;
}
I believe you are looking for:
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
void foo(vector<int> test)
vector would be passed by value in this.
You have more ways to pass vectors depending on the context:-
1) Pass by reference:- This will let function foo change your contents of the vector. More efficient than pass by value as copying of vector is avoided.
2) Pass by const-reference:- This is efficient as well as reliable when you don't want function to change the contents of the vector.
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// Assume x, y, and diameter are instance variables.
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2d.fill(circle);
...
}
Here are some docs about paintComponent (link).
You should override that method in your JPanel and do something similar to the code snippet above.
In your ActionListener you should specify x, y, diameter
and call repaint()
.
Msg 8155, Level 16, State 2, Line 1 No column was specified for column 1 of 'd'. Msg 8155, Level 16, State 2, Line 1 No column was specified for column 2 of 'd'. ANSWER:
ROUND(AVG(CAST(column_name AS FLOAT)), 2) as column_name
If you are storing values via any programming language
Here is an example in C#
To store date you have to convert it first and then store it
insert table1 (foodate)
values (FooDate.ToString("MM/dd/yyyy"));
FooDate is datetime variable which contains your date in your format.
If you're only getting these to manually pass into df.set_index()
, that's unnecessary. Just directly do df.set_index['your_col_name', drop=False]
, already.
It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.
CSS "classes" are not OOP "classes". The inheritance works the other way around.
A DOM element can have many classes, either directly or inherited or otherwise associated, which will all be applied in order, overriding earlier defined properties:
<div class="foo bar">
.foo {
color: blue;
width: 200px;
}
.bar {
color: red;
}
The div will be 200px wide and have the color red.
You override properties of DOM elements with different classes, not properties of CSS classes. CSS "classes" are rulesets, the same way ids or tags can be used as rulesets.
Note that the order in which the classes are applied depends on the precedence and specificity of the selector, which is a complex enough topic in itself.
The JSON.stringify
method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/
This method is also included with json2.js, for supporting older browsers.
If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.
You can also open a required file through a prompt, This helps when you want to select file from different path and different file.
Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant
NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")
If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub
I noticed the same thing about BOTHER not being defined. Like Jamey Sharp said, you can find it in <asm/termios.h>
. Just a forewarning, I think I ran into problems including both it and the regular <termios.h>
file at the same time.
Aside from that, I found with the glibc I have, it still didn't work because glibc's tcsetattr was doing the ioctl for the old-style version of struct termios which doesn't pay attention to the speed setting. I was able to set a custom speed by manually doing an ioctl with the new style termios2 struct, which should also be available by including <asm/termios.h>
:
struct termios2 tio;
ioctl(fd, TCGETS2, &tio);
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = 12345;
tio.c_ospeed = 12345;
ioctl(fd, TCSETS2, &tio);
hey I understand this is an old thread but I have a query in regards to apachebenchmarking. how do you collect the metrics from apache benchmarking. P.S: I have to do it via telegraf and put it to influxdb . any suggestions/advice/help would be appreciated. Thanks a ton.
Your SVN passwords in Ubuntu (12.04) are in:
~/.subversion/auth/svn.simple/
However in newer versions they are encrypted, as earlier someone mentioned. To find gnome-keyring passwords, I suggest You to use 'gkeyring' program.
To install it on Ubuntu – add repository :
sudo add-apt-repository ppa:kampka/ppa
sudo apt-get update
Install it:
sudo apt-get install gkeyring
And run as following:
gkeyring --id 15 --output=name,secret
Try different key ids to find pair matching what you are looking for. Thanks to kampka for the soft.
Answer for a limited, specific situation: assuming you want to delete the files while maintainig the subfolders tree, you could use a recursive algorithm:
import os
def recursively_remove_files(f):
if os.path.isfile(f):
os.unlink(f)
elif os.path.isdir(f):
for fi in os.listdir(f):
recursively_remove_files(os.path.join(f, fi))
recursively_remove_files(my_directory)
Maybe slightly off-topic, but I think many would find it useful
It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.
You can use following code to insert an image through script.
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Above example has been copied from this link. Check noogui's reply for details.
In case you need to insert image from Google Drive, please check this link for current updates.
You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.
declare @TableVar table
(
firstCol varchar(50) NOT NULL,
secondCol varchar(50) NOT NULL
)
BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO
INSERT INTO dbo.ExistingTable
(
firstCol,
secondCol
)
SELECT firstCol,
secondCol
FROM @TableVar
GO
.... where yourdate_column > DATE_SUB(now(), INTERVAL 6 MONTH)
As detailed in this answer, mayur & user3869623's answer's are now relating to a deprecated router. You can now pass multiple parameters as follows:
To call router:
this.router.navigate(['/myUrlPath', "someId", "another ID"]);
In routes.ts:
{ path: 'myUrlpath/:id1/:id2', component: componentToGoTo},
This is a bit late in the day for suggesting this, given how long ago the original question was posted, but this is what I did.
I needed a range of 70 years, which, while not as much as 100, is still too many years for the visitor to scroll through. (jQuery does step through year in groups, but that's a pain in the patootie for most people.)
The first step was to modify the JavaScript for the datepicker widget: Find this code in jquery-ui.js or jquery-ui-min.js (where it will be minimized):
for (a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+
a.id+"', this, 'Y');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');\">";b<=g;b++)
a.yearshtml+='<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
a.yearshtml+="</select>";
And replace it with this:
a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+
".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');
\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');
\">";
for(opg=-1;b<=g;b++) {
a.yearshtml+=((b%10)==0 || opg==-1 ?
(opg==1 ? (opg=0, '</optgroup>') : '')+
(b<(g-10) ? (opg=1, '<optgroup label="'+b+' >">') : '') : '')+
'<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
}
a.yearshtml+="</select>";
This surrounds the decades (except for the current) with OPTGROUP tags.
Next, add this to your CSS file:
.ui-datepicker OPTGROUP { font-weight:normal; }
.ui-datepicker OPTGROUP OPTION { display:none; text-align:right; }
.ui-datepicker OPTGROUP:hover OPTION { display:block; }
This hides the decades until the visitor mouses over the base year. Your visitor can scroll through any number of years quickly.
Feel free to use this; just please give proper attribution in your code.
You could just re-direct specific numbers in your contacts to your voice-mail. That's already supported.
Otherwise I guess the documentation for 'Contacts' would be a good place to start looking.
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
<%= f.select :email_provider, ["gmail","yahoo","msn"]%>
You can get the DOM element and set disabled attribute to true/false.
If you use vue framework,here is a very easy demo.
let vm = new Vue({
el: "#app",
data() {
return { flag: true }
},
computed: {
btnText() {
return this.flag ? "Enable" : "Disable";
}
}
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="text" value="something" :disabled="flag" />
<input type="button" :value="btnText" @click="flag=!flag">
</div>
_x000D_
Unfortunately there is no built-in function to cast an unsigned integer to a two's complement signed value, but we can define a function to do so using bitwise operations:
def s12(value):
return -(value & 0b100000000000) | (value & 0b011111111111)
The first bitwise-and operation is used to sign-extend negative numbers (most significant bit is set), while the second is used to grab the remaining 11 bits. This works since integers in Python are treated as arbitrary precision two's complement values.
You can then combine this with the int
function to convert a string of binary digits into the unsigned integer form, then interpret it as a 12-bit signed value.
>>> s12(int('111111111111', 2))
-1
>>> s12(int('011111111111', 2))
2047
>>> s12(int('100000000000', 2))
-2048
One nice property of this function is that it's idempotent, thus the value of an already signed value will not change.
>>> s12(-1)
-1
Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.
Try something like this:
start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"
This doesn't work in IE8 but might be an option to consider. It is primarily useful if you do not want to specify a width.
.element
{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Guava also has Base64 (among other encodings and incredibly useful stuff)
TempData is also a dictionary object that stays for the time of an HTTP Request. So, TempData can be used to maintain data between one controller action to the other controller action.
TempData is used to check the null values each time. TempData contain two method keep() and peek() for maintain data state from one controller action to others.
When TempDataDictionary object is read, At the end of request marks as deletion to current read object.
The keep() and peek() method is used to read the data without deletion the current read object.
You can use Peek() when you always want to hold/prevent the value for another request. You can use Keep() when prevent/hold the value depends on additional logic.
Overloading in TempData.Peek() & TempData.Keep() as given below.
TempData.Keep() have 2 overloaded methods.
void keep() : That menace all the data not deleted on current request completion.
void keep(string key) : persist the specific item in TempData with help of name.
TempData.Peek() no overloaded methods.
Example for return type of TempData.Keep() & TempData.Peek() methods as given below.
public void Keep(string key) { _retainedKeys.Add(key); }
public object Peek(string key) { object value = values; return value; }
With Tomcat 7, you can add the StuckThreadDetectionValve which will enable you to identify threads that are "stuck". You can set-up the valve in the Context element of the applications where you want to do detecting:
<Context ...>
...
<Valve
className="org.apache.catalina.valves.StuckThreadDetectionValve"
threshold="60" />
...
</Context>
This would write a WARN entry into the tomcat log for any thread that takes longer than 60 seconds, which would enable you to identify the applications and ban them because they are faulty.
Based on the source code you may be able to write your own valve that attempts to stop the thread, however this would have knock on effects on the thread pool and there is no reliable way of stopping a thread in Java without the cooperation of that thread...
There are multiple versions of the echo
command, with different behaviors. Apparently the shell used for your script uses a version that doesn't recognize -n
.
The printf
command has much more consistent behavior. echo
is fine for simple things like echo hello
, but I suggest using printf
for anything more complicated.
What system are you on, and what shell does your script use?
Simply set includeantruntime="false"
:
<javac includeantruntime="false" ...>...</javac>
If you have to use the javac
-task multiple times you might want to consider using PreSetDef
to define your own javac
-task that always sets includeantruntime="false"
.
From http://www.coderanch.com/t/503097/tools/warning-includeantruntime-was-not-set:
That's caused by a misfeature introduced in Ant 1.8. Just add an attribute of that name to the javac task, set it to false, and forget it ever happened.
From http://ant.apache.org/manual/Tasks/javac.html:
Whether to include the Ant run-time libraries in the classpath; defaults to yes, unless build.sysclasspath is set. It is usually best to set this to false so the script's behavior is not sensitive to the environment in which it is run.
I tried the steps above (by paniniluncher) but received the following message:
Google Play services out of date. Requires 3025100 but found 2012110
I received this message because I required different versions of the files noted above. To resolve the issue I first uninstalled the files referenced above, downloaded the versions that I needed (as referenced in the following StackOverflow posting:
Google Play services out of date. Requires 3025100 but found 2012110
and then installed these files using the `adb -e install [path-to-APK-file] and then restarted the emulator and it worked perfectly!
One can use a plain ImageView in his xml and make it clickable (android:clickable="true")? You only have to use as src an image that has been shaped like a button i.e round corners.
Are you looking for something like this?
COLUMN_NAMES=['A','B','C','D','E','F','G']
df = pd.DataFrame(columns=COLUMN_NAMES)
df.columns
Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')
1) Add the following line to /etc/security/limits.conf
webuser hard nofile 64000
then login as webuser
su - webuser
2) Edit following two files for webuser
append .bashrc and .bash_profile file by running
echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile
3) Log out, then log back in and verify that the changes have been made correctly:
$ ulimit -a | grep open
open files (-n) 64000
Thats it and them boom, boom boom.
Just use the length filter on the whole array. It works on more than just strings:
{{ notcount|length }}
My solution: remove some init options (ex. show), because constructor doesnt yield if something is not working (ex slide effect). My function without dynamic html insertion:
function ySearch(){ console.log('ysearch');
$( "#aaa" ).dialog({autoOpen: true,closeOnEscape: true, dialogClass: "ysearch-dialog",modal: false,height: 510, width:860
});
$('#aaa').dialog("open");
console.log($('#aaa').dialog("isOpen"));
return false;
}
The closest thing in C# 3.0, is that you can use a constructor to initialize properties:
Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}
The regex validation for india should make sure that +91 is used, then make sure that 7, 8,9 is used after +91 and finally followed by 9 digits.
/^+91(7\d|8\d|9\d)\d{9}$/
Get the more information from below link
w3schools.com/jsref/jsref_obj_regexp.asp
Can be used as a shorthand in equality check.
So this code
if(ob != null && this.getClass() == ob.getClass) {
}
can be written as
if(ob instanceOf ClassA) {
}
If this is the current url use window.location.pathname otherwise use this regular expression:
var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];
First set in the following path Tools->Options->Text Editor->All Languages->Tabs if still didn't work modify as mentioned below Go to Edit->Advanced->Set Indentation ->Spaces
There is a bot that echoes your chat id upon starting a conversation.
Just search for @chatid_echo_bot
and tap /start
. It will echo your chat id.
Another option is @getidsbot
which gives you much more information. This bot also gives information about a forwarded message (from user, to user, chad ids, etc) if you forward the message to the bot.
Here is a reliable solution that works with both 32bit and 64bit applications.
Add these references:
using System.Diagnostics;
using System.Management;
Add this method to your project:
public static string GetProcessPath(int processId)
{
string MethodResult = "";
try
{
string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query))
{
using (ManagementObjectCollection moc = mos.Get())
{
string ExecutablePath = (from mo in moc.Cast<ManagementObject>() select mo["ExecutablePath"]).First().ToString();
MethodResult = ExecutablePath;
}
}
}
catch //(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
Now use it like so:
int RootProcessId = Process.GetCurrentProcess().Id;
GetProcessPath(RootProcessId);
Notice that if you know the id of the process, then this method will return the corresponding ExecutePath.
Extra, for those interested:
Process.GetProcesses()
...will give you an array of all the currently running processes, and...
Process.GetCurrentProcess()
...will give you the current process, along with their information e.g. Id, etc. and also limited control e.g. Kill, etc.*
The &
means that the function accepts the address (or reference) to a variable, instead of the value of the variable.
For example, note the difference between this:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
format: 'YYYY-MM-DD HH:mm:ss',
Why not just:
import seaborn as sns
sns.barplot(list(D.keys()), list(D.values()))
Rename the branch using this command:
git branch -m [old_branch_name] [new_branch_name]
-m
: It renames/moves the branch. If there is already a branch, you will get an error.
If there is already a branch and you want to rename with that branch, use:
git rename -M [old_branch_name] [new_branch_name]
For more information about help, use this command in the terminal:
git branch --help
or
man git branch
Since you mentioned $.each()
, here's a handy approach that would work in jQuery 1.6+:
var foo = { key1: 'bar', key2: 'baz' };
// keys will be: ['key1', 'key2']
var keys = $.map(foo, function(item, key) {
return key;
});
I would be inclined to include the year in the output. One way:
select to_char(DATE_CREATED, 'YYYY-MM'), sum(Num_of_Pictures)
from pictures_table
group by to_char(DATE_CREATED, 'YYYY-MM')
order by 1
Another way (more standard SQL):
select extract(year from date_created) as yr, extract(month from date_created) as mon,
sum(Num_of_Pictures)
from pictures_table
group by extract(year from date_created), extract(month from date_created)
order by yr, mon;
Remember the order by, since you presumably want these in order, and there is no guarantee about the order that rows are returned in after a group by.
To copy conditional formatting from google spreadsheet (doc1) to another (doc2) you need to do the following:
When Laravel tries to connect to database, if the connection fails or if it finds any errors it will return a PDOException
error. We can catch this error and redirect the action
Add the following code in the app/filtes.php
file.
App::error(function(PDOException $exception)
{
Log::error("Error connecting to database: ".$exception->getMessage());
return "Error connecting to database";
});
Hope this is helpful.
View;
$.ajax({
type: 'GET',
cache: false,
url: '/Login/Method',
dataType: 'json',
data: { },
error: function () {
},
success: function (result) {
alert("success")
}
});
Controller Method;
public JsonResult Method()
{
return Json(new JsonResult()
{
Data = "Result"
}, JsonRequestBehavior.AllowGet);
}
Mockito has limitations testing final, static, and private methods.
with jMockit testing library, you can do few stuff very easy and straight-forward as below:
Mock constructor of a java.io.File class:
new MockUp<File>(){
@Mock
public void $init(String pathname){
System.out.println(pathname);
// or do whatever you want
}
};
Mock a static method:
**
**
Below is the ansible play i used to remove the file when the file exists in the OS end.
- name: find out /etc/init.d/splunk file exists or not'
stat:
path: /etc/init.d/splunk
register: splunkresult
tags:
- always
- name: 'Remove splunk from init.d file if splunk already running'
file:
path: /etc/init.d/splunk
state: absent
when: splunkresult.stat.exists == true
ignore_errors: yes
tags:
- always
I have used play condition as like below
when: splunkresult.stat.exists == true --> Remove the file
you can give true/false based on your requirement
when: splunkresult.stat.exists == false
when: splunkresult.stat.exists == true
PHP runs on the server-side thus you have to use a client-side technology which is capable of showing popup windows: JavaScript.
So you should output a specific JS block via PHP if your form contains errors and you want to show that popup.
The lodash 4.6.1 docs have this as an example for object key equality:
_.uniqWith(objects, _.isEqual);
If you are running a custom named service, you should see two executables in your Tomcat/bin directory
In my case with Tomcat 8
08/14/2019 10:24 PM 116,648 Tomcat-Custom.exe
08/14/2019 10:24 PM 119,720 Tomcat-Customw.exe
2 File(s) 236,368 bytes
Running the "w" terminated executable will let you configure Xmx in the Java
tab
This is for using a single directory for multiple projects. I use this technique for some closely related projects where I often need to pull changes from one project into another. It's similar to the orphaned branches idea but the branches don't need to be orphaned. Simply start all the projects from the same empty directory state.
Don't expect wonders from this solution. As I see it, you are always going to have annoyances with untracked files. Git doesn't really have a clue what to do with them and so if there are intermediate files generated by a compiler and ignored by your .gitignore file, it is likely that they will be left hanging some of the time if you try rapidly swapping between - for example - your software project and a PH.D thesis project.
However here is the plan. Start as you ought to start any git projects, by committing the empty repository, and then start all your projects from the same empty directory state. That way you are certain that the two lots of files are fairly independent. Also, give your branches a proper name and don't lazily just use "master". Your projects need to be separate so give them appropriate names.
Git commits (and hence tags and branches) basically store the state of a directory and its subdirectories and Git has no idea whether these are parts of the same or different projects so really there is no problem for git storing different projects in the same repository. The problem is then for you clearing up the untracked files from one project when using another, or separating the projects later.
cd some_empty_directory
git init
touch .gitignore
git add .gitignore
git commit -m empty
git tag EMPTY
Start your projects from empty.
git branch software EMPTY
git checkout software
echo "array board[8,8] of piece" > chess.prog
git add chess.prog
git commit -m "chess program"
whenever you like.
git branch thesis EMPTY
git checkout thesis
echo "the meaning of meaning" > philosophy_doctorate.txt
git add philosophy_doctorate.txt
git commit -m "Ph.D"
Go back and forwards between projects whenever you like. This example goes back to the chess software project.
git checkout software
echo "while not end_of_game do make_move()" >> chess.prog
git add chess.prog
git commit -m "improved chess program"
You will however be annoyed by untracked files when swapping between projects/branches.
touch untracked_software_file.prog
git checkout thesis
ls
philosophy_doctorate.txt untracked_software_file.prog
Sort of by definition, git doesn't really know what to do with untracked files and it's up to you to deal with them. You can stop untracked files from being carried around from one branch to another as follows.
git checkout EMPTY
ls
untracked_software_file.prog
rm -r *
(directory is now really empty, apart from the repository stuff!)
git checkout thesis
ls
philosophy_doctorate.txt
By ensuring that the directory was empty before checking out our new project we made sure there were no hanging untracked files from another project.
$ GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01T01:01:01' git commit -m empty
If the same dates are specified whenever committing an empty repository, then independently created empty repository commits can have the same SHA1 code. This allows two repositories to be created independently and then merged together into a single tree with a common root in one repository later.
# Create thesis repository.
# Merge existing chess repository branch into it
mkdir single_repo_for_thesis_and_chess
cd single_repo_for_thesis_and_chess
git init
touch .gitignore
git add .gitignore
GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01:T01:01:01' git commit -m empty
git tag EMPTY
echo "the meaning of meaning" > thesis.txt
git add thesis.txt
git commit -m "Wrote my PH.D"
git branch -m master thesis
# It's as simple as this ...
git remote add chess ../chessrepository/.git
git fetch chess chess:chess
It may also help if you keep your projects in subdirectories where possible, e.g. instead of having files
chess.prog
philosophy_doctorate.txt
have
chess/chess.prog
thesis/philosophy_doctorate.txt
In this case your untracked software file will be chess/untracked_software_file.prog
. When working in the thesis
directory you should not be disturbed by untracked chess program files, and you may find occasions when you can work happily without deleting untracked files from other projects.
Also, if you want to remove untracked files from other projects, it will be quicker (and less prone to error) to dump an unwanted directory than to remove unwanted files by selecting each of them.
So you might want to name your branches something like
project1/master
project1/featureABC
project2/master
project2/featureXYZ
Short answer: minimum possible access (cf Jon Skeet's answer).
Long answer:
Non-nested types, enumeration and delegate accessibilities (may only have internal or public accessibility)
| Default | Permitted declared accessibilities ------------------------------------------------------------------ namespace | public | none (always implicitly public) enum | public | public, internal interface | internal | public, internal class | internal | public, internal struct | internal | public, internal delegate | internal | public, internal
Nested type and member accessiblities
| Default | Permitted declared accessibilities ------------------------------------------------------------------ namespace | public | none (always implicitly public) enum | public | All¹ interface | public | All¹ class | private | All¹ struct | private | public, internal, private² delegate | private | All¹ constructor | private | All¹ enum member | public | none (always implicitly public) interface member | public | none (always implicitly public) method | private | All¹ field | private | All¹ user-defined operator| none | public (must be declared public)
¹ All === public, protected, internal, private, protected internal
² structs cannot inherit from structs or classes (although they can, interfaces), hence protected is not a valid modifier
The accessibility of a nested type depends on its accessibility domain, which is determined by both the declared accessibility of the member and the accessibility domain of the immediately containing type. However, the accessibility domain of a nested type cannot exceed that of the containing type.
Note: CIL also has the provision for protected and internal (as opposed to the existing protected "or" internal), but to my knowledge this is not currently available for use in C#.
See:
http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx
http://msdn.microsoft.com/en-us/library/ms173121.aspx
http://msdn.microsoft.com/en-us/library/cx03xt0t.aspx
(Man I love Microsoft URLs...)
Another option is to map is as a Map of composite elements in the ConfPath table.
This mapping would benefit from an index on (ConfPathID,levelStation) though.
public class ConfPath {
private Map<Long,Time> timeForLevelStation = new HashMap<Long,Time>();
public Time getTime(long levelStation) {
return timeForLevelStation.get(levelStation);
}
public void putTime(long levelStation, Time newValue) {
timeForLevelStation.put(levelStation, newValue);
}
}
public class Time {
String src;
String dst;
long distance;
long price;
public long getDistance() {
return distance;
}
public void setDistance(long distance) {
this.distance = distance;
}
public String getDst() {
return dst;
}
public void setDst(String dst) {
this.dst = dst;
}
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
}
Mapping:
<class name="ConfPath" table="ConfPath">
<id column="ID" name="id">
<generator class="native"/>
</id>
<map cascade="all-delete-orphan" name="values" table="example"
lazy="extra">
<key column="ConfPathID"/>
<map-key type="long" column="levelStation"/>
<composite-element class="Time">
<property name="src" column="src" type="string" length="100"/>
<property name="dst" column="dst" type="string" length="100"/>
<property name="distance" column="distance"/>
<property name="price" column="price"/>
</composite-element>
</map>
</class>
In Python 2.x just put a ,
at the end of your print
statement. If you want to avoid the blank space that print
puts between items, use sys.stdout.write
.
import sys
sys.stdout.write('hi there')
sys.stdout.write('Bob here.')
yields:
hi thereBob here.
Note that there is no newline or blank space between the two strings.
In Python 3.x, with its print() function, you can just say
print('this is a string', end="")
print(' and this is on the same line')
and get:
this is a string and this is on the same line
There is also a parameter called sep
that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep
)
E.g.,
Python 2.x
print 'hi', 'there'
gives
hi there
Python 3.x
print('hi', 'there', sep='')
gives
hithere
One approach:
(
shopt -s nullglob
files=(/home/edward/bank1/fiche/Test*)
if [[ "${#files[@]}" -gt 0 ]] ; then
echo found one
else
echo found none
fi
)
Explanation:
shopt -s nullglob
will cause /home/edward/bank1/fiche/Test*
to expand to nothing if no file matches that pattern. (Without it, it will be left intact.)( ... )
sets up a subshell, preventing shopt -s nullglob
from "escaping".files=(/home/edward/bank1/fiche/Test*)
puts the file-list in an array named files
. (Note that this is within the subshell only; files
will not be accessible after the subshell exits.)"${#files[@]}"
is the number of elements in this array.Edited to address subsequent question ("What if i also need to check that these files have data in them and are not zero byte files"):
For this version, we need to use -s
(as you did in your question), which also tests for the file's existence, so there's no point using shopt -s nullglob
anymore: if no file matches the pattern, then -s
on the pattern will be false. So, we can write:
(
found_nonempty=''
for file in /home/edward/bank1/fiche/Test* ; do
if [[ -s "$file" ]] ; then
found_nonempty=1
fi
done
if [[ "$found_nonempty" ]] ; then
echo found one
else
echo found none
fi
)
(Here the ( ... )
is to prevent file
and found_file
from "escaping".)
arr = [1,9,5,2,4,9,5,8,7,9,0,8,2,7,5,8,0,2,9]
arr[rand(arr.count)]
This will return a random element from array.
If You will use the line mentioned below
arr[1+rand(arr.count)]
then in some cases it will return 0 or nil value.
The line mentioned below
rand(number)
always return the value from 0 to number-1.
If we use
1+rand(number)
then it may return number and arr[number] contains no element.
Create List Of String
public static List<string> HTMLFiles = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
HTMLFiles.AddRange(Directory.GetFiles(@"C:\DataBase", "*.txt"));
foreach (var item in HTMLFiles)
{
MessageBox.Show(item);
}
}
Simple and neet : use vw
units for a responsive height/width according to the viewport width.
vw : 1/100th of the width of the viewport. (Source MDN)
HTML:
<div></div>
CSS for a 1:1 aspect ratio:
div{
width:80vw;
height:80vw; /* same as width */
}
Table to calculate height according to the desired aspect ratio and width of element.
aspect ratio | multiply width by
-----------------------------------
1:1 | 1
1:3 | 3
4:3 | 0.75
16:9 | 0.5625
This technique allows you to :
position:absolute;
These units are supported by IE9+ see canIuse for more info
The simplest possible solution I found was:
In your markup:
<a [href]="location.path()">Reload</a>
and in your component typescript file:
constructor(
private location: Location
) { }
I came across the join() while learning about race condition and I will clear the doubts I was having. So let us take this small example
Thread t2 = new Thread(
new Runnable() {
public void run () {
//do something
}
}
);
Thread t1 = new Thread(
new Runnable() {
public void run () {
//do something
}
}
);
t2.start(); //Line 11
t1.start(); //Line 12
t2.join(); //Line 13
t1.join(); //Line 14
System.out.print("<Want to print something that was being modified by t2 and t1>")
My AIM
Three threads are running namely t1, t2 and the main thread. I want to print something after the t1 and t2 has finished. The printing operation is on my main thread therefore for the expected answer I need to let t1 and t2 finish and then print my output.
So t1.join() just makes the main thread wait, till the t1 thread completes before going to the next line in program.
Here is the definition as per GeeksforGeeks:
java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution.
Here is one question that might solve your doubt
Q-> Will t1 thread get the time slice to run by the thread scheduler, when the program is processing the t2.join() at Line 13?
ANS-> Yes it will be eligible to get the time slice to run as we have already made it eligible by running the line t1.start() at Line 11.
t2.join() only applies the condition when the JVM will go to next line, that is Line 14.
It might be also possible that t1 might get finished processing at Line 13.
I moved configuration to code to enable easy modification from CI using system variable. I used this code for file name and result is 'Log_03-23-2020.log'
log4net.Repository.ILoggerRepository repository = LogManager.GetRepository(Assembly.GetEntryAssembly());
Hierarchy hierarchy = (Hierarchy)repository;
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%date %level - %message%newline%exception";
patternLayout.ActivateOptions();
RollingFileAppender roller = new RollingFileAppender();
roller.AppendToFile = true;
roller.File = "Log_";
roller.DatePattern = "MM-dd-yyyy'.log'";
roller.Layout = patternLayout;
roller.MaxFileSize = 1024*1024*10;
roller.MaxSizeRollBackups = 10;
roller.StaticLogFileName = false;
roller.RollingStyle = RollingFileAppender.RollingMode.Composite;
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);
Also you can use COALESCE instead of CASE expression. Because result of concatenating anything to NULL, even itself, is always NULL
INSERT TblStuff(FullName,Address,City,Zip)
SELECT COALESCE(Fname + ' ' + Middle + ' ' + Lname, Fname + LName) AS FullName,
COALESCE(Address1 + ', ' + Address2, Address1) AS Address, City, Zip
FROM tblImport
Demo on SQLFiddle
Basing on this tutorial, here a very basic way to do that:
$('your_trigger_element_selector').on('click', function(){
var data = new FormData();
data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
// append other variables to data if you want: data.append('field_name_x', field_value_x);
$.ajax({
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
url: your_ajax_path,
dataType : 'json',
// in PHP you can call and process file in the same way as if it was submitted from a form:
// $_FILES['input_file_name']
success: function(jsonData){
...
}
...
});
});
Don't forget to add proper error handling
I had a similar solution like @maximilianus. The difference was that my .repositories files were called _remote.repositores and I had to delete them to make it work.
For eg in my case I deleted
After doing so my errors disappeared.
if you are using VirtualBox and UBUNTU in it or you are simply using UBUNTU then it can be useful
wget https://github.com/andrewvc/ee-datasets/archive/master.zip
sudo apt-get install unzip (only if unzip module is not installed)
unzip master.zip
cd ee-datasets
java -jar elastic-loader.jar http://localhost:9200 datasets/movie_db.eloader
Make sure your code is in DOM Ready as pointed by rocket-hazmat
$('#RootNode').click(function(){
//do something
});
document.getElementById("RootNode").onclick = function(){//do something}
$(document).on("click", "#RootNode", function(){
//do something
});
Wrap Code in Dom Ready
$(document).ready(function(){
$('#RootNode').click(function(){
//do something
});
});
I have found some of the other answers to be overly complicated when all you really need is this
app.directive('autoFocus', function($timeout) {
return {
restrict: 'AC',
link: function(_scope, _element) {
$timeout(function(){
_element[0].focus();
}, 0);
}
};
});
usage is
<input name="theInput" auto-focus>
We use the timeout to let things in the dom render, even though it is zero, it at least waits for that - that way this works in modals and whatnot too
You can use the description
method inherited by NSDictionary
from NSObject
, or write a custom method that formats NSDictionary
to your liking.
I've created a library for parsing User Agent strings called Voodoo. But be aware that this should not be used instead of feature detection.
What Voodoo does, is that it parses the userAgent string, which is found in the Navigator object (window.navigator). It's not all browsers that passes a reliable userAgent string, so even though it's the normal way to do it, the userAgent can not always be trusted.
Using a subshell substitution to parse the words undoes all the work you are doing to put spaces together.
Try instead:
cat CSV_file | sed -n 1'p' | tr ',' '\n' | while read word; do
echo $word
done
That also increases parallelism. Using a subshell as in your question forces the entire subshell process to finish before you can start iterating over the answers. Piping to a subshell (as in my answer) lets them work in parallel. This matters only if you have many lines in the file, of course.
First make some data:
> df = data.frame(matrix(rnorm(20), nrow=10))
> df
X1 X2
1 0.7091409 -1.4061361
2 -1.1334614 -0.1973846
3 2.3343391 -0.4385071
4 -0.9040278 -0.6593677
5 0.4180331 -1.2592415
6 0.7572246 -0.5463655
7 -0.8996483 0.4231117
8 -1.0356774 -0.1640883
9 -0.3983045 0.7157506
10 -0.9060305 2.3234110
Then select some rows at random:
> df[sample(nrow(df), 3), ]
X1 X2
9 -0.3983045 0.7157506
2 -1.1334614 -0.1973846
10 -0.9060305 2.3234110
Use git merge-base <commit> <commit>
.
This command finds best common ancestor(s) between two commits. And if the common ancestor is identical to the last commit of a "branch" ,then we can safely assume that that a "branch" has been already merged into the master.
Here are the steps
git merge-base <commit-hash-step1> <commit-hash-step2>
. More info on git merge-base https://git-scm.com/docs/git-merge-base.
I cloned my git project using the git bash
on windows
. All the files then had LF
endings. Our repository has CRLF
endings as default.
I deleted the project, and then cloned it again using the Windows Command Prompt
. The CRLF
endings were intact then. In my case, if I had changed the endings for the project, then it would've resulted in a huge commit and would've caused trouble for my teammates. So, did it this way. Hope this helps somebody.
Just using this will add "mynewclass" to the element with the id myElement and revert it on the next call.
<div id="showhide" class="meta-info" onclick="changeclass(this);">
function changeclass(element) {
$(element).toggleClass('mynewclass');
}
Or for a slighly more jQuery way (you would run this after the DOM is loaded)
<div id="showhide" class="meta-info">
$('#showhide').click(function() {
$(this).toggleClass('mynewclass');
});
See a working example of this here: http://jsfiddle.net/S76WN/
You can configure HttpClient
to automatically pass credentials like this:
var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
git fetch
git branch --track branch-name origin/branch-name
First command makes sure you have remote branch in local repository. Second command creates local branch which tracks remote branch. It assumes that your remote name is origin
and branch name is branch-name
.
--track
option is enabled by default for remote branches and you can omit it.
git mv oldname newname
is just shorthand for:
mv oldname newname
git add newname
git rm oldname
i.e. it updates the index for both old and new paths automatically.
SELECT orderhed.ordernum, orderhed.orderdate, currrate.currencycode,
case(currrate.currentrate) when null then 1 else currrate.currentrate end
FROM orderhed LEFT OUTER JOIN currrate ON orderhed.company = currrate.company AND orderhed.orderdate = currrate.effectivedate
Faster way to create folder:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Every SQL batch has to fit in the Batch Size Limit: 65,536 * Network Packet Size.
Other than that, your query is limited by runtime conditions. It will usually run out of stack size because x IN (a,b,c) is nothing but x=a OR x=b OR x=c which creates an expression tree similar to x=a OR (x=b OR (x=c)), so it gets very deep with a large number of OR. SQL 7 would hit a SO at about 10k values in the IN, but nowdays stacks are much deeper (because of x64), so it can go pretty deep.
Update
You already found Erland's article on the topic of passing lists/arrays to SQL Server. With SQL 2008 you also have Table Valued Parameters which allow you to pass an entire DataTable as a single table type parameter and join on it.
XML and XPath is another viable solution:
SELECT ...
FROM Table
JOIN (
SELECT x.value(N'.',N'uniqueidentifier') as guid
FROM @values.nodes(N'/guids/guid') t(x)) as guids
ON Table.guid = guids.guid;
Use newid()
select newid()
or possibly this
select binary_checksum(newid())
<ComboBox Text="Something">
<ComboBoxItem Content="Item1"></ComboBoxItem >
<ComboBoxItem Content="Item2"></ComboBoxItem >
<ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>
Use:
function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
alert("pname["+i+"].value="+inp.value);
}
}
Here is Demo
.
Your code is just fine. The reason you're getting a black screen is because there's nothing on your second view controller.
Try something like:
secondViewController.view.backgroundColor = UIColor.redColor();
Now the view controller it shows should be red.
To actually do something with secondViewController
, create a subclass of UIViewController
and instead of
let secondViewController:UIViewController = UIViewController()
create an instance of your second view controller:
//If using code
let secondViewController = MyCustomViewController.alloc()
//If using storyboard, assuming you have a view controller with storyboard ID "MyCustomViewController"
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("MyCustomViewController") as UIViewController
Both git add .
and git add -A
will stage all new, modified and deleted files in the newer versions of Git.
The difference is that git add -A
stages files in "higher, current and subdirectories" that belong to your working Git repository. But doing a git add .
only stages files in the current directory and subdirectories following it (not the files lying outside, i.e., higher directories).
Here's an example:
/my-repo
.git/
subfolder/
nested-file.txt
rootfile.txt
If your current working directory is /my-repo
, and you do rm rootfile.txt
, then cd subfolder
, followed by git add .
, then it will not stage the deleted file. But doing git add -A
will certainly stage this change no matter where you perform the command from.
The command below will search all the files recursively whose name matches the search pattern and will replace the string:
find /path/to/searchdir/ -name "serachpatter" -type f | xargs sed -i 's/stringone/StrIngTwo/g'
Also if you want to limit the depth of recursion you can put the limits as well:
find /path/to/searchdir/ -name "serachpatter" -type f -maxdepth 4 -mindepth 2 | xargs sed -i 's/stringone/StrIngTwo/g'
This should work in SQL Server:
update ud
set assid = sale.assid
from sale
where sale.udid = id
One thing you need to realize is in Ruby everything is an object. Given that, if you don't define your methods within Module
or Class
, Ruby will put it within the Object
class. So, your code will be local to the Object
scope.
A typical approach on Object Oriented Programming is encapsulate all logic within a class:
class Point
attr_accessor :x, :y
# If we don't specify coordinates, we start at 0.
def initialize(x = 0, y = 0)
# Notice that `@` indicates instance variables.
@x = x
@y = y
end
# Here we override the `+' operator.
def +(point)
Point.new(self.x + point.x, self.y + point.y)
end
# Here we draw the point.
def draw(offset = nil)
if offset.nil?
new_point = self
else
new_point = self + offset
end
new_point.draw_absolute
end
def draw_absolute
puts "x: #{self.x}, y: #{self.y}"
end
end
first_point = Point.new(100, 200)
second_point = Point.new(3, 4)
second_point.draw(first_point)
Hope this clarifies a bit.
Mine was something simple/stupid. Newbie mistake, for anyone that has converted their NSManagedObject to a normal NSObject.
I had:
@dynamic order_id;
when i should have had:
@synthesize order_id;
There are significant differences. Let's set up some test cases:
var unused; // value will be undefined
Test("test1", "some value");
Test("test2");
Test("test3", unused);
Test("test4", null);
Test("test5", 0);
Test("test6", "");
With the first method you describe, only the second test will use the default value. The second method will default all but the first (as JS will convert undefined
, null
, 0
, and ""
into the boolean false
. And if you were to use Tom's method, only the fourth test will use the default!
Which method you choose really depends on your intended behavior. If values other than undefined
are allowable for argument2
, then you'll probably want some variation on the first; if a non-zero, non-null, non-empty value is desired, then the second method is ideal - indeed, it is often used to quickly eliminate such a wide range of values from consideration.
it works:
type HtmlEvent = React.ChangeEvent<HTMLSelectElement>
const onChange: React.EventHandler<HtmlEvent> =
(event: HtmlEvent) => {
console.log(event.target.value)
}
How about using Guid.NewGuid()
to create a GUID and use that as the filename (or part of the filename together with your time stamp if you like).
I made a comparison between a ReadAllText and StreamBuffer for a 2Mb csv and it seemed that the difference was quite small but ReadAllText seemed to take the upper hand from the times taken to complete functions.
One way is to use Kivy:
Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps.
Kivy runs on Linux, Windows, OS X, Android and iOS. You can run the same [python] code on all supported platforms.
printf("\nmaximum of %d and %d is = %d",a,b,c);
I used the Google Apps Script method indexOf()
and its results were wrong. So I wrote the small function Myindexof()
, instead of indexOf
:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');
I believe the web-cam application software which comes along with the web-cam, or you native windows webcam software can be run in a batch script(windows/dos script) after turning the web cam on(i.e. if it needs an external power supply). In the bacth script , u can add appropriate delay to capture after certain time period. And keep executing the capture command in loop.
I guess this should be possible
-AD
System scope was only designed to deal with 'system' files; files sitting in some fixed location. Files in /usr/lib
, or ${java.home}
(e.g. tools.jar
). It wasn't designed to support miscellaneous .jar
files in your project.
The authors intentionally refused to make the pathname expansions work right for that to discourage you. As a result, in the short term you can use install:install-file
to install into the local repo, and then some day use a repo manager to share.
In here you can save the phone number as international formatted phone number
internationalFormatPhoneNumber = phoneUtil.format(givenPhoneNumber, PhoneNumberFormat.INTERNATIONAL);
it return the phone number as International format +94 71 560 4888
so now I have get country code as this
String countryCode = internationalFormatPhoneNumber.substring(0,internationalFormatPhoneNumber.indexOf('')).replace('+', ' ').trim();
Hope this will help you
With a few tricks you can actually pass named parameters to functions, along with arrays.
The method I developed allows you to access parameters passed to a function like this:
testPassingParams() {
@var hello
l=4 @array anArrayWithFourElements
l=2 @array anotherArrayWithTwo
@var anotherSingle
@reference table # references only work in bash >=4.3
@params anArrayOfVariedSize
test "$hello" = "$1" && echo correct
#
test "${anArrayWithFourElements[0]}" = "$2" && echo correct
test "${anArrayWithFourElements[1]}" = "$3" && echo correct
test "${anArrayWithFourElements[2]}" = "$4" && echo correct
# etc...
#
test "${anotherArrayWithTwo[0]}" = "$6" && echo correct
test "${anotherArrayWithTwo[1]}" = "$7" && echo correct
#
test "$anotherSingle" = "$8" && echo correct
#
test "${table[test]}" = "works"
table[inside]="adding a new value"
#
# I'm using * just in this example:
test "${anArrayOfVariedSize[*]}" = "${*:10}" && echo correct
}
fourElements=( a1 a2 "a3 with spaces" a4 )
twoElements=( b1 b2 )
declare -A assocArray
assocArray[test]="works"
testPassingParams "first" "${fourElements[@]}" "${twoElements[@]}" "single with spaces" assocArray "and more... " "even more..."
test "${assocArray[inside]}" = "adding a new value"
In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1 (and others).
The code that makes this work is pretty light and works both in bash 3 and bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below was developed for that purpose.
Function.AssignParamLocally() {
local commandWithArgs=( $1 )
local command="${commandWithArgs[0]}"
shift
if [[ "$command" == "trap" || "$command" == "l="* || "$command" == "_type="* ]]
then
paramNo+=-1
return 0
fi
if [[ "$command" != "local" ]]
then
assignNormalCodeStarted=true
fi
local varDeclaration="${commandWithArgs[1]}"
if [[ $varDeclaration == '-n' ]]
then
varDeclaration="${commandWithArgs[2]}"
fi
local varName="${varDeclaration%%=*}"
# var value is only important if making an object later on from it
local varValue="${varDeclaration#*=}"
if [[ ! -z $assignVarType ]]
then
local previousParamNo=$(expr $paramNo - 1)
if [[ "$assignVarType" == "array" ]]
then
# passing array:
execute="$assignVarName=( \"\${@:$previousParamNo:$assignArrLength}\" )"
eval "$execute"
paramNo+=$(expr $assignArrLength - 1)
unset assignArrLength
elif [[ "$assignVarType" == "params" ]]
then
execute="$assignVarName=( \"\${@:$previousParamNo}\" )"
eval "$execute"
elif [[ "$assignVarType" == "reference" ]]
then
execute="$assignVarName=\"\$$previousParamNo\""
eval "$execute"
elif [[ ! -z "${!previousParamNo}" ]]
then
execute="$assignVarName=\"\$$previousParamNo\""
eval "$execute"
fi
fi
assignVarType="$__capture_type"
assignVarName="$varName"
assignArrLength="$__capture_arrLength"
}
Function.CaptureParams() {
__capture_type="$_type"
__capture_arrLength="$l"
}
alias @trapAssign='Function.CaptureParams; trap "declare -i \"paramNo+=1\"; Function.AssignParamLocally \"\$BASH_COMMAND\" \"\$@\"; [[ \$assignNormalCodeStarted = true ]] && trap - DEBUG && unset assignVarType && unset assignVarName && unset assignNormalCodeStarted && unset paramNo" DEBUG; '
alias @param='@trapAssign local'
alias @reference='_type=reference @trapAssign local -n'
alias @var='_type=var @param'
alias @params='_type=params @param'
alias @array='_type=array @param'
MySQL’s generic “errno 150” message “means that a foreign key constraint was not correctly formed.” As you probably already know if you are reading this page, the generic “errno: 150” error message is really unhelpful. However:
You can get the actual error message by running SHOW ENGINE INNODB STATUS;
and then looking for LATEST FOREIGN KEY ERROR
in the output.
For example, this attempt to create a foreign key constraint:
CREATE TABLE t1
(id INTEGER);
CREATE TABLE t2
(t1_id INTEGER,
CONSTRAINT FOREIGN KEY (t1_id) REFERENCES t1 (id));
fails with the error Can't create table 'test.t2' (errno: 150)
. That doesn’t tell anyone anything useful other than that it’s a foreign key problem. But run SHOW ENGINE INNODB STATUS;
and it will say:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
130811 23:36:38 Error in foreign key constraint of table test/t2:
FOREIGN KEY (t1_id) REFERENCES t1 (id)):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
It says that the problem is it can’t find an index. SHOW INDEX FROM t1
shows that there aren’t any indexes at all for table t1
. Fix that by, say, defining a primary key on t1
, and the foreign key constraint will be created successfully.
This is lighter weight than xrange
(and the while loop) since it doesn't even need to create the int
objects. It also works equally well in Python2 and Python3
from itertools import repeat
for i in repeat(None, 10):
do_sth()
This happened to me using the Eclipse plug-in and synchronizing. The file causing the issue had no local changes (and in fact no remote changes since my last update). I chose "revert" for the file, with no other modifications to the files, and things returned to normal.
html { overflow-y: scroll; }
This css
rule causes a vertical scrollbar to always appear.
Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/
Use sprintf.
int sprintf ( char * str, const char * format, ... );
Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.
The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).
A terminating null character is automatically appended after the content.
After the format parameter, the function expects at least as many additional arguments as needed for format.
str
Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.
format
C string that contains a format string that follows the same specifications as format in printf (see printf for details).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");
I used the TO_PURE_NUMBER()
function and it worked.
1> Add this namspace. using Newtonsoft.Json.Linq;
2> use this source code.
JObject joResponse = JObject.Parse(response);
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());
This is the simplest example of function pointers and function pointer arrays that I wrote as an exercise.
typedef double (*pf)(double x); /*this defines a type pf */
double f1(double x) { return(x+x);}
double f2(double x) { return(x*x);}
pf pa[] = {f1, f2};
main()
{
pf p;
p = pa[0];
printf("%f\n", p(3.0));
p = pa[1];
printf("%f\n", p(3.0));
}
Just to elaborate a bit on the meta-tag thing. I've heard a talk, where a statement was made, one should always insert the "no-sniff" meta tag in the html to prevent browser sniffing (just like OP did):
<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />
However, this is not a valid method for w3c compliant websites, the validator will raise an error:
Bad value text/html; charset=UTF-8; X-Content-Type-Options=nosniff for attribute content on element meta: The legacy encoding contained ;, which is not a valid character in an encoding name.
And there is no fixing this. To rightly turn off no-sniff, one has to go to the server settings and turn it off there. Because the "no-sniff" option is something from the HTTP header, not from the HTML file which is attached at the HTTP response.
To check if the no-sniff option is disabled, one can enable the developer console, networks tab and then inspect the HTTP response header:
Tried this on firefox, works http://jsfiddle.net/Tm26Q/1/
$(function(){
/** Just to mimic a blinking box on the page**/
setInterval(function(){$("div#box").hide();},2001);
setInterval(function(){$("div#box").show();},1000);
/**/
});
$("div#box").on("DOMAttrModified",
function(){if($(this).is(":visible"))console.log("visible");});
UPDATE
Currently the Mutation Events (like
DOMAttrModified
used in the solution) are replaced by MutationObserver, You can use that to detect DOM node changes like in the above case.
You can:
mkdir -p folder/subfolder
The -p
flag causes any parent directories to be created if necessary.
I had the same problem, and using this solved it.
var w = window.innerWidth;
var h = window.innerHeight;
If there is a project you earlier imported externally (outside of Workspace), that may cause this problem. If you can access Eclipse try to remove it. If you are getting the 'No responding at startup', then go delete the file at source.
This will solve the problem.
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
If you wanna hide that column while grid populating, you can do it in aspx page itself like this
<asp:BoundField DataField="test" HeaderText="test" Visible="False" />
Minor update in @Joran's code.
Using the code below, you can avoid the ambiguity and only get the unique of two columns:
dat <- data.frame(id=c(1,1,3), id2=c(1,1,4) ,somevalue=c("x","y","z"))
dat[row.names(unique(dat[,c("id", "id2")])), c("id", "id2")]
I also ran into this problem, and was able to work around a similar EOF error using:
read.table("....csv", sep=",", ...)
Notice that the separator parameter is defined within the more general read.table()
.
This helped me ..
@Override
public void onBackPressed() {
startActivity(new Intent(currentActivity.this, LastActivity.class));
finish();
}
OR????? even you can use this for drawer toggle also
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
startActivity(new Intent(currentActivity.this, LastActivity.class));
finish();
}
I hope this would help you.. :)
This can easily be done using Java 8 and the use of a reversed Comparator.
I have created a list of files from a directory, which I display unsorted, sorted and reverse sorted using a simple Comparator for the sort and then calling reversed() on it to get the reversed version of that Comparator.
See code below:
package test;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
public static void main(String... args) {
File directory = new File("C:/Media");
File[] files = directory.listFiles();
List<File> filesList = Arrays.asList(files);
Comparator<File> comparator = Comparator.comparingLong(File::lastModified);
Comparator<File> reverseComparator = comparator.reversed();
List<File> forwardOrder = filesList.stream().sorted(comparator).collect(Collectors.toList());
List<File> reverseOrder = filesList.stream().sorted(reverseComparator).collect(Collectors.toList());
System.out.println("*** Unsorted ***");
filesList.forEach(SortTest::processFile);
System.out.println("*** Sort ***");
forwardOrder.forEach(SortTest::processFile);
System.out.println("*** Reverse Sort ***");
reverseOrder.forEach(SortTest::processFile);
}
private static void processFile(File file) {
try {
if (file.isFile()) {
System.out.println(file.getCanonicalPath() + " - " + new Date(file.lastModified()));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
For multiple integer in a single line, map
might be better.
arr = map(int, raw_input().split())
If the number is already known, (like 2 integers), you can use
num1, num2 = map(int, raw_input().split())
In the VSCode launch.json you can use "env" and configure all your environment variables there:
{
"version": "0.2.0",
"configurations": [
{
"env": {
"NODE_ENV": "development",
"port":"1337"
},
...
}
]
}
May be by:-
for(Row row : sheet) {
for(Cell cell : row) {
System.out.print(cell.getStringCellValue());
}
}
For specific type of cell you can try:
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
cellValue = Double.toString(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
First, see if you have splitunc()
as an available function within os.path
. The first item returned should be what you want... but I am on Linux and I do not have this function when I import os
and try to use it.
Otherwise, one semi-ugly way that gets the job done is to use:
>>> pathname = "\\C:\\mystuff\\project\\file.py"
>>> pathname
'\\C:\\mystuff\\project\\file.py'
>>> print pathname
\C:\mystuff\project\file.py
>>> "\\".join(pathname.split('\\')[:-2])
'\\C:\\mystuff'
>>> "\\".join(pathname.split('\\')[:-1])
'\\C:\\mystuff\\project'
which shows retrieving the directory just above the file, and the directory just above that.
Delete Id from table where Id in (select id from table)
if ComboBoxStyle
is set to DropDownList
then the easiest way to make sure the user selects an item is to set SelectedIndex = -1
, which will be empty
The following code works perfectly
public Comparator<Map<String, String>> mapComparator = new Comparator<Map<String, String>>() {
public int compare(Map<String, String> m1, Map<String, String> m2) {
return m1.get("name").compareTo(m2.get("name"));
}
}
Collections.sort(list, mapComparator);
But your maps should probably be instances of a specific class.
print
first converts the object to a string (if it is not already a string). It will also put a space before the object if it is not the start of a line and a newline character at the end.
When using stdout
, you need to convert the object to a string yourself (by calling "str", for example) and there is no newline character.
So
print 99
is equivalent to:
import sys
sys.stdout.write(str(99) + '\n')
other method:
type initial letter then ctrl+spacebar for auto-complete options.
Here's what I'm using to get plain response object with non-stringified values and all nested associations from sequelize
v4 query.
With plain JavaScript (ES2015+):
const toPlain = response => {
const flattenDataValues = ({ dataValues }) => {
const flattenedObject = {};
Object.keys(dataValues).forEach(key => {
const dataValue = dataValues[key];
if (
Array.isArray(dataValue) &&
dataValue[0] &&
dataValue[0].dataValues &&
typeof dataValue[0].dataValues === 'object'
) {
flattenedObject[key] = dataValues[key].map(flattenDataValues);
} else if (dataValue && dataValue.dataValues && typeof dataValue.dataValues === 'object') {
flattenedObject[key] = flattenDataValues(dataValues[key]);
} else {
flattenedObject[key] = dataValues[key];
}
});
return flattenedObject;
};
return Array.isArray(response) ? response.map(flattenDataValues) : flattenDataValues(response);
};
With lodash (a bit more concise):
const toPlain = response => {
const flattenDataValues = ({ dataValues }) =>
_.mapValues(dataValues, value => (
_.isArray(value) && _.isObject(value[0]) && _.isObject(value[0].dataValues)
? _.map(value, flattenDataValues)
: _.isObject(value) && _.isObject(value.dataValues)
? flattenDataValues(value)
: value
));
return _.isArray(response) ? _.map(response, flattenDataValues) : flattenDataValues(response);
};
Usage:
const res = await User.findAll({
include: [{
model: Company,
as: 'companies',
include: [{
model: Member,
as: 'member',
}],
}],
});
const plain = toPlain(res);
// 'plain' now contains simple db object without any getters/setters with following structure:
// [{
// id: 123,
// name: 'John',
// companies: [{
// id: 234,
// name: 'Google',
// members: [{
// id: 345,
// name: 'Paul',
// }]
// }]
// }]
According to the Git Cheatsheet you have to create the branch first
git branch [branchName]
and then
git checkout [branchName]
The PropertyInfo class should help you achieve this, if I understand correctly.
PropertyInfo[] propInfos = typeof(ReflectedType).GetProperties();
propInfos.ToList().ForEach(p =>
Console.WriteLine(string.Format("Property name: {0}", p.Name));
Is this what you need?
'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';
It don't create normally; you need to add it by yourself.
After adding Global.asax
by
You need to add a class
Inherit the newly generated by System.Web.HttpApplication
and copy all the method created Global.asax
to Global.cs
and also add an inherit attribute to the Global.asax file.
Your Global.asax will look like this: -
<%@ Application Language="C#" Inherits="Global" %>
Your Global.cs in App_Code
will look like this: -
public class Global : System.Web.HttpApplication
{
public Global()
{
//
// TODO: Add constructor logic here
//
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
/// Many other events like begin request...e.t.c, e.t.c
}
Just thinking you might be feel unfamiliar of the sequence From->Where->Select, as in sql script, it is like Select->From->Where.
But you may not know that inside Sql Engine, it is also parse in the sequence of 'From->Where->Select', To validate it, you can try a simple script
select id as i from table where i=3
and it will not work, the reason is engine will parse Where before Select, so it won't know alias i in the where. To make this work, you can try
select * from (select id as i from table) as t where i = 3
//Arrange the Picture Of Path.***
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
string[] PicPathArray;
string ArrangePathOfPic;
PicPathArray = openFileDialog1.FileName.Split('\\');
ArrangePathOfPic = PicPathArray[0] + "\\\\" + PicPathArray[1];
for (int a = 2; a < PicPathArray.Length; a++)
{
ArrangePathOfPic = ArrangePathOfPic + "\\\\" + PicPathArray[a];
}
}
// Save the path Of Pic in database
SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("insert into PictureTable (Pic_Path) values (@Pic_Path)", con);
cmd.Parameters.Add("@Pic_Path", SqlDbType.VarChar).Value = ArrangePathOfPic;
cmd.ExecuteNonQuery();
***// Get the Picture Path in Database.***
SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Pic_Path where ID = @ID", con);
SqlDataAdapter adp = new SqlDataAdapter();
cmd.Parameters.Add("@ID",SqlDbType.VarChar).Value = "1";
adp.SelectCommand = cmd;
DataTable DT = new DataTable();
adp.Fill(DT);
DataRow DR = DT.Rows[0];
pictureBox1.Image = Image.FromFile(DR["Pic_Path"].ToString());
All scripting languages are programming languages. So strictly speaking, there is no difference.
The term doesn't refer to any fundamental properties of the language, it refers to the typical use of the language. If the typical use is to write short programs that mainly do calls to pre-existing code, and some simple processing on the results, (that is, if the typical use is to write scripts) then it is a scripting language.
The Function adds gaussian , salt-pepper , poisson and speckle noise in an image
Parameters
----------
image : ndarray
Input image data. Will be converted to float.
mode : str
One of the following strings, selecting the type of noise to add:
'gauss' Gaussian-distributed additive noise.
'poisson' Poisson-distributed noise generated from the data.
's&p' Replaces random pixels with 0 or 1.
'speckle' Multiplicative noise using out = image + n*image,where
n is uniform noise with specified mean & variance.
import numpy as np
import os
import cv2
def noisy(noise_typ,image):
if noise_typ == "gauss":
row,col,ch= image.shape
mean = 0
var = 0.1
sigma = var**0.5
gauss = np.random.normal(mean,sigma,(row,col,ch))
gauss = gauss.reshape(row,col,ch)
noisy = image + gauss
return noisy
elif noise_typ == "s&p":
row,col,ch = image.shape
s_vs_p = 0.5
amount = 0.004
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
elif noise_typ == "poisson":
vals = len(np.unique(image))
vals = 2 ** np.ceil(np.log2(vals))
noisy = np.random.poisson(image * vals) / float(vals)
return noisy
elif noise_typ =="speckle":
row,col,ch = image.shape
gauss = np.random.randn(row,col,ch)
gauss = gauss.reshape(row,col,ch)
noisy = image + image * gauss
return noisy
I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.
Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.
To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.
There is an issue with the Command + F solution. It will replace all 0's if you click replace all. This means if you do not review every zero, zero's contained in important cells will also be removed. For example, if you have phone numbers that have (420) area codes they will all be changed to (40).
If you didn't want to sign up for a service, I'd probably go back to the exchanges themselves; most of them aren't CAPTCHAed yet...
The symbol lookup page for:
etc...
B is not statistically significant. The data is not capable of drawing inferences from it. C does influence B probabilities
df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
avg_c=df['C'].mean()
sumC=df['C'].apply(lambda x: x if x<avg_c else 0).sum()
countC=df['C'].apply(lambda x: 1 if x<avg_c else None).count()
avg_c2=sumC/countC
df['C']=df['C'].apply(lambda x: avg_c2 if x >avg_c else x)
print(df)
model_ols = smf.ols("A ~ B+C",data=df).fit()
print(model_ols.summary())
df[['B','C']].plot()
plt.show()
df2=pd.DataFrame()
df2['B']=np.linspace(10,50,10)
df2['C']=30
df3=pd.DataFrame()
df3['B']=np.linspace(10,50,10)
df3['C']=100
predB=model_ols.predict(df2)
predC=model_ols.predict(df3)
plt.plot(df2['B'],predB,label='predict B C=30')
plt.plot(df3['B'],predC,label='predict B C=100')
plt.legend()
plt.show()
print("A change in the probability of C affects the probability of B")
intercept=model_ols.params.loc['Intercept']
B_slope=model_ols.params.loc['B']
C_slope=model_ols.params.loc['C']
#Intercept 11.874252
#B 0.760859
#C -0.060257
print("Intercept {}\n B slope{}\n C slope{}\n".format(intercept,B_slope,C_slope))
#lower_conf,upper_conf=np.exp(model_ols.conf_int())
#print(lower_conf,upper_conf)
#print((1-(lower_conf/upper_conf))*100)
model_cov=model_ols.cov_params()
std_errorB = np.sqrt(model_cov.loc['B', 'B'])
std_errorC = np.sqrt(model_cov.loc['C', 'C'])
print('SE: ', round(std_errorB, 4),round(std_errorC, 4))
#check for statistically significant
print("B z value {} C z value {}".format((B_slope/std_errorB),(C_slope/std_errorC)))
print("B feature is more statistically significant than C")
Output:
A change in the probability of C affects the probability of B
Intercept 11.874251554067563
B slope0.7608594144571961
C slope-0.060256845997223814
Standard Error: 0.4519 0.0793
B z value 1.683510336937001 C z value -0.7601036314930376
B feature is more statistically significant than C
z>2 is statistically significant
Count()
is an extension method introduced by LINQ while the Count
property is part of the List itself (derived from ICollection
). Internally though, LINQ checks if your IEnumerable
implements ICollection
and if it does it uses the Count
property. So at the end of the day, there's no difference which one you use for a List
.
To prove my point further, here's the code from Reflector for Enumerable.Count()
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
Modified code of Tapas's answer:
Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
username = oReturn("UserName")
Next
This one did it for me:
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "mydata").val("bla");
$('#form1').append(input);
is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)
used the Firefox firebug to check whether the element was inserted.
Hidden elements do get posted back in the form collection, only read-only fields are discarded.
Michel
Something that I saw people using is stringexpression > ''
. This may be not the fastest one, but happens to be one of the shortest.
Tried it on MS SQL as well as on PostgreSQL.
You can convert a string to a date easily by:
CAST(YourDate AS DATE)
In case this helps anyone. I had a similar problem where my ViewWillAppear
is not firing on a UITableViewController
. After a lot of playing around, I realized that the problem was that the UINavigationController
that is controlling my UITableView
is not on the root view. Once I fix that, it is now working like a champ.
You set disable the Logs by setting its level to OFF as follows:
Logger.getLogger("org").setLevel(Level.OFF);
Logger.getLogger("akka").setLevel(Level.OFF);
or edit log file and set log level to off by just changing the following property:
log4j.rootCategory=OFF, console
Inner join matches tables on keys, but outer join matches keys just for one side. For example when you use left outer join the query brings the whole left side table and matches the right side to the left table primary key and where there is not matched places null.
Here's a Swift version:
func durationsBySecond(seconds s: Int) -> (days:Int,hours:Int,minutes:Int,seconds:Int) {
return (s / (24 * 3600),(s % (24 * 3600)) / 3600, s % 3600 / 60, s % 60)
}
Can be used like this:
let (d,h,m,s) = durationsBySecond(seconds: duration)
println("time left: \(d) days \(h) hours \(m) minutes \(s) seconds")
I found the right answer just by comparing the conversion to 1/1/1970 w/o the local time adjustment;
DateTime date = new DateTime(2011, 4, 1, 12, 0, 0, 0);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan span = (date - epoch);
double unixTime =span.TotalSeconds;
In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".
Here are 2 from infochimps.com:
http://www.infochimps.com/datasets/wikipedia-articles-abstract-search
http://www.infochimps.com/datasets/wikipedia-articles-title-autocomplete
Add this single line in your activity, after setContentView()
call
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
Try this:
<a onclick='$("#notification").fadeOut(300, function() { $(this).remove(); });' class="notificationClose "><img src="close.png"/></a>
I think your double quotes around the onclick
were making it not work. :)
EDIT: As pointed out below, inline javascript is evil and you should probably take this out of the onclick
and move it to jQuery's click()
event handler. That is how the cool kids are doing it nowadays.
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
The Jenkinsfile is written in groovy which uses the Java (and C) form of comments:
/* this
is a
multi-line comment */
// this is a single line comment
In case you don't want to use any graphical interface for vim and you prefer to just stick with terminal emulator there may be a much simpler approach to this problem. Instead of using yank or anything like this, first take a look at documentation of terminal you use. I've been struggling with the same issue (trying to use +clipboard and xclip and so on) and in the end it turned out that in my terminal emulator it's enough to just press shift and select any text you want to copy. That's it. Quite simple and no need for messing with configuration. (I use urxvt by the way).
if (myReader.HasRows) //The key Word is **.HasRows**
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null Or Empty";
}
With bootstrap 4 just use col-auto
<div class="container-fluid">
<div class="row">
<div class="col-sm-auto">
Fixed content
</div>
<div class="col-sm">
Normal scrollable content
</div>
</div>
</div>
Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?
14 bits = 16 384, 20 bits = 1 048 576
14 + 20 = 34 bits = more than one 32 bit register can hold.
But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.
Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.
Update 2016:
Found a link to Microsoft's specification for Excel 2013 & 2016
This works for me:
C:\xampp\phpMyAdmin\config.inc.php
$cfg['Servers'][$i]['password'] = 'secret';
Edit: Before you got this error it is most likely that from phpmyadmin->Users you have added password for the root user. In my case that was "secret" so the above primer works for me BUT for you will work this:
$cfg['Servers'][$i]['password'] = 'Enter the password for root you have added before you got this error';
If you use the html approach:
don't add blank lines
Like this:
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
the markup will break.
Remove blank lines:
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
If you still want to show the item but make it not clickable and look disabled with CSS:
CSS:
.disabled {
pointer-events:none; //This makes it not clickable
opacity:0.6; //This grays it out to look disabled
}
HTML:
<li class="disabled">Disabled List Item</li>
Also, if you are using BootStrap, they already have a class called disabled for this purpose. See this example.
As @LV98 pointed out, users could change this on the client side and submit a selection you weren't expecting. You will want to validate at the server as well.
@m59 Directives will work for ng-bind-html you just need to wait for $viewContentLoaded
to finish
app.directive('targetBlank', function($timeout) {
return function($scope, element) {
$scope.initializeTarget = function() {
return $scope.$on('$viewContentLoaded', $timeout(function() {
var elems;
elems = element.prop('tagName') === 'A' ? element : element.find('a');
elems.attr('target', '_blank');
}));
};
return $scope.initializeTarget();
};
});
Do, I need to resolve all the conflicts before proceeding to next cherry -pick
Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.
Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.
That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.
Further, is it suggested to do cherry-pick or branch merge in this case?
Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.
Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.
var timeoutId = 0;
$('#myElement').on('mousedown', function() {
timeoutId = setTimeout(myFunction, 1000);
}).on('mouseup mouseleave', function() {
clearTimeout(timeoutId);
});
Edit: correction per AndyE...thanks!
Edit 2: using bind now for two events with same handler per gnarf
For a menu which responds to click events as opposed to just hover, and acts in a similar way to a select control...
HTML
<ul tabindex='0'>
<li>
<input id='item1' type='radio' name='item' checked='true' />
<label for='item1'>Item 1</label>
</li>
<li>
<input id='item2' type='radio' name='item' />
<label for='item2'>Item 2</label>
</li>
<li>
<input id='item3' type='radio' name='item' />
<label for='item3'>Item 3</label>
</li>
</ul>
CSS
ul, li {
list-style:none;
margin:0;
padding:0;
}
li input {
display:none;
}
ul:not(:focus) input:not(:checked), ul:not(:focus) input:not(:checked) + label {
display:none;
}
input:checked+label {
color:red;
}
You can use "struct" in C++ if you are writing a library whose internals are C++ but the API can be called by either C or C++ code. You simply make a single header that contains structs and global API functions that you expose to both C and C++ code as this:
// C access Header to a C++ library
#ifdef __cpp
extern "C" {
#endif
// Put your C struct's here
struct foo
{
...
};
// NOTE: the typedef is used because C does not automatically generate
// a typedef with the same name as a struct like C++.
typedef struct foo foo;
// Put your C API functions here
void bar(foo *fun);
#ifdef __cpp
}
#endif
Then you can write a function bar() in a C++ file using C++ code and make it callable from C and the two worlds can share data through the declared struct's. There are other caveats of course when mixing C and C++ but this is a simplified example.
@ModelAttribute
is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username
and userClient.firstName
, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient
object.
(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)
You can use this code -
Block Right Click -
<body oncontextmenu="return false;">
Block Keys - You should use this on the upper of the body tag. (use in the head tag)
<script>
document.onkeydown = function (e) {
if (event.keyCode == 123) {
return false;
}
if (e.ctrlKey && e.shiftKey && (e.keyCode == 'I'.charCodeAt(0) || e.keyCode == 'i'.charCodeAt(0))) {
return false;
}
if (e.ctrlKey && e.shiftKey && (e.keyCode == 'C'.charCodeAt(0) || e.keyCode == 'c'.charCodeAt(0))) {
return false;
}
if (e.ctrlKey && e.shiftKey && (e.keyCode == 'J'.charCodeAt(0) || e.keyCode == 'j'.charCodeAt(0))) {
return false;
}
if (e.ctrlKey && (e.keyCode == 'U'.charCodeAt(0) || e.keyCode == 'u'.charCodeAt(0))) {
return false;
}
if (e.ctrlKey && (e.keyCode == 'S'.charCodeAt(0) || e.keyCode == 's'.charCodeAt(0))) {
return false;
}
}
</script>
I wanted to change default java version form 1.6* to 1.7*. I tried the following steps and it worked for me:
ln -s /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/bin/java java
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:
<textarea name="comentarii" cols="36" rows="5" placeholder="Message>
biplot
using sklearn
and matplotlib
.import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
import pandas as pd
from sklearn.preprocessing import StandardScaler
iris = datasets.load_iris()
X = iris.data
y = iris.target
#In general a good idea is to scale the data
scaler = StandardScaler()
scaler.fit(X)
X=scaler.transform(X)
pca = PCA()
x_new = pca.fit_transform(X)
def myplot(score,coeff,labels=None):
xs = score[:,0]
ys = score[:,1]
n = coeff.shape[0]
scalex = 1.0/(xs.max() - xs.min())
scaley = 1.0/(ys.max() - ys.min())
plt.scatter(xs * scalex,ys * scaley, c = y)
for i in range(n):
plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)
if labels is None:
plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')
else:
plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("PC{}".format(1))
plt.ylabel("PC{}".format(2))
plt.grid()
#Call the function. Use only the 2 PCs.
myplot(x_new[:,0:2],np.transpose(pca.components_[0:2, :]))
plt.show()
I made a singleton helper class that holds temporary objects.
public class IntentHelper {
private static IntentHelper _instance;
private Hashtable<String, Object> _hash;
private IntentHelper() {
_hash = new Hashtable<String, Object>();
}
private static IntentHelper getInstance() {
if(_instance==null) {
_instance = new IntentHelper();
}
return _instance;
}
public static void addObjectForKey(Object object, String key) {
getInstance()._hash.put(key, object);
}
public static Object getObjectForKey(String key) {
IntentHelper helper = getInstance();
Object data = helper._hash.get(key);
helper._hash.remove(key);
helper = null;
return data;
}
}
Instead of putting your objects within Intent, use IntentHelper:
IntentHelper.addObjectForKey(obj, "key");
Inside your new Activity, you can get the object:
Object obj = (Object) IntentHelper.getObjectForKey("key");
Bear in mind that once loaded, the object is removed to avoid unnecessary references.
When a JSON start's with {} it is a ObjectJSON object and when it start's with [] it is an Array JOSN Array
An JSON array can consist of a/many objects and that is called an array of objects
See This question
Your logic in reading
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
is slightly flawed.
If is
applies then ==
will be True, but it does NOT apply in reverse. ==
may yield True while is
yields False.