To remove the variable from the current environment (not permanently):
set FOOBAR=
To permanently remove the variable from the user environment (which is the default place setx
puts it):
REG delete HKCU\Environment /F /V FOOBAR
If the variable is set in the system environment (e.g. if you originally set it with setx /M
), as an administrator run:
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
Note: The REG
commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.
The -nc
, --no-clobber
option isn't the best solution as newer files will not be downloaded. One should use -N
instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:
wget -N http://www.example.com/images/misc/pic.png
Then running Wget with -N, with or without
-r
or-p
, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file.-nc
may not be specified at the same time as-N
.
-N
,--timestamping
: Turn on time-stamping.
For those who prefer using the Task Scheduler, it's possible to schedule a task to run after a restart / shutdown has been initiated by setting the task to run after event 1074 in the System log in the Event Viewer has been logged. However, it's only good for very short task, which will run as long as the system is restarting / shutting down, which is usually only a few seconds.
Begin the task: On an event
Log: System
Source: USER32
EventID: 1074
schtasks /create /tn "taskname" /tr "task file" /sc onevent /ec system /mo *[system/eventid=1074]
Comment: the /ec option is available from Windows Vista and above. (thank you @t2d)
Please note that the task status can be:
The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist. (0x800704DD)
However, it doesn't mean that it didn't run.
If you want to select the same item in a listbox
using a listview
, you can use:
Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
For aa As Integer = 0 To ListView1.SelectedItems.Count - 1
ListBox1.SelectedIndex = ListView1.SelectedIndices(aa)
Next
End Sub
Or you could do:
var myDouble = Double((mySwiftString.text as NSString).doubleValue)
Stopping Skype from using port 80: http://forum.skype.com/lofiversion/index.php/t15582.html
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
from datetime import datetime
date_today = datetime.now()
month_first_day = date_today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
print(month_first_day)
Use ANSI escape sequences. This article goes into some detail about them. You can use them with printf
as well.
Try inheriting from ConfigurationSection. This blog post by Phil Haack has an example.
Confirmed, per the documentation for IConfigurationSectionHandler:
In .NET Framework version 2.0 and above, you must instead derive from the ConfigurationSection class to implement the related configuration section handler.
You can use the IF
statement in a new cell to replace text, such as:
=IF(A4="C", "Other", A4)
This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.
EDIT
Assuming that the Employee_Count
values are in B1-B10, you can use this:
=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)
This function doesn't even require the data to be sorted; the LARGE
function will find the 10th largest number in the series, and then the rest of the formula will compare against that.
I also had same problem then I found this on there documentation page
So if you want to create a project by name of test_laravel
in directory /Applications/MAMP/htdocs/
then what you need to do is
go to your project parent directory
cd /Applications/MAMP/htdocs
and fire this command
composer create-project laravel/laravel test_laravel --prefer-dist
that's it, this is really easy and it also creates Application Key automatically for you
If you are trying to do redirect in beforeAction() you should use send() method
return $this->redirect('/some/url',302)->send();
Promise.all
is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error.
Some libraries have something called Promise.when
, which I understand would instead wait for all promises in the array to either resolve or reject, but I'm not familiar with it, and it's not in ES6.
Your code
I agree with others here that your fix should work. It should resolve with an array that may contain a mix of successful values and errors objects. It's unusual to pass error objects in the success-path but assuming your code is expecting them, I see no problem with it.
The only reason I can think of why it would "not resolve" is that it's failing in code you're not showing us and the reason you're not seeing any error message about this is because this promise chain is not terminated with a final catch (as far as what you're showing us anyway).
I've taken the liberty of factoring out the "existing chain" from your example and terminating the chain with a catch. This may not be right for you, but for people reading this, it's important to always either return or terminate chains, or potential errors, even coding errors, will get hidden (which is what I suspect happened here):
Promise.all(state.routes.map(function(route) {
return route.handler.promiseHandler().catch(function(err) {
return err;
});
}))
.then(function(arrayOfValuesOrErrors) {
// handling of my array containing values and/or errors.
})
.catch(function(err) {
console.log(err.message); // some coding error in handling happened
});
They are the same thing, aren't they?
No, they aren't.
I think the first sentence of the Wikipedia page you referenced gives a nice, brief summary:
UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
To elaborate:
Unicode is a standard, which defines a map from characters to numbers, the so-called code points, (like in the example below). For the full mapping, you can have a look here.
! -> U+0021 (21),
" -> U+0022 (22),
\# -> U+0023 (23)
UTF-8 is one of the ways to encode these code points in a form a computer can understand, aka bits. In other words, it's a way/algorithm to convert each of those code points to a sequence of bits or convert a sequence of bits to the equivalent code points. Note that there are a lot of alternative encodings for Unicode.
Joel gives a really nice explanation and an overview of the history here.
Yes, it's built in to jQuery. See the docs at jquery documentation.
ajaxError may be what you want.
This is a late answer, but this question appears highly on search results so it's worth answering properly.
Basically, you shouldn't be trying to make a div clickable, but rather make an anchor div-like by giving the <a>
tag a display: block
CSS attribute.
That way, your HTML remains semantically valid and you can inherit the typical browser behaviours for hyperlinks. It also works even if javascript is disabled / js resources don't load.
I deleted the node_modules folder and run npm install
and my application started without any errors.
you can add the following code : the ckeditor field data will be stored in $('#ELEMENT_ID').val() via each click. I've used the method and it works very well. ckeditor field data will be saved realtime and will be ready for sending.
$().click(function(){
$('#ELEMENT_ID').val(CKEDITOR.instances['ELEMENT_ID'].getData());
});
$sidemenu
is not an object
, so you can't call methods on it. It is probably not being sent to your view
, or $sidemenus
is empty.
You either need to keep creating new objects, or clone the existing one. See What is the most efficient way to deep clone an object in JavaScript? for how to clone.
For me, I encountered this error many times,
Error inflating class android.support.design.widget.NavigationView #28 and #29
The solution that works for me is that you must match your support design library and your support appcompat library.
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
For me they must match. :) It works for me!
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
I tried the followings with 3 different executions.
echo $(realpath $_)
. application # /correct/path/to/dir or /path/to/temporary_dir
bash application # /path/to/bash
/PATH/TO/application # /correct/path/to/dir
echo $(realpath $(dirname $0))
. application # failed with `realpath: missing operand`
bash application # /correct/path/to/dir
/PATH/TO/application # /correct/path/to/dir
echo $(realpath $BASH_SOURCE)
$BASH_SOURCE
is basically the same with ${BASH_SOURCE[0]}
.
. application # /correct/path/to/dir
bash application # /correct/path/to/dir
/PATH/TO/application # /correct/path/to/dir
Only $(realpath $BASH_SOURCE)
seems to be reliable.
In short,
Struts is for Front-end development of website
Hibernate is for back-end development of website
Spring is for full stack development of website in which Spring MVC(Model-View-Controller) is for Front-end. ORM, JDBC for Data Access / Integration(backend). etc
in my case i already had the maven dependency to 'spring-boot-starter-web' and the project would start fine without auto-stopping when i run it as springboot app from within the IDE. however, when i deploy it to K8s, the app would start and auto-stop immediately. So i modified my main app class to extend SpringBootServletInitializer and this seems to have fixed the auto-stopping.
@SpringBootApplication public class MyApp extends SpringBootServletInitializer { public static void main(String[] args) {
SpringApplication.run(MyApp.class, args); }}
Button btnDownload = (Button) findViewById(R.id.DownloadView);
Button btnApp = (Button) findViewById(R.id.AppView);
btnDownload.setOnClickListener(handler);
btnApp.setOnClickListener(handler);
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
if(v==btnDownload){
// doStuff
Intent intentMain = new Intent(CurrentActivity.this ,
SecondActivity.class);
CurrentActivity.this.startActivity(intentMain);
Log.i("Content "," Main layout ");
}
if(v==btnApp){
// doStuff
Intent intentApp = new Intent(CurrentActivity.this,
ThirdActivity.class);
CurrentActivity.this.startActivity(intentApp);
Log.i("Content "," App layout ");
}
}
};
Note : and then you should declare all your activities in the manifest .xml file like this :
<activity android:name=".SecondActivity" ></activity>
<activity android:name=".ThirdActivity" ></activity>
EDIT : update this part of Code :) :
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);// Add THIS LINE
setContentView(R.layout.app);
TextView tv = (TextView) this.findViewById(R.id.thetext);
tv.setText("App View yo!?\n");
}
NB : check this (Broken link) Tutorial About How To Switch Between Activities.
Diogo
Justin has given you some very fine tips :)
You will also get that error if the cell where you are performing the calculation has an error resulting from a formula.
For example if Cell A1 has #DIV/0! error then you will get "Excel VBA Run-time error '13' Type mismatch" when performing this code
Sheets("Sheet1").Range("A1").Value - 1
I have made some slight changes to your code. Could you please test it for me? Copy the code with the line numbers as I have deliberately put them there.
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim x As Integer, i As Integer, a As Integer, y As Integer
Dim name As String
Dim lastRow As Long
10 On Error GoTo Whoa
20 Application.ScreenUpdating = False
30 name = InputBox("Please insert the name of the sheet")
40 If Len(Trim(name)) = 0 Then Exit Sub
50 Set ws = Sheets(name)
60 With ws
70 If Not IsError(.Range("BE4").Value) Then
80 x = Val(.Range("BE4").Value)
90 Else
100 MsgBox "Please check the value of cell BE4. It seems to have an error"
110 GoTo LetsContinue
120 End If
130 .Range("BF4").Value = x
140 lastRow = .Range("BE" & Rows.Count).End(xlUp).Row
150 For i = 5 To lastRow
160 If IsError(.Range("BE" & i)) Then
170 MsgBox "Please check the value of cell BE" & i & ". It seems to have an error"
180 GoTo LetsContinue
190 End If
200 a = 0: y = Val(.Range("BE" & i))
210 If y <> x Then
220 If y <> 0 Then
230 If y = 3 Then
240 a = x
250 .Range("BF" & i) = Val(.Range("BE" & i)) - x
260 x = Val(.Range("BE" & i)) - x
270 End If
280 .Range("BF" & i) = Val(.Range("BE" & i)) - a
290 x = Val(.Range("BE" & i)) - a
300 Else
310 .Range("BF" & i).ClearContents
320 End If
330 Else
340 .Range("BF" & i).ClearContents
350 End If
360 Next i
370 End With
LetsContinue:
380 Application.ScreenUpdating = True
390 Exit Sub
Whoa:
400 MsgBox "Error Description :" & Err.Description & vbNewLine & _
"Error at line : " & Erl
410 Resume LetsContinue
End Sub
to select records for the last 7 days
WHERE Created_Date >= DATEADD(day, -7, GETDATE())
to select records for the current week
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM
WHERE CreatedDate >= DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))
AND CreatedDate < DATEADD(day, 8 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))
if you want to select records for last week instead of the last 7 days
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM
WHERE CreatedDate >= DATEADD(day, -(DATEPART(dw, GETDATE()) + 6), CONVERT(DATE, GETDATE()))
AND CreatedDate < DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))
In a very general sense:
UPDATE MyTable
SET MyNullValue = MyDate
WHERE MyNullValue IS NULL
Put whatever you want to send to PHP in the value
attribute.
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<option value="--Any--">--Any--</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
</select>
You can also omit the value
attribute. It defaults to using the text.
If you don't want to change the HTML, you can put an array in your PHP to translate the values:
$makes = array(2 => 'Toyota',
3 => 'Nissan');
$maker = $makes[$_POST['Make']];
As everyone else has pointed out, this can work:
<a href="newsletter_01.pdf" target="_blank">Read more</a>
But what nobody has pointed out is that it's not guaranteed to work.
There is no way to force a user's browser to open a PDF file in a new tab. Depending on the user's browser settings, even with target="_blank"
the browser may react the following ways:
Take a look at Firefox's settings, for example:
Chrome has a similar setting:
If the user has chosen to "Save File" in their browsers settings when encountering a PDF, there is no way you can override it.
For Python3 it is required to use BytesIO:
from io import BytesIO
from PIL import Image, ImageDraw
image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")
byte_io = BytesIO()
image.save(byte_io, 'PNG')
Read more: http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image
enum
are pretty powerful in Java. You could easily add a contains
method to your enum (as you would add a method to a class):
enum choices {
a1, a2, b1, b2;
public boolean contains(String s)
{
if (s.equals("a1") || s.equals("a2") || s.equals("b1") || s.equals("b2"))
return true;
return false;
}
};
From this answer:
[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
var content = request.Content;
string jsonContent = content.ReadAsStringAsync().Result;
}
Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
It could be that your default format doesn't match the file extension. You should specify the file format along with the filename, making sure the format matches the extension:
With someWorkbook
.SaveAs "C:\someDirector\Awesome.xlsm", fileformat:=xlOpenXMLWorkbookMacroEnabled
End With
OTOH, I don't see an extension on your .SaveAs filename. Maybe you need to supply one when doing this programmatically. That makes sense--not having to supply an extension from the GUI interface is convenient, but we programmers are expected to write unambiguous code. I suggest adding the extension and the matching format. See this msdn page for a list of file formats. To be honest, I don't recognize a lot o the descripions.
xlExcel8 = 56 is the .xls format
xlExcel12 = 50 is the .xlsb format
xlOpenXMLWorkbook = 51 is the .xlsx format
xlOpenXMLWorkbookMacroEnabled = 52 is the .xlsm format
xlWorkbookDefault is also listed with a value of 51, which puzzles me since I thought the default format could be changed.
Bootstrap 4.0
*:focus
{
box-shadow: none !important;
border: solid 1px red( any color ) !important;
}
In ASP.NET Core MVC the solution is to add a using
in _ViewImports.cshtml, instead of putting it web.config in the View folder when working with ASP.NET MVC 5.
_ViewImports.cshtml
@using mySolution
@using mySolution.ViewModels // <-- Add this, and place your ViewModel (e.g. LoginViewModel) in here.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
View
@model LoginViewModel // Add to _ViewImports to make this line work
<div>This is the View for the login screen.</div>
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
what platform are you running?..
if its unix, maybe adding
alias java='java -Xmx1g'
to .bashrc (or similar) work
edit: Changing XmX to Xmx
In my experience the flow is:
Font myFont = new Font("Serif", Font.BOLD, 12);
, then use a setFont method on your components like
JButton b = new JButton("Hello World");
b.setFont(myFont);
Use pointer-events CSS style. (as Jason MacDonald suggested)
See MDN https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events. Its supported in most browsers.
Simple adding "disabled" attribute to anchor will do the job if you have global CSS rule like following:
a[disabled], a[disabled]:hover {
pointer-events: none;
color: #e1e1e1;
}
bootstrap provides various classes for table
<table class="table"></table>
<table class="table table-bordered"></table>
<table class="table table-hover"></table>
<table class="table table-condensed"></table>
<table class="table table-responsive"></table>
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
See the MDN section on Promises. In particular, look at the return type of then().
To log in, the user-agent has to submit a request to the server and wait to receive a response. Since making your application totally stop execution during a request round-trip usually makes for a bad user experience, practically every JS function that logs you in (or performs any other form of server interaction) will use a Promise, or something very much like it, to deliver results asynchronously.
Now, also notice that return
statements are always evaluated in the context of the function they appear in. So when you wrote:
let AuthUser = data => {
return google
.login(data.username, data.password)
.then( token => {
return token;
});
};
the statement return token;
meant that the anonymous function being passed into then()
should return the token, not that the AuthUser
function should. What AuthUser
returns is the result of calling google.login(username, password).then(callback);
, which happens to be a Promise.
Ultimately your callback token => { return token; }
does nothing; instead, your input to then()
needs to be a function that actually handles the token in some way.
HTML code
<div ng-app>
<div ng-controller='ctrl'>
<div ng-class='whatClassIsIt(call.state[0])'>{{call.state[0]}}</div>
<div ng-class='whatClassIsIt(call.state[1])'>{{call.state[1]}}</div>
<div ng-class='whatClassIsIt(call.state[2])'>{{call.state[2]}}</div>
<div ng-class='whatClassIsIt(call.state[3])'>{{call.state[3]}}</div>
<div ng-class='whatClassIsIt(call.state[4])'>{{call.state[4]}}</div>
<div ng-class='whatClassIsIt(call.state[5])'>{{call.state[5]}}</div>
<div ng-class='whatClassIsIt(call.state[6])'>{{call.state[6]}}</div>
<div ng-class='whatClassIsIt(call.state[7])'>{{call.state[7]}}</div>
</div>
JavaScript Code
function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}
$scope.whatClassIsIt= function(someValue){
if(someValue=="first")
return "ClassA"
else if(someValue=="second")
return "ClassB";
else
return "ClassC";
}
}
"Employed Russian" is among the best answer, and I think all other suggested answer may not work. The reason is simply because when an application is first created, all its the APIs it needs are resolved at compile time. Using "ldd" u can see all the statically linked dependencies:
ldd /usr/lib/firefox/firefox
linux-vdso.so.1 => (0x00007ffd5c5f0000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f727e708000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f727e500000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f727e1f8000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f727def0000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f727db28000)
/lib64/ld-linux-x86-64.so.2 (0x00007f727eb78000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f727d910000)
But at runtime, firefox will also load many other dynamic libraries, eg (for firefox) there are many "glib"-labelled libraries loaded (even though statically linked there are none):
/usr/lib/x86_64-linux-gnu/libdbus-glib-1.so.2.2.2
/lib/x86_64-linux-gnu/libglib-2.0.so.0.4002.0
/usr/lib/x86_64-linux-gnu/libavahi-glib.so.1.0.2
Manytimes, you can see names of one version being soft-linked into another version. Eg:
lrwxrwxrwx 1 root root 23 Dec 21 2014 libdbus-glib-1.so.2 -> libdbus-glib-1.so.2.2.2
-rw-r--r-- 1 root root 160832 Mar 1 2013 libdbus-glib-1.so.2.2.2
This therefore means different version of "libraries" exists in one system - which is not a problem as it is the same file, and it will provide compatibilities when applications have multiple versions dependencies.
Therefore, at the system level, all the libraries are almost interdependent on one another, and just changing the libraries loading priority via manipulating LD_PRELOAD or LD_LIBRARY_PATH will not help - even it can load, runtime it may still crash.
http://lightofdawn.org/wiki/wiki.cgi/-wiki/NewAppsOnOldGlibc
Best alternative is chroot (mentioned by ER briefly): but for this you will need to recreate the entire environment in which is the original binary execute - usually starting from /lib, /usr/lib/, /usr/lib/x86 etc. You can either use "Buildroot", or YoctoProject, or just tar from an existing Distro environment. (like Fedora/Suse etc).
If you want to reduce the size to decimal(7,2) from decimal(9,2) you will have to account for the existing data with values greater to fit into decimal(7,2). Either you will have to delete those numbers are truncate it down to fit into your new size. If there was no data for the field you are trying to update it will do it automatically without issues
I've created a new class to handle binding RadioButtons and CheckBoxes to enums. It works for flagged enums (with multiple checkbox selections) and non-flagged enums for single-selection checkboxes or radio buttons. It also requires no ValueConverters at all.
This might look more complicated at first, however, once you copy this class into your project, it's done. It's generic so it can easily be reused for any enum.
public class EnumSelection<T> : INotifyPropertyChanged where T : struct, IComparable, IFormattable, IConvertible
{
private T value; // stored value of the Enum
private bool isFlagged; // Enum uses flags?
private bool canDeselect; // Can be deselected? (Radio buttons cannot deselect, checkboxes can)
private T blankValue; // what is considered the "blank" value if it can be deselected?
public EnumSelection(T value) : this(value, false, default(T)) { }
public EnumSelection(T value, bool canDeselect) : this(value, canDeselect, default(T)) { }
public EnumSelection(T value, T blankValue) : this(value, true, blankValue) { }
public EnumSelection(T value, bool canDeselect, T blankValue)
{
if (!typeof(T).IsEnum) throw new ArgumentException($"{nameof(T)} must be an enum type"); // I really wish there was a way to constrain generic types to enums...
isFlagged = typeof(T).IsDefined(typeof(FlagsAttribute), false);
this.value = value;
this.canDeselect = canDeselect;
this.blankValue = blankValue;
}
public T Value
{
get { return value; }
set
{
if (this.value.Equals(value)) return;
this.value = value;
OnPropertyChanged();
OnPropertyChanged("Item[]"); // Notify that the indexer property has changed
}
}
[IndexerName("Item")]
public bool this[T key]
{
get
{
int iKey = (int)(object)key;
return isFlagged ? ((int)(object)value & iKey) == iKey : value.Equals(key);
}
set
{
if (isFlagged)
{
int iValue = (int)(object)this.value;
int iKey = (int)(object)key;
if (((iValue & iKey) == iKey) == value) return;
if (value)
Value = (T)(object)(iValue | iKey);
else
Value = (T)(object)(iValue & ~iKey);
}
else
{
if (this.value.Equals(key) == value) return;
if (!value && !canDeselect) return;
Value = value ? key : blankValue;
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And for how to use it, let's say you have an enum for running a task manually or automatically, and can be scheduled for any days of the week, and some optional options...
public enum StartTask
{
Manual,
Automatic
}
[Flags()]
public enum DayOfWeek
{
Sunday = 1 << 0,
Monday = 1 << 1,
Tuesday = 1 << 2,
Wednesday = 1 << 3,
Thursday = 1 << 4,
Friday = 1 << 5,
Saturday = 1 << 6
}
public enum AdditionalOptions
{
None = 0,
OptionA,
OptionB
}
Now, here's how easy it is to use this class:
public class MyViewModel : ViewModelBase
{
public MyViewModel()
{
StartUp = new EnumSelection<StartTask>(StartTask.Manual);
Days = new EnumSelection<DayOfWeek>(default(DayOfWeek));
Options = new EnumSelection<AdditionalOptions>(AdditionalOptions.None, true, AdditionalOptions.None);
}
public EnumSelection<StartTask> StartUp { get; private set; }
public EnumSelection<DayOfWeek> Days { get; private set; }
public EnumSelection<AdditionalOptions> Options { get; private set; }
}
And here's how easy it is to bind checkboxes and radio buttons with this class:
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<!-- Using RadioButtons for exactly 1 selection behavior -->
<RadioButton IsChecked="{Binding StartUp[Manual]}">Manual</RadioButton>
<RadioButton IsChecked="{Binding StartUp[Automatic]}">Automatic</RadioButton>
</StackPanel>
<StackPanel Orientation="Horizontal">
<!-- Using CheckBoxes for 0 or Many selection behavior -->
<CheckBox IsChecked="{Binding Days[Sunday]}">Sunday</CheckBox>
<CheckBox IsChecked="{Binding Days[Monday]}">Monday</CheckBox>
<CheckBox IsChecked="{Binding Days[Tuesday]}">Tuesday</CheckBox>
<CheckBox IsChecked="{Binding Days[Wednesday]}">Wednesday</CheckBox>
<CheckBox IsChecked="{Binding Days[Thursday]}">Thursday</CheckBox>
<CheckBox IsChecked="{Binding Days[Friday]}">Friday</CheckBox>
<CheckBox IsChecked="{Binding Days[Saturday]}">Saturday</CheckBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<!-- Using CheckBoxes for 0 or 1 selection behavior -->
<CheckBox IsChecked="{Binding Options[OptionA]}">Option A</CheckBox>
<CheckBox IsChecked="{Binding Options[OptionB]}">Option B</CheckBox>
</StackPanel>
</StackPanel>
SQL Compare by RedGate http://www.red-gate.com/products/SQL_Compare/index.htm
DBDeploy to help with database change management in an automated fashion http://dbdeploy.com/
<div class="container-fluid login-container">
<div class="row">
<form (ngSubmit)="login('da')">
<div class="col-md-4">
<div class="login-text">
Login
</div>
<div class="form-signin">
<input type="text" class="form-control" placeholder="Email" required>
<input type="password" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="col-md-4">
<div class="login-go-div">
<input type="image" src="../../../assets/images/svg/login-go-initial.svg" class="login-go"
onmouseover="this.src='../../../assets/images/svg/login-go.svg'"
onmouseout="this.src='../../../assets/images/svg/login-go-initial.svg'"/>
</div>
</div>
</form>
</div>
</div>
This is the working code for it.
To resolve this error:
ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name
Just run this PL/SQL
command for extended tablespace size automatically on-demand:
alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;
I get this error in import big dump file, just run this command without stopping import routine or restarting the database.
Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.
More info: alter_autoextend_on
I created a small application which had similar functionality
MainActivity
public class MyActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.open,
R.string.close
)
{
public void onDrawerClosed(View view)
{
super.onDrawerClosed(view);
invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
syncState();
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//Set the custom toolbar
if (toolbar != null){
setSupportActionBar(toolbar);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
actionBarDrawerToggle.syncState();
}
}
My XML of that Activity
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity"
android:id="@+id/drawer"
>
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/toolbar_custom"/>
</FrameLayout>
<!-- The navigation drawer -->
<ListView
android:layout_marginTop="?attr/actionBarSize"
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#457C50"/>
</android.support.v4.widget.DrawerLayout>
My Custom Toolbar XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toolbar"
android:background="?attr/colorPrimaryDark">
<TextView android:text="U titel"
android:textAppearance="@android:style/TextAppearance.Theme"
android:textColor="@android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</android.support.v7.widget.Toolbar>
My Theme Style
<resources>
<style name="AppTheme" parent="Base.Theme.AppCompat"/>
<style name="AppTheme.Base" parent="Theme.AppCompat">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primaryDarker</item>
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">@android:color/white</item>
</style>
<color name="primary">#457C50</color>
<color name="primaryDarker">#580C0C</color>
</resources>
My Styles in values-v21
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="AppTheme.Base">
<item name="android:windowContentTransitions">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
<item name="android:windowSharedElementExitTransition">@android:transition/move</item>
</style>
</resources>
I also faced this ? issue. Meanwhile I ran into three cases where it happened:
substr()
I was using substr()
on a UTF8 string which cut UTF8 characters, thus the cut chars could not be displayed correctly. Use mb_substr($utfstring, 0, 10, 'utf-8');
instead. Credits
htmlspecialchars()
Another problem was using htmlspecialchars()
on a UTF8 string. The fix is to use: htmlspecialchars($utfstring, ENT_QUOTES, 'UTF-8');
preg_replace()
Lastly I found out that preg_replace()
can lead to problems with UTF. The code $string = preg_replace('/[^A-Za-z0-9ÄäÜüÖöß]/', ' ', $string);
for example transformed the UTF string "F(×)=2×-3" into "F ? 2? ". The fix is to use mb_ereg_replace()
instead.
I hope this additional information will help to get rid of such problems.
To detect run:
select @@sql_mode
-- It will give something like:
-- STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
To fix, run:
set global sql_mode = ''
No need for regex. os.path.splitext
is your friend:
os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')
You might want to start with an introduction to version control. This guide is specific to subversion, but the core concepts can be applied to most version control systems. After you have the basics, you can delve into the git guide.
In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.
The lesson learned is "always use homogeneous development and deployment databases!"
use IDENTITY(1,1)
while creating the table
eg
CREATE TABLE SAMPLE(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Status] [smallint] NOT NULL,
CONSTRAINT [PK_SAMPLE] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
)
This works on GitHub:
[](Comment text goes here)
The resulting HTML looks like:
<a href="Comment%20text%20goes%20here"></a>
Which is basically an empty link. Obviously you can read that in the source of the rendered text, but you can do that on GitHub anyway.
To grant a permission:
grant select on schema_name.sequence_name to user_or_role_name;
To check which permissions have been granted
select * from all_tab_privs where TABLE_NAME = 'sequence_name'
Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:
Some code that would serve you specifically as well:
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
console.log pix[i+3]
}
This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.
Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:
$('el').click(function(e){
console.log(e.clientX, e.clientY)
}
Those should grab your x and y values.
I was also looking for the relative path version, this works OK. Note when run (Spyder 3.6) you will see (unicode error) 'unicodeescape' codec can't decode bytes at the closing triple quote. Remove the offending comment lines 14 and 15 and adjust the file names and location for your environment and check for indentation.
""" Created on Fri Jan 24 12:12:40 2020
Source: Read a .csv into pandas from F: drive on Windows 7
Demonstrates: Load a csv not in the CWD by specifying relative path - windows version
@author: Doug
From CWD C:\Users\Doug\.spyder-py3\Data Camp\pandas
we will load file
C:/Users/Doug/.spyder-py3/Data Camp/Cleaning/g1803.csv
"""
import csv
trainData2 = []
with open(r'../Cleaning/g1803.csv', 'r') as train2Csv:
trainReader2 = csv.reader(train2Csv, delimiter=',', quotechar='"')
for row in trainReader2:
trainData2.append(row)
print(trainData2)
To convert a string with comma separated values to a string array use Split
:
string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');
Result will be a string array with four strings:
{"One","Two","Three","Four"}
Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1
in order to call the method:
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
var theType = DLL.GetType("DLL.Class1");
var c = Activator.CreateInstance(theType);
var method = theType.GetMethod("Output");
method.Invoke(c, new object[]{@"Hello"});
Console.ReadLine();
}
}
Convert PPK to OpenSSh
OS X: Install Homebrew, then run
brew install putty
Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search
To generate the private key:
cd ~
puttygen id_dsa.ppk -O private-openssh -o id_dsa
and to generate the public key:
puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub
Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:
mkdir -p ~/.ssh
mv -i ~/id_dsa* ~/.ssh
chmod 600 ~/.ssh/id_dsa
chmod 666 ~/.ssh/id_dsa.pub
connect with ssh server
ssh -i ~/.ssh/id_dsa username@servername
Port Forwarding to connect mysql remote server
ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName
Encountered the same problem. I was doing something like:
connect 'jdbc:derby://localhost:1527/~/databases/db1'
Replacing the path with the absolute path fixed this problem:
connect 'jdbc:derby://localhost:1527//Users/ayush99/databases/db1'
.
In summary: Avoid using ~
or any such variables in the path of existing database.
You've got a problem with this line:
while file_to_read != " ":
This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.
Listen to everyone else's advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.
There is a new spec called the Native File System API that allows you to do this properly like this:
const result = await window.chooseFileSystemEntries({ type: "save-file" });
There is a demo here, but I believe it is using an origin trial so it may not work in your own website unless you sign up or enable a config flag, and it obviously only works in Chrome. If you're making an Electron app this might be an option though.
From the site i found out the following things:
SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record March 25, 2007 by pinaldave
SELECT @@IDENTITY It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. @@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.
SELECT SCOPE_IDENTITY() It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.
SELECT IDENT_CURRENT(‘tablename’) It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
There are a couple ways to do this.
First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:
E:\> openssl x509 -pubkey -noout -in cert.pem > pubkey.pem
If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.
openssl> x509 -pubkey -noout -in cert.pem
Output will look something like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----
It turns out that because of a peculiar mixture of javascript frameworks that I needed to initiate the script using an event listener provide by one of the other frameworks.
Lattice solution with additional settings which I needed:
library(lattice)
distribution<-function(x) {2^(-x*2)}
X<-seq(0,10,0.00001)
xyplot(distribution(X)~X,type="l", col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255), cex.lab = 3.5, cex.axis = 3.5, lwd=2 )
X<-seq(0,10,0.00001)
col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255)
lwd = 2
cex.lab = 3.5, cex.axis = 3.5
You can delete all breakpoints using
del <start_breakpoint_num> - <end_breakpoint_num>
To view the start_breakpoint_num and end_breakpoint_num use:
info break
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
You can embed case insensitity into the regular expression like so:
\.(?i:)(?:jpg|gif|doc|pdf)$
try this code, it has already a smooth animation when clicked the link.
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top - 100
}, 500);
});
It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.
But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.
To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.
I did have the same problem and at first I added:
<activity
android:name="com.companyname.applicationname"
android:windowSoftInputMode="adjustPan">
to my manifest file. But this alone did not solve the issue. Then as mentioned by Artem Russakovskii, I added:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:isScrollContainer="false">
</ScrollView>
in the scrollview.
This is what worked for me.
SQL Server allows the following (be careful to use single quotes instead of double)
UPDATE User
SET UserId = 12345
, Name = 'J Doe'
, Location = 'USA'
, Bio='my bio
spans
multiple
lines!'
WHERE UserId = 12345
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
if (attributes[i] is DomainNameAttribute)
{
System.Console.WriteLine(((DomainNameAttribute) attributes[i]).Name);
}
}
I typically use triggers to handle timestamps but I think this may work.
$data = array(
'name' => $name,
'email' => $email
);
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
This is the example of dynamic Form controls generated from server.
https://stackblitz.com/edit/angular-t3mmg6
This example is dynamic Form controls is in add component (This is where you can get the Formcontrols from the server). If you see addcomponent method you can see the Forms Controls. In this example I am not using angular material,but It works (I am using @ work). This is target to angular 6, but works in all previous version.
Need to add JITComplierFactory for AngularVersion 5 and above.
Thanks
Vijay
lateinit vs lazy
lateinit
i) Use it with mutable variable[var]
lateinit var name: String //Allowed
lateinit val name: String //Not Allowed
ii) Allowed with only non-nullable data types
lateinit var name: String //Allowed
lateinit var name: String? //Not Allowed
iii) It is a promise to compiler that the value will be initialized in future.
NOTE: If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.
lazy
i) Lazy initialization was designed to prevent unnecessary initialization of objects.
ii) Your variable will not be initialized unless you use it.
iii) It is initialized only once. Next time when you use it, you get the value from cache memory.
iv) It is thread safe(It is initialized in the thread where it is used for the first time. Other threads use the same value stored in the cache).
v) The variable can only be val.
vi) The variable can only be non-nullable.
If you want to make a 'title' cell that spans all columns, as header for your table, you may want to use the caption tag (http://www.w3schools.com/tags/tag_caption.asp / https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) This element is meant for this purpose. It behaves like a div, but doesn't span the entire width of the parent of the table (like a div would do in the same position (don't try this at home!)), instead, it spans the width of the table. There are some cross-browser issues with borders and such (was acceptable for me). Anyways, you can make it look as a cell that spans all columns. Within, you can make rows by adding div-elements. I'm not sure if you can insert it in between tr-elements, but that would be a hack I guess (so not recommended). Another option would be messing around with floating divs, but that is yuck!
Do
<table>
<caption style="gimme some style!"><!-- Title of table --></caption>
<thead><!-- ... --></thead>
<tbody><!-- ... --></tbody>
</table>
Don't
<div>
<div style="float: left;/* extra styling /*"><!-- Title of table --></div>
<table>
<thead><!-- ... --></thead>
<tbody><!-- ... --></tbody>
</table>
<div style="clear: both"></div>
</div>
this works for me:
table {
border-collapse: collapse;
border-style: hidden;
}
table td, table th {
border: 1px solid black;
}
tested in FF 3.6 and Chromium 5.0, IE lacks support; from W3C:
Borders with the 'border-style' of 'hidden' take precedence over all other conflicting borders. Any border with this value suppresses all borders at this location.
Considering lolesque's comment to best answer you can add either an attribute or a class to show/hide elements with display properties that differs from what it normally has, if your site needs backwards compatibility I would suggest making a class and adding/removing it to show/display the element
.news-show {
display:inline-block;
}
.news-hide {
display:none;
}
Replace inline-block with your preferred display method of your choice and use jquerys addclass https://api.jquery.com/addclass/ and removeclass https://api.jquery.com/removeclass/ instead of show/hide, if backwards compatibility is no problem you can use attributes like this.
.news[data-news-visible=show] {
display:inline-block;
}
.news[data-news-visible=hide] {
display:none;
}
And use jquerys attr() http://api.jquery.com/attr/ to show and hide the element.
Whichever method you prefer it makes you able to easily implement css3 animations when showing/hiding elements this way
Not possible in IE, as the UI Zoom button in the status bar is not scriptable. YMMV for other browsers.
I ended on this:
function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}
array_multisort($sortarray, SORT_ASC, $array);
}
Just call the function, passing the array and the name of the field of the second level array. Like:
sort_array_of_array($inventory, 'price');
Here's an example of how you could implement a list view:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//We have our list view
final ListView dynamic = findViewById(R.id.dynamic);
//Create an array of elements
final ArrayList<String> classes = new ArrayList<>();
classes.add("Data Structures");
classes.add("Assembly Language");
classes.add("Calculus 3");
classes.add("Switching Systems");
classes.add("Analysis Tools");
//Create adapter for ArrayList
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, classes);
//Insert Adapter into List
dynamic.setAdapter(adapter);
//set click functionality for each list item
dynamic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("User clicked ", classes.get(position));
}
});
}
You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
function printResult() {
var DocumentContainer = document.getElementById('your_div_id');
var WindowObject = window.open('', "PrintWindow", "width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
For Java users
write this line above your setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
For kotlin users
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
Very Late Answer but I will highlight some point as I had to deal with it years ago setting up my IIS site across network
168.192.x.x
or via http://his-pc-name
(do not forget the http part)Make sure your IIS is working fine on remote machine by checking localhost
which should served the default site. Also make sure your firewall is configured to allow connection via port 80 or you can just disable firewall for the time being for testing purposes.
Refering to the very first question, I am looking into the same. The result I get, recording a macro, is, starting by selecting cell A76:
Sub find_last_row()
Range("A76").Select
Range(Selection, Selection.End(xlDown)).Select
End Sub
Static method is inherited in subclass but it is not polymorphism. When you writing the implementation of static method, the parent's class method is over hidden, not overridden. Think, if it is not inherited then how you can be able to access without classname.staticMethodname();
?
I personally would just use the JavaScript code to switch between 2 classes.
Have the CSS outline everything you need on your div MINUS the background rule, then add two classes (e.g: expanded & collapsed) as rules each with the correct background image (or background position if using a sprite).
CSS with different images
.div {
/* button size etc properties */
}
.expanded {background: url(img/x.gif) no-repeat left top;}
.collapsed {background: url(img/y.gif) no-repeat left top;}
Or CSS with image sprite
.div {
background: url(img/sprite.gif) no-repeat left top;
/* Other styles */
}
.expanded {background-position: left bottom;}
Then...
JavaScript code with images
$(function){
$('#button').click(function(){
if($(this).hasClass('expanded'))
{
$(this).addClass('collapsed').removeClass('expanded');
}
else
{
$(this).addClass('expanded').removeClass('collapsed');
}
});
}
JavaScript with sprite
Note: the elegant toggleClass does not work in Internet Explorer 6, but the below addClass
/removeClass
method will work fine in this situation as well
The most elegant solution (unfortunately not Internet Explorer 6 friendly)
$(function){
$('#button').click(function(){
$(this).toggleClass('expanded');
});
}
$(function){
$('#button').click(function(){
if($(this).hasClass('expanded'))
{
$(this).removeClass('expanded');
}
else
{
$(this).addClass('expanded');
}
});
}
As far as I know this method will work accross browsers, and I would feel much more comfortable playing with CSS and classes than with URL changes in the script.
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
Format specifier in printf
should be %f
for doubl
datatypes since float
datatyles eventually convert to double
datatypes inside printf
.
There is no provision to print float
data. Please find the discussion here : Correct format specifier for double in printf
Yes !!!! If I say Encapsulation is a kind of an advanced specific scope abstraction,
How many of you read/upvote my answer. Let's dig in why I am saying like this.
I need to clear two things before my claiming.
One is data hiding and, another one is the abstraction
I said, "Encapsulation is a kind of an advanced specific scope abstraction". Why? because we can see encapsulation as data hiding + abstraction
encapsulation = data hiding + abstraction
In encapsulation, we need to hide the data so outside person can not see the data and we need to provide methods that can be used to access the data. These methods may have validations or other features inside those things also hidden to an outside person. So here, we are hiding the implementation of access methods and it is called abstraction.
This is why I said like above encapsulation is a kind of abstraction.
So Where is the difference?
The difference is the abstraction is a general one if we are hiding something from the user for simplicity, maintainability and security and,
encapsulation is a specific one for which is related to internal states security where we are hiding the internal state (data hiding) and we are providing methods to access the data and those methods implementation also hidden from the outside person(abstraction).
To get the titles for dates greater than a week ago today, use this:
SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7
Try the following code:
ActivityManager activityManager = (ActivityManager) newContext.getSystemService( Context.ACTIVITY_SERVICE );
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for(RunningAppProcessInfo appProcess : appProcesses){
if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
Log.i("Foreground App", appProcess.processName);
}
}
Process name is the package name of the app running in foreground. Compare it to the package name of your application. If it is the same then your application is running on foreground.
I hope this answers your question.
Hey It's very simple see this
@OLD_GUEST_NAME = d.GUEST_NAME from deleted d;
this variable will store your old deleted value and then you can insert it where you want.
for example-
Create trigger testupdate on test for update, delete
as
declare @tableid varchar(50);
declare @testid varchar(50);
declare @newdata varchar(50);
declare @olddata varchar(50);
select @tableid = count(*)+1 from audit_test
select @testid=d.tableid from inserted d;
select @olddata = d.data from deleted d;
select @newdata = i.data from inserted i;
insert into audit_test (tableid, testid, olddata, newdata) values (@tableid, @testid, @olddata, @newdata)
go
It is entirely dependent on how your data is sorted to begin with. If you think it will be pseudo-random then your best bet is to either pick a random selection or choose the middle.
All process for remote login. Remote login is off by default.You need to open it manually for all ip..to give access all ip
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password';
Specific Ip
GRANT ALL PRIVILEGES ON *.* TO 'root'@'your_desire_ip' IDENTIFIED BY 'password';
then
flush privileges;
You can check your User Host & Password
SELECT host,user,authentication_string FROM mysql.user;
Now your duty is to change this
bind-address = 127.0.0.1
You can find this on
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
if you not find this on there then try this
sudo nano /etc/mysql/my.cnf
comment in this
#bind-address = 127.0.0.1
Then restart Mysql
sudo service mysql restart
Now enjoy remote login
find location -ctime time_period
Examples of time_period:
More than 30 days ago: -ctime +30
Less than 30 days ago: -ctime -30
Exactly 30 days ago: -ctime 30
I fixed this problem employing the two procedures of :
In Eclipse->'Project' menu -> 'Java Compiler' -> set 'Compiler compliance level' = 1.6 check on 'Use default compliance settings' Set 'Generated .class compatibility' = 1.6 Set 'Source compatibilty' = 1.6
Then go to 'Windows' menu --> 'Preferences' -->'Java' , expand 'Java' --> 'Compiler' -->Set 'Compiler compliance level' = 1.6
Hint: Source compatibility must be equal to or less than compliance level.
According the MDN custom headers are not exposed by default. The server admin need to expose them using "Access-Control-Expose-Headers" in the same fashion they deal with "access-control-allow-origin"
See this MDN link for confirmation [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers]
Although the accepted answer is correct but if you are just trying to upload your image to cloudinary, there's a better way:
Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap());
Where multipartFile is your org.springframework.web.multipart.MultipartFile.
Depending on what browsers you're targeting, you could go for the object-fit property to solve this:
object-fit: cover;
or maybe fill
is what you're looking for. Still under consideration for IE.
this regex can help you, you should get the first group by \1 or whatever method you have in your language.
href="([^"]*)
example:
<a href="http://www.amghezi.com">amgheziName</a>
result:
http://www.amghezi.com
I see permutation has been suggested. In fact it can be made into one line:
>>> A = np.random.randint(5, size=(10,3))
>>> np.random.permutation(A)[:2]
array([[0, 3, 0],
[3, 1, 2]])
The table normally contains multiple rows. Use a loop and use row.Field<string>(0)
to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection
:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count
to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
The situation you describe is pretty fishy. Whenever you close your program's startup form, the entire application should quit automatically, including closing all other open forms. Make sure that you're closing the correct form, and you should not experience any problems.
The other possibility is that you've changed your project (using its Properties page) not to close until all open windows have been closed. In this mode, your application will not exit until the last remaining open form has been closed. If you've chosen this setting, you have to make sure that you call the Close
method of all forms that you've shown during the course of application, not just the startup/main form.
The first setting is the default for a reason, and if you've changed it, you probably want to go fix it back.
It is by far the most intuitive model for normal applications, and it prevents exactly the situation you describe. For it to work properly, make sure that you have specified your main form as the "Startup form" (rather than a splash screen or log-in form).
The settings I'm talking about are highlighted here:
But primarily, note that you should never have to call Application.Exit
in a properly-designed application. If you find yourself having to do this in order for your program to close completely, then you are doing something wrong. Doing it is not a bad practice in itself, as long as you have a good reason. The other two answers fail to explain that, and thus I feel are incomplete at best.
both option are valid and targeting two different steps of your build:
file(COPY ...
copies the file in configuration step and only in this step. When you rebuild your project without having changed your cmake configuration, this command won't be executed.add_custom_command
is the preferred choice when you want to copy the file around on each build step. The right version for your task would be:
add_custom_command(
TARGET foo POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_SOURCE_DIR}/test/input.txt
${CMAKE_CURRENT_BINARY_DIR}/input.txt)
you can choose between PRE_BUILD
, PRE_LINK
, POST_BUILD
best is you read the documentation of add_custom_command
an example on how to use the first version can be found here: Use CMake add_custom_command to generate source for another target
In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,
default_days = 1000 # How long to certify for
defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:
openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM
Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.
For posterity, your question was how to send an http request to https://stackoverflow.com/questions
. The real answer is: you cannot with telnet, cause this is an https-only reachable url.
So, you might want to use openssl
instead of telnet
, like this for instance
$ openssl s_client -connect stackoverflow.com:443
...
---
GET /questions HTTP/1.1
Host: stackoverflow.com
This will give you the https response.
The best explanation I have found is by Mike Acton, Understanding Strict Aliasing. It's focused a little on PS3 development, but that's basically just GCC.
From the article:
"Strict aliasing is an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias each other.)"
So basically if you have an int*
pointing to some memory containing an int
and then you point a float*
to that memory and use it as a float
you break the rule. If your code does not respect this, then the compiler's optimizer will most likely break your code.
The exception to the rule is a char*
, which is allowed to point to any type.
This is the problem:
while (br.readLine() != null) {
System.out.println(br.readLine());
}
You've got two calls to readLine
- the first only checks that there's a line (but reads it and throws it away) and the second reads the next line. You want:
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Now we're only calling readLine()
once per loop iteration, and using the line that we've read both for the "have we finished?" and "print out the line" parts.
NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.
Updating Visual Studio to 'Update 2' got it working again.
Tools -> Extensions and Updates ->Visual Studio Update 2
As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.
JavaScript is executed in the browser, which is pretty far removed from Eclipse. Eclipse would have to somehow hook into the browser's JavaScript engine to debug it. Therefore there's no built-in debugging of JavaScript via Eclipse, since JS isn't really its main focus anyways.
However, there are plug-ins which you can install to do JavaScript debugging. I believe the main one is the AJAX Toolkit Framework (ATF). It embeds a Mozilla browser in Eclipse in order to do its debugging, so it won't be able to handle cross-browser complications that typically arise when writing JavaScript, but it will certainly help.
Within Crystal, you can do it by creating a formula that uses the ToNumber
function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:
If NumericText ({field}) then ToNumber ({field}) else 0
Alternatively, you might find it easier to convert the field's datatype within the query used in the report.
Solved:
forgot my password
.Sample:
git clone https://<bitbucket_id>@bitbucket.org/<repo>
I think what you want to do is actually pass by reference (pointer) to the function-- create a new environment (which are passed by reference to functions) with the list added to it:
listptr=new.env(parent=globalenv())
listptr$list=mylist
#Then the function is modified as:
lPtrAppend <- function(lstptr, obj) {
lstptr$list[[length(lstptr$list)+1]] <- obj
}
Now you are only modifying the existing list (not creating a new one)
If you have QT and if you are lazy to implement a function and stuff you can use
std::string str;
QString(str).toStdWString()
The efficient way to check if the record exists you must use is_null method to check against the query.
The code below might be helpful:
$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
//user does not exist...
}else{
//user exists...
}
Add produces = "application/json"
in @RequestMapping
In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:
SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])
I spent almost 6 hours before I stumble on the post.
You may use the following function to send a status change:
function header_status($statusCode) {
static $status_codes = null;
if ($status_codes === null) {
$status_codes = array (
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended'
);
}
if ($status_codes[$statusCode] !== null) {
$status_string = $statusCode . ' ' . $status_codes[$statusCode];
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
}
}
You may use it as such:
<?php
header_status(500);
if (that_happened) {
die("that happened")
}
if (something_else_happened) {
die("something else happened")
}
update_database();
header_status(200);
The command I use is:
diff -qr dir1/ dir2/
It is exactly the same as Mark's :) But his answer bothered me as it uses different types of flags, and it made me look twice. Using Mark's more verbose flags it would be:
diff --brief --recursive dir1/ dir2/
I apologise for posting when the other answer is perfectly acceptable. Could not stop myself... working on being less pedantic.
for Mac users, install the Intel HAXM kernel extension to allow the emulator to make use of CPU virtualization extensions.
The steps to configure VM acceleration are as follows:
sdk/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM_version.dmg.
kextstat | grep intel
You should see a status message containing the following extension name, indicating that the kernel extension is loaded:com.intel.kext.intelhaxm
Reference:
https://developer.android.com/studio/run/emulator-acceleration.html#vm-mac
In my opinion it's easiest to work in a 'private browsing session' of chrome, to ensure that your javascript files don't come from the cache.
Hex Color code
#007AFF
and you need this libary https://github.com/thii/SwiftHEXColors
ps. iOS, Swift
Use a Pair
as keys for the HashMap
. JDK has no Pair, but you can either use a 3rd party libraray such as http://commons.apache.org/lang or write a Pair taype of your own.
The warning:
deprecated conversion from string constant to 'char*'
is given because you are doing somewhere (not in the code you posted) something like:
void foo(char* str);
foo("hello");
The problem is that you are trying to convert a string literal (with type const char[]
) to char*
.
You can convert a const char[]
to const char*
because the array decays to the pointer, but what you are doing is making a mutable a constant.
This conversion is probably allowed for C compatibility and just gives you the warning mentioned.
Add namespace
using System.Configuration;
and in place of
ConfigurationSettings.AppSettings
you should use
ConfigurationManager.AppSettings
String path = ConfigurationManager.AppSettings["configFile"];
There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
%u prints unsigned integer
%d prints signed integer
to get a pointer address use %p
Here are the full list of formatting escapes. I am just giving a screen shot from this page
Is the browser supports it, using translate is powerful.
position: absolute;
background-color: red;
width: 70%;
height: 30%;
/* The translate % is relative to the size of the div and not the container*/
/* 21.42% = ( (100%-70%/2) / 0.7 ) */
/* 116.666% = ( (100%-30%/2) / 0.3 ) */
transform: translate3d( 21.42%, 116.666%, 0);
If you are managing the Hibernate session manually, you may want to look into sessionFactory.getCurrentSession() and associated docs here:
http://www.hibernate.org/hib_docs/v3/reference/en/html/architecture-current-session.html
Interesting little problem. It is a bit tricky, since real numbers, not always represent exact integers, even if they are meant to, so it's important to allow a tolerance.
For instance tolerance could be 1E-6, in the unit tests, I kept a rather coarse tolerance to have shorter numbers.
None of the answers that I can read now works in this way, so here is my solution:
public boolean isInteger(double n, double tolerance) {
double absN = Math.abs(n);
return Math.abs(absN - Math.round(absN)) <= tolerance;
}
And the unit test, to make sure it works:
@Test
public void checkIsInteger() {
final double TOLERANCE = 1E-2;
assertThat(solver.isInteger(1, TOLERANCE), is(true));
assertThat(solver.isInteger(0.999, TOLERANCE), is(true));
assertThat(solver.isInteger(0.9, TOLERANCE), is(false));
assertThat(solver.isInteger(1.001, TOLERANCE), is(true));
assertThat(solver.isInteger(1.1, TOLERANCE), is(false));
assertThat(solver.isInteger(-1, TOLERANCE), is(true));
assertThat(solver.isInteger(-0.999, TOLERANCE), is(true));
assertThat(solver.isInteger(-0.9, TOLERANCE), is(false));
assertThat(solver.isInteger(-1.001, TOLERANCE), is(true));
assertThat(solver.isInteger(-1.1, TOLERANCE), is(false));
}
This is a packaging bug. The entire proguard file is missing. We'll have an update asap, but until then just copy it over from a previous version of the tools:
and copy over the following files:
So at the end if you started from a new ADT copy by hand the files :)
Edit: with the latest ADT release, the bundle should now work with auto-update, so install these new versions:
Don't try to upgrade from previous version because it doesn’t work at all. If you have got problems with zipalign, it's now under build-tools and no more under tools/ so you can do a symbolic link or just copy it into the expected folder.
It doesn't work because it doesn't make sense (so little sense that HTML 5 explicitly forbids it).
To fix it, decide if you want a link or a submit button and use whichever one you actually want (Hint: You don't have a form, so a submit button is nonsense).
Swift 2.1.1 below works:
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let v = UIView()
v.backgroundColor = UIColor.RGB(53, 60, 62)
return v
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 80
}
If use self.theTable.tableFooterView = tableFooter
there is a space between last row and tableFooterView
.
AngularJS extends this events-loop, creating something called AngularJS context
.
$watch()
Every time you bind something in the UI you insert a $watch
in a $watch
list.
User: <input type="text" ng-model="user" />
Password: <input type="password" ng-model="pass" />
Here we have $scope.user
, which is bound to the first input, and we have $scope.pass
, which is bound to the second one. Doing this we add two $watch
es to the $watch
list.
When our template is loaded, AKA in the linking phase, the compiler will look for every directive and creates all the $watch
es that are needed.
AngularJS provides $watch
, $watchcollection
and $watch(true)
. Below is a neat diagram explaining all the three taken from watchers in depth.
angular.module('MY_APP', []).controller('MyCtrl', MyCtrl)
function MyCtrl($scope,$timeout) {
$scope.users = [{"name": "vinoth"},{"name":"yusuf"},{"name":"rajini"}];
$scope.$watch("users", function() {
console.log("**** reference checkers $watch ****")
});
$scope.$watchCollection("users", function() {
console.log("**** Collection checkers $watchCollection ****")
});
$scope.$watch("users", function() {
console.log("**** equality checkers with $watch(true) ****")
}, true);
$timeout(function(){
console.log("Triggers All ")
$scope.users = [];
$scope.$digest();
console.log("Triggers $watchCollection and $watch(true)")
$scope.users.push({ name: 'Thalaivar'});
$scope.$digest();
console.log("Triggers $watch(true)")
$scope.users[0].name = 'Superstar';
$scope.$digest();
});
}
$digest
loopWhen the browser receives an event that can be managed by the AngularJS context the $digest
loop will be fired. This loop is made from two smaller loops. One processes the $evalAsync
queue, and the other one processes the $watch list
. The $digest
will loop through the list of $watch
that we have
app.controller('MainCtrl', function() {
$scope.name = "vinoth";
$scope.changeFoo = function() {
$scope.name = "Thalaivar";
}
});
{{ name }}
<button ng-click="changeFoo()">Change the name</button>
Here we have only one $watch
because ng-click doesn’t create any watches.
We press the button.
$digest
loop will run and will ask every $watch for changes.$watch
which was watching for changes in $scope.name
reports a change, it will force another $digest
loop.$digest
loop. That means that every time we write a letter in an input, the loop will run checking every $watch
in this page.If you call $apply
when an event is fired, it will go through the angular-context, but if you don’t call it, it will run outside it. It is as easy as that. $apply
will call the $digest()
loop internally and it will iterate over all the watches to ensure the DOM is updated with the newly updated value.
The $apply()
method will trigger watchers on the entire $scope
chain whereas the $digest()
method will only trigger watchers on the current $scope
and its children
. When none of the higher-up $scope
objects need to know about the local changes, you can use $digest()
.
To handle session properly, take a look at http://php.net/manual/en/session.configuration.php.
There you'll find these variables:
These control the garbage collector (GC) probability of running with each page request.
You could set those with ini_set() at the beginning of your script or .htaccess file so you get certainty to some extent they will get deleted sometime.
Rfast has a function called nth_element that does exactly what you ask and is faster than all of the implementations discussed above
Also the methods discussed above that are based on partial sort, don't support finding the k smallest values
Disclaimer: An issue appears to occur when dealing with integers which can by bypassed by using as.numeric (e.g. Rfast::nth(as.numeric(1:10), 2)), and will be addressed in the next update of Rfast.
Rfast::nth(x, 5, descending = T)
Will return the 5th largest element of x, while
Rfast::nth(x, 5, descending = F)
Will return the 5th smallest element of x
Benchmarks below against most popular answers.
For 10 thousand numbers:
N = 10000
x = rnorm(N)
maxN <- function(x, N=2){
len <- length(x)
if(N>len){
warning('N greater than length(x). Setting N=length(x)')
N <- length(x)
}
sort(x,partial=len-N+1)[len-N+1]
}
microbenchmark::microbenchmark(
Rfast = Rfast::nth(x,5,descending = T),
maxn = maxN(x,5),
order = x[order(x, decreasing = T)[5]])
Unit: microseconds
expr min lq mean median uq max neval
Rfast 160.364 179.607 202.8024 194.575 210.1830 351.517 100
maxN 396.419 423.360 559.2707 446.452 487.0775 4949.452 100
order 1288.466 1343.417 1746.7627 1433.221 1500.7865 13768.148 100
For 1 million numbers:
N = 1e6
x = rnorm(N)
microbenchmark::microbenchmark(
Rfast = Rfast::nth(x,5,descending = T),
maxN = maxN(x,5),
order = x[order(x, decreasing = T)[5]])
Unit: milliseconds
expr min lq mean median uq max neval
Rfast 89.7722 93.63674 114.9893 104.6325 120.5767 204.8839 100
maxN 150.2822 207.03922 235.3037 241.7604 259.7476 336.7051 100
order 930.8924 968.54785 1005.5487 991.7995 1031.0290 1164.9129 100
This is defined in PEP8 here:
Global Variable Names
(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.
Modules that are designed for use via
from M import *
should use the__all__
mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").
PEP8 provides coding conventions for the Python code comprising the standard library in the main Python distribution. The more you follow this, closer you are to the original intent.
Back in 2002, Novell developed some software called NetDrive that can map a WebDAV, FTP, SFTP, etc. share to a windows drive letter. It is now abandonware, so it's no longer maintained (and not available on the Novell website), but it's free to use. I found quite a few available to download by searching for "netdrive.exe" I actually downloaded a few and compared their md5sums to make sure that I was getting a common (and hopefully safe) version.
Update 10 Nov 2017 SFTPNetDrive is the current project from the original netdrive project. And they made it free for personal use:
We Made SFTP Net Drive FREE for Personal Use
They have paid options as well on the website.
For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.
This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.
Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts
On stackoverflow, see:
Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?
MattDMo's answer here: What is the default font of Sublime Text?
I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)
Other viewing environments that benefit from shorter lines:
github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.
If you want to find out only whether or not the files are identical, you can use the Windows fc
command in binary mode:
fc.exe /b file1 file2
For details, see the reference for fc
I was facing same problem in my ubuntu 16.04
but i fixed that problem and it's very simple just follow these step and you will be able to install postgresql 10 in your system :
Add this to your sources.list:
sudo vim /etc/apt/sources.list
deb http://ftp.de.debian.org/debian/ wheezy main non-free contrib
deb-src http://ftp.de.debian.org/debian/ wheezy main non-free contrib
after that add these link to your pgdg.list file if it's not there you have to create && add link && save it.
sudo vim /etc/apt/sources.list.d/pgdg.list
deb http://apt.postgresql.org/pub/repos/apt/ xenial-pgdg main
deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main
then update your system
sudo apt-get update
sudo apt-get upgrade
and install that unmet dependencies :
apt-get install ssl-cert
that's it. now Install postgresql using these command
sudo apt-get install postgresql-10
Using the accepted answer I create a helper class so you could use it in a similar way you would use the Lock statement. Just thought I'd share.
Use:
using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock
{
//Only 1 of these runs at a time
RunSomeStuff();
}
And the helper class:
class SingleGlobalInstance : IDisposable
{
//edit by user "jitbit" - renamed private fields to "_"
public bool _hasHandle = false;
Mutex _mutex;
private void InitMutex()
{
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
string mutexId = string.Format("Global\\{{{0}}}", appGuid);
_mutex = new Mutex(false, mutexId);
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
_mutex.SetAccessControl(securitySettings);
}
public SingleGlobalInstance(int timeOut)
{
InitMutex();
try
{
if(timeOut < 0)
_hasHandle = _mutex.WaitOne(Timeout.Infinite, false);
else
_hasHandle = _mutex.WaitOne(timeOut, false);
if (_hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
}
catch (AbandonedMutexException)
{
_hasHandle = true;
}
}
public void Dispose()
{
if (_mutex != null)
{
if (_hasHandle)
_mutex.ReleaseMutex();
_mutex.Close();
}
}
}
You can try if(typeof object !== 'undefined')
In case of detached HEAD, commits work like normal, except no named branch gets updated. To get master branch updated with your committed changes, make a temporary branch where you are (this way the temporary branch will have all the committed changes you have made in the detached HEAD) , then switch to the master branch and merge the temporary branch with the master.
git branch temp
git checkout master
git merge temp
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
If only one checkbox should be checked in the same time use RadioButtonFor instead:
@Html.RadioButtonFor(model => model.Type,1, new { @checked = "checked" }) fultime
@Html.RadioButtonFor(model => model.Type,2) party
@Html.RadioButtonFor(model => model.Type,3) next option...
If one more one could be checked in the same time use excellent extension: CheckBoxListFor:
Hope,it will help
Never mind got the way to do it.
def plotGraph(X,Y):
fignum = random.randint(0,sys.maxint)
fig = plt.figure(fignum)
### Plotting arrangements ###
return fig
------ plotting module ------
----- mainModule ----
import matplotlib.pyplot as plt
### tempDLStats, tempDLlabels are the argument
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
plt.show()
plot1.savefig('plot1.png')
plot2.savefig('plot2.png')
plot3.savefig('plot3.png')
----- mainModule -----
Its simple these are the steps: 1. first go to the following settings Window -> Preferences -> Java -> Editor -> content assist -> advanced 2. there will be two boxes having checkboxes. 3. check everthing in there and click apply. 4. now ofcourse when you'll be coding there will be auto code completion feature automatically.
There is no show
event in js - you need to bind your button either to the click
event:
$('#id').on('click', function (e) {
//your awesome code here
})
Mind that if your button is inside a form
, you may prefer to bind the whole form to the submit
event.
I think it's generally browser specific. To be on the safe side, base64 encode a JSON object, and store everything in that. That way you just have to decode it and parse the JSON. All the characters used in base64 should play fine with most, if not all browsers.
You often see the check for definedness so you don't have to deal with the warning for using an undef value (and in Perl 5.10 it tells you the offending variable):
Use of uninitialized value $name in ...
So, to get around this warning, people come up with all sorts of code, and that code starts to look like an important part of the solution rather than the bubble gum and duct tape that it is. Sometimes, it's better to show what you are doing by explicitly turning off the warning that you are trying to avoid:
{
no warnings 'uninitialized';
if( length $name ) {
...
}
}
In other cases, use some sort of null value instead of the data. With Perl 5.10's defined-or operator, you can give length
an explicit empty string (defined, and give back zero length) instead of the variable that will trigger the warning:
use 5.010;
if( length( $name // '' ) ) {
...
}
In Perl 5.12, it's a bit easier because length
on an undefined value also returns undefined. That might seem like a bit of silliness, but that pleases the mathematician I might have wanted to be. That doesn't issue a warning, which is the reason this question exists.
use 5.012;
use warnings;
my $name;
if( length $name ) { # no warning
...
}
In this case, you might get some differences. Consider a line like:
"foo\tbar "
In this case, if you strip
, then you'll get {"foo":"bar"}
as the dictionary entry. If you don't strip, you'll get {"foo":"bar "}
(note the extra space at the end)
Note that if you use line.split()
instead of line.split('\t')
, you'll split on every whitespace character and the "strip
ing" will be done during splitting automatically. In other words:
line.strip().split()
is always identical to:
line.split()
but:
line.strip().split(delimiter)
Is not necessarily equivalent to:
line.split(delimiter)
Use TO_TIMESTAMP function
TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')
C# will allow you to have a string split over multiple lines, the term is called verbatim literal
:
string myString = @"this is a
test
to see how long my string
can be
and it can be quite long";
If you are looking for the alternative to & _
from VB, use the +
to join your lines.
IIS v10 (but this should be the same also for IIS 7.x)
Quick addition for people which are looking for respective max values
Max for maxAllowedContentLength
is: UInt32.MaxValue
4294967295 bytes
: ~4GB
Max for maxRequestLength
is: Int32.MaxValue
2147483647 bytes
: ~2GB
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<!-- ~ 2GB -->
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- ~ 4GB -->
<requestLimits maxAllowedContentLength="4294967295" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
You can open the Find in Path dialog by pressing:
Ctrl + Shift + F
You have to read
database column
here. You could have a look on following code snippet
string connectionString = ConfigurationManager.ConnectionStrings["NameOfYourSqlConnectionString"].ConnectionString;
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("SELECT SomeColumnName FROM TableName", _connection))
{
SqlDataReader sqlDataReader = command.ExecuteReader();
if (sqlDataReader.HasRows)
{
while (sqlDataReader.Read())
{
string YourFirstDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
string YourSecondDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
string YourThridDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
}
}
sqlDataReader.Close();
}
_connection.Close();
You can use the pandas library if the file is note very large. Be careful when using iter over pandas dataframes. I am doing this here to demonstrate the possibility. One could also consider the pd.Dataframe.to_sql() function when copying from a dataframe to an sql table
Assuming you have created the table you want you could:
import psycopg2
import pandas as pd
data=pd.read_csv(r'path\to\file.csv', delimiter=' ')
#prepare your data and keep only relevant columns
data.drop(['col2', 'col4','col5'], axis=1, inplace=True)
data.dropna(inplace=True)
print(data.iloc[:3])
conn=psycopg2.connect("dbname=db user=postgres password=password")
cur=conn.cursor()
for index,row in data.iterrows():
cur.execute('''insert into table (col1,col3,col6)
VALUES (%s,%s,%s)''', (row['col1'], row['col3'], row['col6'])
cur.close()
conn.commit()
conn.close()
print('\n db connection closed.')
This happened to me right after upgrading Firefox to version 51. After clearing the cache
, the problem has gone.
On Windows, the only sure way is to use CtrlBreak. Stops every python script instantly!
(Note that on some keyboards, "Break" is labeled as "Pause".)
There is no such attribute in Android, to show a shadow. But possible ways to do it are:
Add a plain LinearLayout with grey color, over which add your actual layout, with margin at bottom and right equal to 1 or 2 dp
Have a 9-patch image with a shadow and set it as the background to your Linear layout
This piece of snippet is from c++ primer book. Although I am sure this is wrong.
Each type parameter must be preceded by the keyword class or typename:
// error: must precede U with either typename or class
template <typename T, U> T calc(const T&, const U&);
These keywords have the same meaning and can be used interchangeably inside a template parameter list. A template parameter list can use both keywords:
// ok: no distinction between typename and class in a template parameter list
template <typename T, class U> calc (const T&, const U&);
It may seem more intuitive to use the keyword typename rather than class to designate a template type parameter. After all, we can use built-in (nonclass) types as a template type argument. Moreover, typename more clearly indicates that the name that follows is a type name. However, typename was added to C++ after templates were already in widespread use; some programmers continue to use class exclusively
You can use:
date -d "yesterday 13:55" '+%Y-%m-%d'
Or whatever time you want to retrieve will retrieved by bash.
For month:
date -d "30 days ago" '+%Y-%m-%d'
You might need to change your object to an array first. I dont know what export
does, but I assume its expecting an array.
You can either use
Or if its a simple object, you can just typecast it.
$arr = (array) $Object;
The kernel is part of the operating system and closer to the hardware it provides low level services like:
An operating system also includes applications like the user interface (shell, gui, tools, and services).
If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors();
in the configure
method. The method looks like that:
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests() // authorize
.anyRequest().authenticated() // all requests are authenticated
.and()
.httpBasic();
http.cors();
}
As Tr?n Si Long suggested, use
String[] mStrings = new String[title.length];
And replace string concatation with proper parenthesis.
mStrings[i] = (urlbase + (title[i].replaceAll("[^a-zA-Z]", ""))).toLowerCase() + imgSel;
Try this. If it's problem due to concatation, it will be resolved with proper brackets. Hope it helps.
Taken from [blog]: http://sickprogrammersarea.blogspot.in/2014/03/technical-interview-questions-on-c_6.html
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.
Explanation:
Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack.
If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.
The key here is the name
attribute of the f
object representing the opened file. You get it like that:
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> f.name
'/Users/Desktop/febROSTER2012.xls'
Does it help?
Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.
Since Http service in angular2 returns an Observable type, From your Angular2 installation directory('node_modules' in my case),We need to import map function of the Observable in your component using http service,as:
import 'rxjs/add/operator/map';
You have another server_name ec2-xx-xx-xxx-xxx.us-west-1.compute.amazonaws.com
somewhere in the config.
@jonrsharpe has an excellent explanation of what's going on. I thought I'd just show the difference in time when running each of the 3 options 10,000,000 times (enough for a slight difference to show).
Code used:
def a(x):
if x != 'val':
pass
def b(x):
if not x == 'val':
pass
def c(x):
if x == 'val':
pass
else:
pass
x = 1
for i in range(10000000):
a(x)
b(x)
c(x)
And the cProfile profiler results:
So we can see that there is a very minute difference of ~0.7% between if not x == 'val':
and if x != 'val':
. Of these, if x != 'val':
is the fastest.
However, most surprisingly, we can see that
if x == 'val':
pass
else:
is in fact the fastest, and beats if x != 'val':
by ~0.3%. This isn't very readable, but I guess if you wanted a negligible performance improvement, one could go down this route.
system
The system
method calls a system program. You have to provide the command as a string argument to this method. For example:
>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true
The invoked program will use the current STDIN
, STDOUT
and STDERR
objects of your Ruby program. In fact, the actual return value is either true
, false
or nil
. In the example the date was printed through the IO object of STDIN
. The method will return true
if the process exited with a zero status, false
if the process exited with a non-zero status and nil
if the execution failed.
As of Ruby 2.6, passing exception: true
will raise an exception instead of returning false
or nil
:
>> system('invalid')
=> nil
>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)
Another side effect is that the global variable $?
is set to a Process::Status
object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.
>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>
Backticks
Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.
>> `date`
=> Wed Sep 4 22:22:51 CEST 2013
The global variable $?
is set through the backticks, too. With backticks you can also make use string interpolation.
%x()
Using %x
is an alternative to the backticks style. It will return the output, too. Like its relatives %w
and %q
(among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date)
, %x{date}
and %x-date-
are all synonyms. Like backticks %x
can make use of string interpolation.
exec
By using Kernel#exec
the current process (your Ruby script) is replaced with the process invoked through exec
. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.
Open3.popen3
Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3
comes in handy:
require 'open3'
Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
pid = thread.pid
puts stdout.read.chomp
end
Not sure if this covers absolutely everything, but I use something like this (especially when debugging) to detect when an array has an element added:
var array = [1,2,3,4];
array = new Proxy(array, {
set: function(target, key, value) {
if (Number.isInteger(Number(key)) || key === 'length') {
debugger; //or other code
}
target[key] = value;
return true;
}
});
I have solved it with adding some key in info.plist. The steps I followed are:
Opened my Project target's info.plist
file
Added a Key called NSAppTransportSecurity
as a Dictionary
.
Added a Subkey called NSAllowsArbitraryLoads
as Boolean
and set its value to YES
as like following image.
Clean the Project and Now Everything is Running fine as like before.
Ref Link: https://stackoverflow.com/a/32609970
EDIT:
OR In source code of info.plist
file we can add that:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>
Can be as easy as:
var ms = new MemoryStream(imageData);
System.Drawing.Image image = Image.FromStream(ms);
image.Save("c:\\image.jpg");
Testing it out:
byte[] imageData;
// Create the byte array.
var originalImage = Image.FromFile(@"C:\original.jpg");
using (var ms = new MemoryStream())
{
originalImage.Save(ms, ImageFormat.Jpeg);
imageData = ms.ToArray();
}
// Convert back to image.
using (var ms = new MemoryStream(imageData))
{
Image image = Image.FromStream(ms);
image.Save(@"C:\newImage.jpg");
}
If you are so lost for read the last comment. I have reached another solution.
The main problem is the way that you named the services names.
In this case, if in your docker-compose.yml
, the service for php are called "api" or something like that, you must ensure that in the file nginx.conf
the line that begins with fastcgi_pass
have the same name as the php service. i.e fastcgi_pass api:9000;
Quick List: There are a number of common types of
setup.exe
files. Here are some of them in a "short-list". More fleshed-out details here (towards bottom).
Setup.exe Extract: (various flavors to try)
setup.exe /a setup.exe /s /extract_all setup.exe /s /extract_all:[path] setup.exe /stage_only setup.exe /extract "C:\My work" setup.exe /x setup.exe /x [path] setup.exe /s /x /b"C:\FolderInWhichMSIWillBeExtracted" /v"/qn" dark.exe -x outputfolder setup.exe
dark.exe
is a WiX binary - install WiX to extract a WiX setup.exe (as of now). More (section 4).
There is always:
setup.exe /?
MSI Extract: msiexec.exe
/ File.msi
extraction:
msiexec /a File.msi msiexec /a File.msi TARGETDIR=C:\MyInstallPoint /qn
Many Setup Tools: It is impossible to cover all the different kinds of possible setup.exe
files. They might feature all kinds of different command line switches. There are so many possible tools that can be used. (non-MSI
,MSI
, admin-tools
, multi-platform
, etc...).
NSIS / Inno: Commmon, free tools such as Inno Setup
seem to make extraction hard (unofficial unpacker, not tried by me, run by virustotal.com). Whereas NSIS
seems to use regular archives that standard archive software (7-zip et al) can open and extract.
General Tricks: One trick is to launch the
setup.exe
and look in the1)
system's temp folder for extracted files
. Another trick is to use2)
7-Zip, WinRAR, WinZip
or similar archive tools to see if they can read the format. Some claim success by3)
opening the setup.exe in Visual Studio
. Not a technique I use.4)
And there is obviously application repackaging
- capturing the changes done to a computer after a setup has run and clean it up - requires a special tool (most of the free ones come and go, Advanced Installer Architect and AdminStudio are big players).
UPDATE: A quick presentation of various deployment tools used to create installers: How to create windows installer (comprehensive links).
And a simpler list view of the most used development tools as of now (2018), for quicker reading and overview.
And for safekeeping:
- Create MSI from extracted setup files (towards bottom)
- Regarding silent installation using Setup.exe generated using Installshield 2013 (.issuite) project file (different kinds of Installshield setup.exe files)
- What is the purpose of administrative installation initiated using msiexec /a?.
Just a disclaimer: A setup.exe
file can contain an embedded MSI, it can be a legacy style (non-MSI) installer or it can be just a regular executable with no means of extraction whatsoever. The "discussion" below first presents the use of admin images for MSI files and how to extract MSI files from setup.exe files. Then it provides some links to handle other types of setup.exe files. Also see the comments section.
UPDATE: a few sections have now been added directly below, before the description of MSI file extract using administrative installation. Most significantly a blurb about extracting WiX setup.exe bundles (new kid on the block). Remember that a "last resort" to find extracted setup files, is to launch the installer and then look for extracted files in the temp folder (Hold down Windows Key, tap R, type %temp%
or %tmp%
and hit Enter) - try the other options first though - for reliability reasons.
Apologies for the "generalized mess" with all this heavy inter-linking. I do believe that you will find what you need if you dig enough in the links, but the content should really be cleaned up and organized better.
General links:
Extract content:
Vendor links:
Tech Note: The WiX toolkit now delivers setup.exe
files built with the bootstrapper tool Burn
that you need the toolkit's own dark.exe
decompiler to extract. Burn is used to build setup.exe files that can install several embedded MSI or executables in a specified sequence. Here is a sample extraction command:
dark.exe -x outputfolder MySetup.exe
Before you can run such an extraction, some prerequisite steps are required:
command prompt
, CD
to the folder where the setup.exe
resides. Then specify the above command and press EnterMSI or Windows Installer has built-in support for this - the extraction of files from an MSI file. This is called an administrative installation. It is basically intended as a way to create a network installation point from which the install can be run on many target computers. This ensures that the source files are always available for any repair operations.
Note that running an admin install versus using a zip tool to extract the files is very different! The latter will not adjust the media layout of the media table so that the package is set to use external source files - which is the correct way. Always prefer to run the actual admin install over any hacky zip extractions. As to compression, there are actually three different compression algorithms used for the cab files inside the MSI file format: MSZip, LZX, and Storing (uncompressed). All of these are handled correctly by doing an admin install.
Important: Windows Installer caches installed MSI files on the system for repair, modify and uninstall scenarios. Starting with Windows 7 (MSI version 5) the MSI files are now cached full size to avoid breaking the file signature that prevents the UAC prompt on setup launch (a known Vista problem). This may cause a tremendous increase in disk space consumption (several gigabytes for some systems). To prevent caching a huge MSI file, you should run an admin-install of the package before installing. This is how a company with proper deployment in a managed network would do things, and it will strip out the cab files and make a network install point with a small MSI file and files besides it.
It is recommended to read more about admin-installs since it is a useful concept, and I have written a post on stackoverflow: What is the purpose of administrative installation initiated using msiexec /a?.
In essence the admin install is important for:
Please read the stackoverflow post linked above for more details. It is quite an important concept for system administrators, application packagers, setup developers, release managers, and even the average user to see what they are installing etc...
You can perform an admin-install in a few different ways depending on how the installer is delivered. Essentially it is either delivered as an MSI file or wrapped in an setup.exe file.
Run these commands from an elevated command prompt, and follow the instructions in the GUI for the interactive command lines:
MSI files:
msiexec /a File.msi
that's to run with GUI, you can do it silently too:
msiexec /a File.msi TARGETDIR=C:\MyInstallPoint /qn
setup.exe files:
setup.exe /a
A setup.exe file can also be a legacy style setup (non-MSI) or the dreaded Installscript MSI file type - a well known buggy Installshield project type with hybrid non-standards-compliant MSI format. It is essentially an MSI with a custom, more advanced GUI, but it is also full of bugs.
For legacy setup.exe files the /a will do nothing, but you can try the /extract_all:[path] switch as explained in this pdf. It is a good reference for silent installation and other things as well. Another resource is this list of Installshield setup.exe command line parameters.
MSI patch files (*.MSP) can be applied to an admin image to properly extract its files. 7Zip will also be able to extract the files, but they will not be properly formatted.
Finally - the last resort - if no other way works, you can get hold of extracted setup files by cleaning out the temp folder on your system, launch the setup.exe interactively and then wait for the first dialog to show up. In most cases the installer will have extracted a bunch of files to a temp folder. Sometimes the files are plain, other times in CAB format, but Winzip, 7Zip or even Universal Extractor (haven't tested this product) - may be able to open these.
SELECT
[User], Activity,
STUFF(
(SELECT DISTINCT ',' + PageURL
FROM TableName
WHERE [User] = a.[User] AND Activity = a.Activity
FOR XML PATH (''))
, 1, 1, '') AS URLList
FROM TableName AS a
GROUP BY [User], Activity
Consider that you work with RDBMS and have to select what to use - full table scans, or index access - but only one of them.
If you select full table scan - use hive. If index access - HBase.
Shift-Tab
Ctrl-Tab
< key
depends on your editor.
Check your DataFrame with data.columns
It should print something like this
Index([u'regiment', u'company', u'name',u'postTestScore'], dtype='object')
Check for hidden white spaces..Then you can rename with
data = data.rename(columns={'Number ': 'Number'})
The following worked for me.
$ perldoc perllocal | grep Module
$ perldoc perllocal | grep -E 'VERSION|Module'
I found that the parser would complain if I used the
entity in my page. After a little research, I learned that if I added a DOCTYPE declaration to the beginning of the page, the entity was allowed. I use this DOCTYPE declaration:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
A side effect of this is that the resulting code (as seen by using the "view source" feature of a web browser) doesn't actually contain the
entity. It instead includes the actual characters that represent a nonbreaking space. Although it works, it's not really what I want. I'm still looking for a way to make the parser not replace the entity with the character.
More information here: http://java.net/jira/browse/JAVASERVERFACES-1576