If you're recompiling a disassembled APK
with APK tool:
Just Set Memory Allocation a little bigger
set switch -Xmx1024m
to -Xmx2048m
java -Xmx2048m -jar signapk.jar -w testkey.x509.pem testkey.pk8 "%APKOUT%" "%SIGNED%"
you're good to go.. :)
I'm new to this topic, so I can't say a whole lot, but BLAS is pretty much the standard in scientific computing. BLAS is actually an API standard, which has many implementations. I'm honestly not sure which implementations are most popular or why.
If you want to also be able to do common linear algebra operations (solving systems, least squares regression, decomposition, etc.) look into LAPACK.
this will help:
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancelAll();
this should remove all notifications made by the app
and if you create a notification by calling
startForeground();
inside a Service.you may have to call
stopForeground(false);
first,then cancel the notification.
This helped in my case:
cmdkey.exe /add:<targetname> /user:<username> /pass:<password>
psexec.exe \\<targetname> <remote_command>
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
You need use patches.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')
ax2.add_patch(
patches.Rectangle(
(0.1, 0.1),
0.5,
0.5,
fill=False # remove background
) )
fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')
Using your interface you can do
class Modal() {
constructor(public iModal: IModal) {
//You now have access to all your interface variables using this.iModal object,
//you don't need to define the properties at all, constructor does it for you.
}
}
One simple way of doing this is:
var data = [{_x000D_
"Total": 34,_x000D_
"Version": "1.0.4",_x000D_
"Office": "New York"_x000D_
}, {_x000D_
"Total": 67,_x000D_
"Version": "1.1.0",_x000D_
"Office": "Paris"_x000D_
}];_x000D_
_x000D_
drawTable(data);_x000D_
_x000D_
function drawTable(data) {_x000D_
_x000D_
// Get Table headers and print_x000D_
var head = $("<tr />")_x000D_
$("#DataTable").append(head);_x000D_
for (var j = 0; j < Object.keys(data[0]).length; j++) {_x000D_
head.append($("<th>" + Object.keys(data[0])[j] + "</th>"));_x000D_
}_x000D_
_x000D_
// Print the content of rows in DataTable_x000D_
for (var i = 0; i < data.length; i++) {_x000D_
drawRow(data[i]);_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
function drawRow(rowData) {_x000D_
var row = $("<tr />")_x000D_
$("#DataTable").append(row);_x000D_
row.append($("<td>" + rowData["Total"] + "</td>"));_x000D_
row.append($("<td>" + rowData["Version"] + "</td>"));_x000D_
row.append($("<td>" + rowData["Office"] + "</td>"));_x000D_
}
_x000D_
table {_x000D_
border: 1px solid #666;_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
th {_x000D_
background: #f8f8f8;_x000D_
font-weight: bold;_x000D_
padding: 2px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table id="DataTable"></table>
_x000D_
Here is a version that JSLint likes:
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var param = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = param.length,
tmp,
p;
for (p = 0; p < plength; p += 1) {
tmp = param[p].split('=');
GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
Or if you need support for several values for one key like eg. ?key=value1&key=value2 you can use this:
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var params = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = params.length,
tmp,
key,
val,
obj,
p;
for (p = 0; p < plength; p += 1) {
tmp = params[p].split('=');
key = decodeURIComponent(tmp[0]);
val = decodeURIComponent(tmp[1]);
if (GET.hasOwnProperty(key)) {
obj = GET[key];
if (obj.constructor === Array) {
obj.push(val);
} else {
GET[key] = [obj, val];
}
} else {
GET[key] = val;
}
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
For those wondering, @edward-coast
If you want to set the keep alive for the server, add this to /etc/ssh/sshd_config
:
ClientAliveInterval 60
ClientAliveCountMax 2
ClientAliveInterval: Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client.
ClientAliveCountMax: Sets the number of client alive messages (see below) which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session.
This has worked for me:
let webApiUrl = 'example.com/getStuff';
let tokenStr = 'xxyyzz';
axios.get(webApiUrl, { headers: {"Authorization" : `Bearer ${tokenStr}`} });
Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'
This will give you all the row which contains any special character.
JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.
What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");
Here is IBM's reference page.
If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE
Very simple use this just in one line:
byte[] imgdata = File.ReadAllBytes(@"C:\download.png");
Using OVER()
and LIMIT 1
:
SELECT COUNT(1) OVER()
FROM posts
INNER JOIN votes ON votes.post_id = posts.id
GROUP BY posts.id
LIMIT 1;
use strncpy
to make sure you have no buffer overflow.
char name[]= "whatever_you_want";
strncpy( sara.first, name, sizeof(sara.first)-1 );
sara.first[sizeof(sara.first)-1] = 0;
#Import functions from library
from numpy import size, array
#Transpose a 2D list
def transpose_list_2d(list_in_mat):
list_out_mat = []
array_in_mat = array(list_in_mat)
array_out_mat = array_in_mat.T
nb_lines = size(array_out_mat, 0)
for i_line_out in range(0, nb_lines):
array_out_line = array_out_mat[i_line_out]
list_out_line = list(array_out_line)
list_out_mat.append(list_out_line)
return list_out_mat
Try:
int i = Convert.ToInt32(dt.Rows.Count);
I think it's the shortest, thus the simplest way.
Please set the request Content Type before you read the response stream;
request.ContentType = "text/xml";
^\d{1,2}[\W_]?po$
\d
defines a number and {1,2}
means 1 or two of the expression before, \W
defines a non word character.
BehaviorSubject
keeps in memory the last value that was emitted by the observable. A regular Subject
doesn't.
BehaviorSubject
is like ReplaySubject
with a buffer size of 1.
git commit -m "first commit"
git remote add origin <linkyourrepository>
git push -u origin master
will works!
Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.
var i = 0;_x000D_
this.setInterval(function() {_x000D_
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
console.log('Counting...');_x000D_
$('#counter').html(i++); //just for explaining and showing_x000D_
} else {_x000D_
console.log('Stopped counting');_x000D_
}_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
$(this).addClass('pauseInterval');_x000D_
},function() { //mouse leave_x000D_
$(this).removeClass('pauseInterval');_x000D_
}_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
$('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
background-color: #eee;_x000D_
font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
width: 50%;_x000D_
background: #ddd;_x000D_
border: 2px solid #009afd;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
text-align: center;_x000D_
transition: .3s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
border-color: red; _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter"> </p>_x000D_
<button id="pauseInterval">Pause/unpause</button></p>
_x000D_
You can create a big subplot that covers the two subplots and then set the common labels.
import random
import matplotlib.pyplot as plt
x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]
fig = plt.figure()
ax = fig.add_subplot(111) # The big subplot
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
# Turn off axis lines and ticks of the big subplot
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(labelcolor='w', top=False, bottom=False, left=False, right=False)
ax1.loglog(x, y1)
ax2.loglog(x, y2)
# Set common labels
ax.set_xlabel('common xlabel')
ax.set_ylabel('common ylabel')
ax1.set_title('ax1 title')
ax2.set_title('ax2 title')
plt.savefig('common_labels.png', dpi=300)
Another way is using fig.text() to set the locations of the common labels directly.
import random
import matplotlib.pyplot as plt
x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.loglog(x, y1)
ax2.loglog(x, y2)
# Set common labels
fig.text(0.5, 0.04, 'common xlabel', ha='center', va='center')
fig.text(0.06, 0.5, 'common ylabel', ha='center', va='center', rotation='vertical')
ax1.set_title('ax1 title')
ax2.set_title('ax2 title')
plt.savefig('common_labels_text.png', dpi=300)
Global Gzip in HttpModule
If you don't have access to the final IIS instance (shared hosting...) you can create a HttpModule that adds this code to every HttpApplication.Begin_Request event :
HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
Testing
Kudos, no solution is done without testing. I like to use the Firefox plugin "Liveheaders" it shows all the information about every http message between the browser and server, including compression, file size (which you could compare to the file size on the server).
There is actually no need to check whether it exists or not. Since you already wants to create it if it exists , just mkdir will do
mkdir -p /home/mlzboy/b2c2/shared/db
This is way I did it:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)
You can define your own sizes.
Unfortunately none of the above worked for me, so instead I added a label on top of the comboxbox that says "Please select". I used the following code to show and hide it:
When I initialise my combobox, if there is no selected value I bring it to the front and set the text:
PleaseSelectValueLabel.BringToFront();
PleaseSelectValueLabel.Text = Constants.AssessmentValuePrompt;
If there is a value selected I send it to the back:
PleaseSelectValueLabel.SendToBack();
I then use the following events to move the label to the front or back depending on whether the user has selected a value:
private void PleaseSelectValueLabel_Click(object sender, EventArgs e)
{
PleaseSelectValueLabel.SendToBack();
AssessmentValue.Focus();
}
private void AssessmentValue_Click(object sender, EventArgs e)
{
PleaseSelectValueLabel.SendToBack();
}
//if the user hasnt selected an item, make the please select label visible again
private void AssessmentValue_Leave(object sender, EventArgs e)
{
if (AssessmentValue.SelectedIndex < 0)
{
PleaseSelectValueLabel.BringToFront();
}
}
Elaborating on yasaluyari
's answer I would stick with something like this:
We can just modify our mysql_query as follows:
function mysql_catchquery($query,$emsg='Error submitting the query'){
if ($result=mysql_query($query)) return $result;
else throw new Exception($emsg);
}
Now we can simply use it like this, some good example:
try {
mysql_catchquery('CREATE TEMPORARY TABLE a (ID int(6))');
mysql_catchquery('insert into a values(666),(418),(93)');
mysql_catchquery('insert into b(ID, name) select a.ID, c.name from a join c on a.ID=c.ID');
$result=mysql_catchquery('select * from d where ID=7777777');
while ($tmp=mysql_fetch_assoc($result)) { ... }
} catch (Exception $e) {
echo $e->getMessage();
}
Note how beautiful it is. Whenever any of the qq fails we gtfo with our errors. And you can also note that we don't need now to store the state of the writing queries into a $result
variable for verification, because our function now handles it by itself. And the same way it handles the selects, it just assigns the result to a variable as does the normal function, yet handles the errors within itself.
Also note, we don't need to show the actual errors since they bear huge security risk, especially so with this outdated extension. That is why our default will be just fine most of the time. Yet, if we do want to notify the user for some particular query error, we can always pass the second parameter to display our custom error message.
You may need to config the CORS at Spring Boot side. Please add below class in your Project.
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
System.out.println("WebConfig; "+request.getRequestURI());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Expose-Headers", "Authorization");
response.addHeader("Access-Control-Expose-Headers", "responseType");
response.addHeader("Access-Control-Expose-Headers", "observe");
System.out.println("Request Method: "+request.getMethod());
if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
try {
chain.doFilter(req, res);
} catch(Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Pre-flight");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
"USERID"+"ROLE"+
"access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
response.setStatus(HttpServletResponse.SC_OK);
}
}
}
UPDATE:
To append Token to each request you can create one Interceptor as below.
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = window.localStorage.getItem('tokenKey'); // you probably want to store it in localStorage or something
if (!token) {
return next.handle(req);
}
const req1 = req.clone({
headers: req.headers.set('Authorization', `${token}`),
});
return next.handle(req1);
}
}
For small scripts an optional way to make it readable is to use a variable like this:
awk -v fmt="'%s'\n" '{printf fmt, $1}'
I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable
What I usually do is use clock()
or time()
from the time
library. clock
measures interpreter time, while time
measures system time. Additional caveats can be found in the docs.
For example,
def fn():
st = time()
dostuff()
print 'fn took %.2f seconds' % (time() - st)
Or alternatively, you can use timeit
. I often use the time
approach due to how fast I can bang it out, but if you're timing an isolate-able piece of code, timeit
comes in handy.
From the timeit docs,
def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
Then to convert to minutes, you can simply divide by 60. If you want the script runtime in an easily readable format, whether it's seconds or days, you can convert to a timedelta
and str
it:
runtime = time() - st
print 'runtime:', timedelta(seconds=runtime)
and that'll print out something of the form [D day[s], ][H]H:MM:SS[.UUUUUU]
. You can check out the timedelta docs.
And finally, if what you're actually after is profiling your code, Python makes available the profile library as well.
There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).
You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:
Company: Vodafone
------------------
LSE symbol: VOD
in Google: LON:VOD
in Yahoo: VOD.L
NASDAQ symbol: VOD
in Google: NASDAQ:VOD
in Yahoo: VOD
Given an answer as high voted and views. I did find the answer with mixed of here and other links.
I have a scenario where all patient-related menu is disabled if a patient is not selected. (Refer link - how to disable a li tag using JavaScript)
//css
.disabled{
pointer-events:none;
opacity:0.4;
}
// jqvery
$("li a").addClass('disabled');
// remove .disabled when you are done
So rather than write long code, I found an interesting solution via CSS.
$(document).ready(function () {_x000D_
var PatientId ; _x000D_
//var PatientId =1; //remove to test enable i.e. patient selected_x000D_
if (typeof PatientId == "undefined" || PatientId == "" || PatientId == 0 || PatientId == null) {_x000D_
console.log(PatientId);_x000D_
$("#dvHeaderSubMenu a").each(function () { _x000D_
$(this).addClass('disabled');_x000D_
}); _x000D_
return;_x000D_
}_x000D_
})
_x000D_
.disabled{_x000D_
pointer-events:none;_x000D_
opacity:0.4;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dvHeaderSubMenu">_x000D_
<ul class="m-nav m-nav--inline pull-right nav-sub">_x000D_
<li class="m-nav__item">_x000D_
<a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
<i class="m-nav__link-icon fa fa-tachometer"></i>_x000D_
Overview_x000D_
</a>_x000D_
</li>_x000D_
_x000D_
<li class="m-nav__item active">_x000D_
<a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
<i class="m-nav__link-icon fa fa-user"></i>_x000D_
Personal_x000D_
</a>_x000D_
</li>_x000D_
<li class="m-nav__item m-dropdown m-dropdown--inline m-dropdown--arrow" data-dropdown-toggle="hover">_x000D_
<a href="#" class="m-dropdown__toggle dropdown-toggle" onclick="console.log('PatientMenu Clicked')">_x000D_
<i class="m-nav__link-icon flaticon-medical-8"></i>_x000D_
Insurance Claim_x000D_
</a>_x000D_
<div class="m-dropdown__wrapper">_x000D_
<span class="m-dropdown__arrow m-dropdown__arrow--left"></span>_x000D_
_x000D_
<ul class="m-nav">_x000D_
<li class="m-nav__item">_x000D_
<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')" >_x000D_
<i class="m-nav__link-icon flaticon-toothbrush-1"></i>_x000D_
<span class="m-nav__link-text">_x000D_
Primary_x000D_
</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="m-nav__item">_x000D_
<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
<i class="m-nav__link-icon flaticon-interface"></i>_x000D_
<span class="m-nav__link-text">_x000D_
Secondary_x000D_
</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="m-nav__item">_x000D_
<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
<i class="m-nav__link-icon flaticon-healthy"></i>_x000D_
<span class="m-nav__link-text">_x000D_
Medical_x000D_
</span>_x000D_
</a>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
_x000D_
</li>_x000D_
</ul> _x000D_
</div>
_x000D_
there is a better way.
View.performClick();
http://developer.android.com/reference/android/view/View.html#performClick()
this should answer all your problems. every View inherits this function, including Button, Spinner, etc.
Just to clarify, View does not have a static performClick() method. You must call performClick() on an instance of View. For example, you can't just call
View.performClick();
Instead, do something like:
View myView = findViewById(R.id.myview);
myView.performClick();
With jquery you can easy detect copy, paste, etc by binding the function:
$("#textA").bind('copy', function() {
$('span').text('copy behaviour detected!')
});
$("#textA").bind('paste', function() {
$('span').text('paste behaviour detected!')
});
$("#textA").bind('cut', function() {
$('span').text('cut behaviour detected!')
});
More information here: http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/
As was mentioned in the question here, the open
command in 10.6 now has an args
flag, so you can call:
open -n ./AppName.app --args -AppCommandLineArg
I can't believe how overcomplicated some of these answers are... (no offence!)
Here's a single-line function that will get the job done:
Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"\")+1):End Function
Function getPath(pf)As String:getPath=Left(pf,InStrRev(pf,"\")):End Function
It's not necessary, it's optional, just as public
on interface methods.
See the JLS on this:
http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html
9.1.1.1 abstract Interfaces Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.
And
9.4 Abstract Method Declarations
[...]
For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.
It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.
I have found that sometimes the CTRL + F11 combination just doesn't do it for me. I have solved it by disabling the keyboard input in the emulator settings.
To do that, go to your emulator settings, klick the "show advanced settings" button and scroll all the way down. Then, disable the "enable keyboard input" option.
After doing that, try to start your emulator again, and the CTRL + F11 combination should work.
One option to try is to put the image in the drawable-nodpi
folder and set background of a layout to the drawable resource id.
This definitely works with scaling down, I haven't tested with scaling up though.
My take is that Optional should be a Monad and these are not conceivable in Java.
In functional programming you deal with pure and higher order functions that take and compose their arguments only based on their "business domain type". Composing functions that feed on, or whose computation should be reported to, the real-world (so called side effects) requires the application of functions that take care of automatically unpacking the values out of the monads representing the outside world (State, Configuration, Futures, Maybe, Either, Writer, etc...); this is called lifting. You can think of it as a kind of separation of concerns.
Mixing these two levels of abstraction doesn't facilitate legibility so you're better off just avoiding it.
A SOAP request is an XML file consisting of the parameters you are sending to the server.
The SOAP response is equally an XML file, but now with everything the service wants to give you.
Basically the WSDL is a XML file that explains the structure of those two XML.
To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
http://www.webservicex.net/uszip.asmx?op=GetInfoByCity
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
String soapAction = "http://www.webserviceX.NET/GetInfoByCity";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "http://www.webserviceX.NET";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:GetInfoByCity>
<myNamespace:USCity>New York</myNamespace:USCity>
</myNamespace:GetInfoByCity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
soapBodyElem1.addTextNode("New York");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
so the .animate method works only if you have given a position attribute to an element, if not it didn't move?
for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;
Have been using this one for a message overlay that can be closed immediately on click or it does an autoclose after 10 seconds.
button = $('.status-button a', whatever);
if(button.hasClass('close')) {
button.delay(10000).queue(function() {
$(this).click().dequeue();
});
}
If you are using BookId as an combined primary key, then remember to change your interface from:
public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {
to:
public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {
And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:
public class QueuedBook implements Serializable {
@EmbeddedId
@NotNull
private BookId bookId;
...
InitialValue="0" : initial validation will fire when 0th index item is selected in ddl.
<asp:RequiredFieldValidator InitialValue="0" Display="Dynamic" CssClass="error" runat="server" ID="your_id" ValidationGroup="validationgroup" ControlToValidate="your_dropdownlist_id" />
EDIT: updated code in order to reflect changes made to the way pipes work in more recent versions of RXJS. All operators (take in my example) are now wrapped into the pipe() operator.
I realize that this Question was quite a while ago and you surely have a proper solution by now, but for anyone looking for this I would suggest solving it with a Promise to keep the async pattern.
A more verbose version would be creating a new Promise:
function getValueFromObservable() {
return new Promise(resolve=>{
this.store.pipe(
take(1) //useful if you need the data once and don't want to manually cancel the subscription again
)
.subscribe(
(data:any) => {
console.log(data);
resolve(data);
})
})
}
On the receiving end you will then have "wait" for the promise to resolve with something like this:
getValueFromObservable()
.then((data:any)=>{
//... continue with anything depending on "data" after the Promise has resolved
})
A slimmer solution would be using RxJS' .toPromise() instead:
function getValueFromObservable() {
return this.store.pipe(take(1))
.toPromise()
}
The receiving side stays the same as above of course.
I like using ls
options, for sample:
-l
use a long listing format-t
sort by modification time, newest first-r
reverse order while sorting-F
,--classify
append indicator (one of */=>@|) to entries-h
,--human-readable
with -l and -s, print sizes like 1K 234M 2G etc...
Sometime --color
and all others. (See ls --help
)
This will show files, symlinks, devices, pipe, sockets etc.
so
find /some/path -maxdepth 1 ! -type d
could be sorted by date easily:
find /some/path -maxdepth 1 ! -type d -exec ls -hltrF {} +
or
find /some/path -maxdepth 1 -type f
sorted by size:
find /some/path -maxdepth 1 -type f -exec ls -lSF --color {} +
To not show hidden entries, where name begin by a dot, you could add ! -name '.*'
:
find /some/path -maxdepth 1 ! -type d ! -name '.*' -exec ls -hltrF {} +
Then
You could replace /some/path
by .
to list for current directory or ..
for parent directory.
Use ClassLoader#getResource()
instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream
instead of InputStream
. If you can, just fix the API to ask for an InputStream
instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.
What you need to realize, coming from CVS, is that you no longer create directories when setting up a branch.
No more "sticky tag" (which can be applied to just one file), or "branch tag".
Branch and tags are two different objects in Git, and they always apply to the all repo.
You would no longer (with SVN this time) have to explicitly structure your repository with:
branches
myFirstBranch
myProject
mySubDirs
mySecondBranch
...
tags
myFirstTag
myProject
mySubDirs
mySecondTag
...
That structure comes from the fact CVS is a revision system and not a version system (see Source control vs. Revision Control?).
That means branches are emulated through tags for CVS, directory copies for SVN.
Your question makes senses if you are used to checkout a tag, and start working in it.
Which you shouldn't ;)
A tag is supposed to represent an immutable content, used only to access it with the guarantee to get the same content every time.
In Git, the history of revisions is a series of commits, forming a graph.
A branch is one path of that graph
x--x--x--x--x # one branch
\
--y----y # another branch
1.1
^
|
# a tag pointing to a commit
See Jakub Narebski's answer for all the technicalities, but frankly, at this point, you do not need (yet) all the details ;)
The main point is: a tag being a simple pointer to a commit, you will never be able to modify its content. You need a branch.
In your case, each developer working on a specific feature:
Instead of tracking directly the branches of your colleagues, you could track only the branch of one "official" central repository to which everyone pushes his/her work in order to integrate and share everyone's work for this particular feature.
Here is a tidyverse
option that might work depending on the data, and some caveats on its usage:
library(tidyverse)
starting_df %>%
rownames_to_column() %>%
gather(variable, value, -rowname) %>%
spread(rowname, value)
rownames_to_column()
is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column()
and replace rowname
with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths
sample data would be:
smiths %>%
gather(variable, value, -subject) %>%
spread(subject, value)
Using the example starting_df
with the tidyverse
approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths
data will not give that warning because all columns except for subject
are doubles.
The earlier answer using as.data.frame(t())
will convert everything to a factor
if there are mixed column types unless stringsAsFactors = FALSE
is added,
whereas the tidyverse
option converts everything to a character by default if
there are mixed column types.
Using higher-order functions (note: I'm using inline anonymous functions, which appeared in PHP 5.3):
function array_flatten($array) {
return array_reduce(
$array,
function($prev, $element) {
if (!is_array($element))
$prev[] = $element;
else
$prev = array_merge($prev, array_flatten($element));
return $prev;
},
array()
);
}
The is
operator in Python probably doesn't do what you expect. Instead of this:
if numpy.array_equal(tmp,universe_array) is True:
break
I would write it like this:
if numpy.array_equal(tmp,universe_array):
break
The is
operator tests object identity, which is something quite different from equality.
Have a look at qtlcharts. It allows you to create interactive correlation matrices:
library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)
It's more impressive when you correlate more variables, like in the package's vignette:
I think your answer will be background-size:cover
.
.ui-page
{
background: #000;
background-image:url(image.gif);
background-size:cover;
}
This way you don't have to use any magic numbers:
os.MkdirAll(newPath, os.ModePerm)
Also, rather than using + to create paths, you can use:
import "path/filepath"
path := filepath.Join(someRootPath, someSubPath)
The above uses the correct separators automatically on each platform for you.
You need a root node
<?xml version="1.0" encoding="ISO-8859-1"?>
<documents>
<document>
<name>Sample Document</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&wordcount3=0</url>
</document>
<document>
<name>Sample</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&</url>
</document>
</documents>
It seems the original author has found their solution, but for anyone else who gets here looking to add actual custom headers, if you have access to mod the generated Protocol code you can override GetWebRequest
:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.WebRequest request = base.GetWebRequest(uri);
request.Headers.Add("myheader", "myheader_value");
return request;
}
Make sure you remove the DebuggerStepThroughAttribute
attribute if you want to step into it.
If you really want to do this with jQuery (why?) you should get the DOM window.location object to use its functions:
$(window.location)[0].replace("https://www.google.it");
Note that [0] says to jQuery to use directly the DOM object and not the $(window.location) jQuery object incapsulating the DOM object.
In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.
Example:
select * from table order by [some_column]
offset 10 rows
FETCH NEXT 10 rows only
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
A basic implementation which you'll need to adapt would look something like this:
function insertParam(key, value) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
// kvp looks like ['key1=value1', 'key2=value2', ...]
var kvp = document.location.search.substr(1).split('&');
let i=0;
for(; i<kvp.length; i++){
if (kvp[i].startsWith(key + '=')) {
let pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}
if(i >= kvp.length){
kvp[kvp.length] = [key,value].join('=');
}
// can return this or...
let params = kvp.join('&');
// reload page with new params
document.location.search = params;
}
This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match
the slow regex method I benchmarked against for completions sake (approx +150% slower)
function insertParam2(key,value)
{
key = encodeURIComponent(key); value = encodeURIComponent(value);
var s = document.location.search;
var kvp = key+"="+value;
var r = new RegExp("(&|\\?)"+key+"=[^\&]*");
s = s.replace(r,"$1"+kvp);
if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};
//again, do what you will here
document.location.search = s;
}
If you are on Linux:
sudo service virtualbox restart
Your Call works if it were a Table Valued Function. Since its a scalar function, you need to call it like:
SELECT dbo.fn_HomePageSlider(9, 3025) AS MyResult
jQuery UI Dialog right here: http://jqueryui.com/demos/dialog/
class
to typename
.typename
is illegal for template template arguments, so to be consistent, you should use class
:
template<template<class> typename MyTemplate, class Bar> class Foo { }; // :(
template<template<class> class MyTemplate, class Bar> class Foo { }; // :)
This error message is easy to reproduce.
cmd
, Enter.
On Linux: Ctrl + Alt + t.)npm
and hit Enter to see if Node.js is installed.command not found
, download at https://nodejs.org/en/download/
and install.sudo apt install nodejs
if you prefer.)node thisFileDoesNotExist.js
(and hit Enter).On Windows expect to see something similar to:
internal/modules/cjs/loader.js:969
throw err;
^
Error: Cannot find module [... + a few more lines]
On Linux (Ubuntu 18.04):
module.js:549
throw err;
^
Error: Cannot find module [...]
I have not tried macOS, but would expect something similar there as well.
Note: This might happen for no apparent reason when debugging
in Visual Studio Code.
If you get the error inside VScode, see if the answer by
HappyHands31
is of any help.
Finally, to run Node.js in the terminal without an error, in the Windows terminal (command line) try:
echo console.log('\nHello world!')> hello.js
node hello.js
In the Linux terminal try:
echo "console.log('\nHello world\!\n')"> hello.js
node hello.js
Of course, expect to see the terminal responding:
Hello world!
Dont go crazy I just clean , then rebuild project and error was gone
Use Math.floor()
:
var f = 20.536;
var i = Math.floor(f); // 20
Using Delegation Kotlin we can easily put and get data from shared preferences.
inline fun <reified T> Context.sharedPrefs(key: String) = object : ReadWriteProperty<Any?, T> {
val sharedPrefs by lazy { [email protected]("APP_DATA", Context.MODE_PRIVATE) }
val gson by lazy { Gson() }
var newData: T = (T::class.java).newInstance()
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return getPrefs()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.newData = value
putPrefs(newData)
}
fun putPrefs(value: T?) {
sharedPrefs.edit {
when (value) {
is Int -> putInt(key, value)
is Boolean -> putBoolean(key, value)
is String -> putString(key, value)
is Long -> putLong(key, value)
is Float -> putFloat(key, value)
is Parcelable -> putString(key, gson.toJson(value))
else -> throw Throwable("no such type exist to put data")
}
}
}
fun getPrefs(): T {
return when (newData) {
is Int -> sharedPrefs.getInt(key, 0) as T
is Boolean -> sharedPrefs.getBoolean(key, false) as T
is String -> sharedPrefs.getString(key, "") as T ?: "" as T
is Long -> sharedPrefs.getLong(key, 0L) as T
is Float -> sharedPrefs.getFloat(key, 0.0f) as T
is Parcelable -> gson.fromJson(sharedPrefs.getString(key, "") ?: "", T::class.java)
else -> throw Throwable("no such type exist to put data")
} ?: newData
}
}
//use this delegation in activity and fragment in following way
var ourData by sharedPrefs<String>("otherDatas")
In today's world there is a another answer that is cleaner, and taken from another Stack Overflow answer:
function clicked()
{
var myDiv = $( "#my-div" );
$.post( "someurl.php", {"someData": someData}, $.proxy(doSomething, myDiv), "json" );
}
function doSomething( data )
{
// this will be equal to myDiv now. Thanks to jQuery.proxy().
var $myDiv = this;
// doing stuff.
...
}
Here's the original question and answer: jQuery HOW TO?? pass additional parameters to success callback for $.ajax call?
Here's my solution:
@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>
This resolved my issue if you do not want to make the app available to the public (keeping Status & Review on NO)
I had to sign out of the previous account on the Facebook App and also remove the Facebook account in Settings. Removing just from the Settings will not remove the error because the App itself still has the previous account logged in.
If you have set your Roles as Administrator/Developer/Tester, you can put in that account login info in and it should work then.
So far, I made a solution using Ruby. Place this inside the Product model:
#return first of matching products (id only to minimize memory consumption)
def self.custom_find_by_name(product_name)
@@product_names ||= Product.all(:select=>'id, name')
@@product_names.select{|p| p.name.downcase == product_name.downcase}.first
end
#remember a way to flush finder cache in case you run this from console
def self.flush_custom_finder_cache!
@@product_names = nil
end
This will give me the first product where names match. Or nil.
>> Product.create(:name => "Blue jeans")
=> #<Product id: 303, name: "Blue jeans">
>> Product.custom_find_by_name("Blue Jeans")
=> nil
>> Product.flush_custom_finder_cache!
=> nil
>> Product.custom_find_by_name("Blue Jeans")
=> #<Product id: 303, name: "Blue jeans">
>>
>> #SUCCESS! I found you :)
In Rails 4.02+ according to the docs there is no method like update_all
with 2 arguments. Instead one can use this code:
# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)
# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false
Homebrew does NOT replace stuff in "/usr/bin". You'll just want to put "/usr/local/bin" ahead of "/usr/bin" in your path, then "which python" will give you "/usr/local/bin/python".
Replacing /usr/bin/python (or /usr/bin/ruby) is highly unrecommended.
I disagree with the advice given here - even the reference for the accepted answer concludes:
You can of course use query string parameters with HTTPS, but don’t use them for anything that could present a security problem. For example, you could safely use them to identity part numbers or types of display like ‘accountview’ or ‘printpage’, but don’t use them for passwords, credit card numbers or other pieces of information that should not be publicly available.
So, no they aren't really safe...!
scp remote:"[A-C]/[12].txt" local:
I do not believe there is a "per query" way to do this. (You can use the use
keyword to specify the database - not the schema - but that's technically a separate query as you have to issue the go
command afterward.)
Remember, in SQL server fully qualified table names are in the format:
[database].[schema].[table]
In SQL Server Management Studio you can configure all the defaults you're asking about.
You can set up the default database
on a per-user basis (or in your connection string):
Security > Logins > (right click) user > Properties > General
You can set up the default schema
on a per-user basis (but I do not believe you can configure it in your connection string, although if you use dbo
that is always the default):
Security > Logins > (right click) user > Properties > User Mapping > Default Schema
In short, if you use dbo
for your schema, you'll likely have the least amount of headaches.
You should escape the forward slash too, here is the correct JSON:
[{
"id": "services.html",
"img": "img/SolutionInnerbananer.jpg",
"html": "<h2class=\"fg-white\">AboutUs<\/h2><pclass=\"fg-white\">developing and supporting complex IT solutions.Touchingmillions of lives world wide by bringing in innovative technology <\/p>"
}]
it's possible that conflict with other library, delete node_modules and again npm install.
You can use kubectl delete pods -l dev-lead!=carisa
or what label you have.
The best way to go about it would be to get a SynchronizationContext
from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher
directly). For example:
class MyViewModel
{
private readonly SynchronizationContext _syncContext;
public MyViewModel()
{
// we assume this ctor is called from the UI thread!
_syncContext = SynchronizationContext.Current;
}
// ...
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
_syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
}
}
Let's say you have a url like this http://www.example.com/controller/action/arg1/arg2
If you want to know what are the arguments that are being passed in this url
$param_offset=0;
$params = array_slice($this->uri->rsegment_array(), $param_offset);
var_dump($params);
Output will be:
array (size=2)
0 => string 'arg1'
1 => string 'arg2'
This should work:
override func viewDidLoad() {
super.viewDidLoad()
var button = UIBarButtonItem(title: "YourTitle", style: UIBarButtonItemStyle.Bordered, target: self, action: "goBack")
self.navigationItem.backBarButtonItem = button
}
func goBack()
{
self.navigationController?.popViewControllerAnimated(true)
}
Although it is not recommended since this actually replaces the backButton and it also removed the back arrow and the swipe gesture.
The best presentation for code in documents is in a fixed-width font (as it should appear in an IDE), with either a faint, shaded background or a light border to distinguish the block from other text.
After creating a file you must force the stream to release the resources:
//FSm is stream for creating file on a path//
System.IO.FileStream FS = new System.IO.FileStream(path + fname,
System.IO.FileMode.Create);
pro.CopyTo(FS);
FS.Dispose();
Not the best solution, but here is what I got:
1) Annotate getter you want to initialize with this annotation:
@Retention(RetentionPolicy.RUNTIME)
public @interface Lazy {
}
2) Use this method (can be put in a generic class, or you can change T with Object class) on a object after you read it from database:
public <T> void forceLoadLazyCollections(T entity) {
Session session = getSession().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.refresh(entity);
if (entity == null) {
throw new RuntimeException("Entity is null!");
}
for (Method m : entityClass.getMethods()) {
Lazy annotation = m.getAnnotation(Lazy.class);
if (annotation != null) {
m.setAccessible(true);
logger.debug(" method.invoke(obj, arg1, arg2,...); {} field", m.getName());
try {
Hibernate.initialize(m.invoke(entity));
}
catch (Exception e) {
logger.warn("initialization exception", e);
}
}
}
}
finally {
session.close();
}
}
I use metaclasses and decorators for generate tests. You can check my implementation python_wrap_cases. This library doesn't require any test frameworks.
Your example:
import unittest
from python_wrap_cases import wrap_case
@wrap_case
class TestSequence(unittest.TestCase):
@wrap_case("foo", "a", "a")
@wrap_case("bar", "a", "b")
@wrap_case("lee", "b", "b")
def testsample(self, name, a, b):
print "test", name
self.assertEqual(a, b)
Console output:
testsample_u'bar'_u'a'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test bar
FAIL
testsample_u'foo'_u'a'_u'a' (tests.example.test_stackoverflow.TestSequence) ... test foo
ok
testsample_u'lee'_u'b'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test lee
ok
Also you may use generators. For example this code generate all possible combinations of tests with arguments a__list
and b__list
import unittest
from python_wrap_cases import wrap_case
@wrap_case
class TestSequence(unittest.TestCase):
@wrap_case(a__list=["a", "b"], b__list=["a", "b"])
def testsample(self, a, b):
self.assertEqual(a, b)
Console output:
testsample_a(u'a')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... ok
testsample_a(u'a')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... FAIL
testsample_a(u'b')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... FAIL
testsample_a(u'b')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... ok
You can create a user using MySQL
like this:
CREATE USER 'username'@'servername' IDENTIFIED BY 'password';
and if you want to do that for a specific database, simply you can write in the MySQL
:
GRANT ALL PRIVILEGES ON database_name.*
TO 'username'@'servername'
IDENTIFIED BY 'password';
Note that it's all one sentence, also note that you need to change:
database_name // your database name
username // any name you want to use as username
servername // the name of your server, for example: localhost
password // any text you want to use as user password
Depending on your needs, *ngIf
or [ngClass]="{hide_element: item.hidden}"
where CSS class hide_element
is { display: none; }
*ngIf
can cause issues if you're changing state variables *ngIf
is removing, in those cases using CSS display: none;
is required.
Please be aware that the warning on iTunes Connect does not say anything about the limit being only for over-the-air delivery. It would be preferable if the warning mentioned this.
This worked for me
<p:column headerText="name" style="width:20px;"/>
The suggestion to use .split(/[ ,]+/)
is good, but with natural sentences sooner or later you'll end up getting empty elements in the array. e.g. ['foo', '', 'bar']
.
Which is fine if that's okay for your use case. But if you want to get rid of the empty elements you can do:
var str = 'whatever your text is...';
str.split(/[ ,]+/).filter(Boolean);
The best way is to interact with the axes
object directly
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')
plt.show()
Semantically speaking, wouldn't it be best to use an ordered or unordered list and then style it appropriately using CSS?
<ul id="[UL_ID]">
<li><img src="[image1_url]" alt="img1" /></li>
<li><img src="[image2_url]" alt="img2" /></li>
<li><img src="[image3_url]" alt="img3" /></li>
<li><img src="[image4_url]" alt="img4" /></li>
<li><img src="[image5_url]" alt="img5" /></li>
<li><img src="[image6_url]" alt="img6" /></li>
</ul>
Using CSS, you'll be able to style this whatever way you want and remove the whitespace imbetween the books.
To deserialize the response need to use HashMap
:
String resp = ...//String output from your source
Gson gson = new GsonBuilder().create();
gson.fromJson(resp,TheResponse.class);
class TheResponse{
HashMap<String,Song> songs;
}
class Song{
String id;
String pos;
}
The simplest solution would be (using 'upstream
' as the remote name referencing the original repo forked):
git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master
git push origin master --force
(Similar to this GitHub page, section "What should I do if I’m in a bad situation?")
Be aware that you can lose changes done on the master
branch (both locally, because of the reset --hard
, and on the remote side, because of the push --force
).
An alternative would be, if you want to preserve your commits on master
, to replay those commits on top of the current upstream/master
.
Replace the reset part by a git rebase upstream/master
. You will then still need to force push.
See also "What should I do if I’m in a bad situation?"
A more complete solution, backing up your current work (just in case) is detailed in "Cleanup git master branch and move some commit to new branch".
See also "Pull new updates from original GitHub repository into forked GitHub repository" for illustrating what "upstream
" is.
Note: recent GitHub repos do protect the master
branch against push --force
.
So you will have to un-protect master
first (see picture below), and then re-protect it after force-pushing).
Note: on GitHub specifically, there is now (February 2019) a shortcut to delete forked repos for pull requests that have been merged upstream.
Encounter the same error today and solved it with:
npm i --save-dev @types/es6-promise
Update:
add:
import {Promise} from 'es6-promise'
$('.formData').attr('value','YOUR_VALUE')
sed ':a;/^\n*$/{$d;N;};/\n$/ba' file
This is sort of covered by the various responses above, but the first time I read this article I missed an important fact, which led to a minor bug in my code...
Session.Clear()
will CLEAR the values of all the keys but will NOT cause the session end event to fire.
Session.Abandon()
will NOT clear the values on the current request. IF another page is requested, the values will be gone for that one. However, abandon WILL throw the event.
So, in my case (and perhaps in yours?), I needed Clear()
followed by Abandon()
.
You might need to do some checking. You cannot safely convert factors directly to numeric. as.character
must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor
then coerce to numeric as necessary.
df1[] <- lapply(df1, function(x) {
if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
# a b
# "numeric" "numeric"
Assuming that you have a data frame called students
, you can select individual rows or columns using the bracket syntax, like this:
students[1,2]
would select row 1 and column 2, the result here would be a single cell.students[1,]
would select all of row 1, students[,2]
would select all of column 2.If you'd like to select multiple rows or columns, use a list of values, like this:
students[c(1,3,4),]
would select rows 1, 3 and 4, students[c("stu1", "stu2"),]
would select rows named stu1
and stu2
.Hope I could help.
The following seems to work:
import datetime
print (datetime.datetime.now().strftime("%y"))
The datetime.data object that it wants is on the "left" of the dot rather than the right. You need an instance of the datetime to call the method on, which you get through now()
Cache.delete() can be used for new chrome, firefox and opera.
I believe the action name is "workbench.action.quickOpen".
Add your dependencies like mongodb,web,jpa. Delete/clear the remainings.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
That should work via HTTPRewriteModule.
Example rewrite from www.example.com to example.com:
server {
server_name www.example.com;
rewrite ^ http://example.com$request_uri? permanent;
}
I would probably use:
for x in xyz:
if x not in a:
print x...
Something neat...
I wanted to look up an "Exact Town ID" based on a "Partial Exact Town Name" BUT although I had the entire town name I was searching against a list of Partial town names. So I First found the "Exact Town Name" based on the part (which was actually a partial name since the "master list" is partial names unfortunately)... THEN searched for the "Exact Town ID" based on that Exact town name SO all my Vlookups/Index/Match-whatevers....were set to EXACT ....
=INDEX(county_cheatsheet!$E$1:$E$516,MATCH(VLOOKUP(LEFT(D3,3)&"*",county_cheatsheet!$E$1:$E$516,1,FALSE),county_cheatsheet!$E$1:E$516,0))
The lookup of the "first three letters of the partial town name against the list of partial town names is the MATCH(VLOOKUP(LEFT(D3,3)&"*" part
Based on Haim's answer I created a PHP code to test and display all the differences between two databases. This will also display if a table is present in source or test databases. You have to change with your details the <> variables content.
<?php
$User = "<DatabaseUser>";
$Pass = "<DatabasePassword>";
$SourceDB = "<SourceDatabase>";
$TestDB = "<DatabaseToTest>";
$link = new mysqli( "p:". "localhost", $User, $Pass, "" );
if ( mysqli_connect_error() ) {
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
mysqli_set_charset( $link, "utf8" );
mb_language( "uni" );
mb_internal_encoding( "UTF-8" );
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';
$SourceDB_Content = query( $link, $sQuery );
if ( !is_array( $SourceDB_Content) ) {
echo "Table $SourceDB cannot be accessed";
exit(0);
}
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';
$TestDB_Content = query( $link, $sQuery );
if ( !is_array( $TestDB_Content) ) {
echo "Table $TestDB cannot be accessed";
exit(0);
}
$SourceDB_Tables = array();
foreach( $SourceDB_Content as $item ) {
$SourceDB_Tables[] = $item["TABLE_NAME"];
}
$TestDB_Tables = array();
foreach( $TestDB_Content as $item ) {
$TestDB_Tables[] = $item["TABLE_NAME"];
}
//var_dump( $SourceDB_Tables, $TestDB_Tables );
$LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
$NoOfDiscrepancies = 0;
echo "
<table border='1' width='100%'>
<tr>
<td>Table</td>
<td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
<td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
<td>Test result</td>
<tr>
";
foreach( $LookupTables as $table ) {
$FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
$FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
echo "
<tr>
<td>$table</td>
<td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td>
<td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>
<td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>
</tr>
";
}
echo "
</table>
<br><br>
No of discrepancies found: $NoOfDiscrepancies
";
function query( $link, $q ) {
$result = mysqli_query( $link, $q );
$errors = mysqli_error($link);
if ( $errors > "" ) {
echo $errors;
exit(0);
}
if( $result == false ) return false;
else if ( $result === true ) return true;
else {
$rset = array();
while ( $row = mysqli_fetch_assoc( $result ) ) {
$rset[] = $row;
}
return $rset;
}
}
function compareTables( $source, $test, $table ) {
global $link;
global $NoOfDiscrepancies;
$sQuery = "
SELECT column_name,ordinal_position,data_type,column_type FROM
(
SELECT
column_name,ordinal_position,
data_type,column_type,COUNT(1) rowcount
FROM information_schema.columns
WHERE
(
(table_schema='$source' AND table_name='$table') OR
(table_schema='$test' AND table_name='$table')
)
AND table_name IN ('$table')
GROUP BY
column_name,ordinal_position,
data_type,column_type
HAVING COUNT(1)=1
) A;
";
$result = query( $link, $sQuery );
$data = "";
if( is_array( $result ) && count( $result ) > 0 ) {
$NoOfDiscrepancies++;
$data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";
foreach( $result as $item ) {
$data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";
}
$data .= "</table>";
return $data;
}
else {
return "Checked but no discrepancies found!";
}
}
?>
As the plural in getElementsByName()
implies, does it always return list of elements that have this name. So when you have an input element with that name:
<input type="text" name="Tue">
And it is the first one with that name, you have to use document.getElementsByName('Tue')[0]
to get the first element of the list of elements with this name.
Beside that are properties case sensitive and the correct spelling of the value property is .value
.
PUT http://{rm http address:port}/ws/v1/cluster/apps/{appid}/state
{
"state":"KILLED"
}
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
Should this not work?
echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk '{print $1}'
Apache part - enabling you to open https://localhost/xyz
There is the config file xampp/apache/conf/extra/httpd-ssl.conf which contains all the ssl specific configuration. It's fairly well documented, so have a read of the comments and take look at http://httpd.apache.org/docs/2.2/ssl/.
The files starts with <IfModule ssl_module>
, so it only has an effect if the apache has been started with its mod_ssl module.
Open the file xampp/apache/conf/httpd.conf in an editor and search for the line
#LoadModule ssl_module modules/mod_ssl.so
remove the hashmark, save the file and re-start the apache. The webserver should now start with xampp's basic/default ssl confguration; good enough for testing but you might want to read up a bit more about mod_ssl in the apache documentation.
PHP part - enabling adldap to use ldap over ssl
adldap needs php's openssl extension to use "ldap over ssl" connections. The openssl extension ships as a dll with xampp. You must "tell" php to load this dll, e.g. by having an extension=nameofmodule.dll
in your php.ini
Run
echo 'ini: ', get_cfg_var('cfg_file_path');
It should show you which ini file your php installation uses (may differ between the php-apache-module and the php-cli version).
Open this file in an editor and search for
;extension=php_openssl.dll
remove the semicolon, save the file and re-start the apache.
The best way to handle this is using some kind of URL re-writing. In this way, you can have clean restful URLs, and NOT with any extensions i.e abc.com/welcom/register as opposed to abc.com/welcome/resister.html
I use Tuckey URL which is pretty cool.
It's got instructions on how to set up your web app.I have set it up with my Spring MVC web app. Of course, everything was fine until I wanted to use annotations for Spring 3 validations like @Email
or @Null
for domain objects.
When I add the Spring mvc directives:
< mvc:annotation-driven />
< mvc:default-servlet-handler />
.. it breaks the good ol Tuckey code. Apparently, < mvc:default-servlet-handler />
replaces Tuckey, which I'm still trying to solve.
You can use the JFileChooser class, check this example.
function function_one()_x000D_
{_x000D_
alert("The function called 'function_one' has been called.")_x000D_
//Here u would like to call function_two._x000D_
function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
Either way works, but many places have coding standards in place that will guide the developer one way or the other. If such a policy is not in place, just follow your heart. One thing, though, it REALLY helps the readability of the code if you do use it. especially if you are not following a naming convention on class-level variable names.
For me it was a mistake in the pom.xml
- I'd set <scope>provided<scope>
on my dependencies, and this was making them not get copied during the mvn package
stage.
My symptoms were the error message the OP posted, and that the jars were not included in the WEB-INF/lib path inside the .war after package was run. When I removed the scope, the jars appeared in the output, and all loads up fine now.
You can do this:
create type number_tab is table of number;
select * from table (number_tab(1,2,3,4,5,6));
The column is given the name COLUMN_VALUE by Oracle, so this works too:
select column_value from table (number_tab(1,2,3,4,5,6));
We can do like below:
const item= {
image: require("../../assets/dashboard/project1.jpeg"),
location: "Chennai",
status: 1,
projectId: 1
}
<Image source={item.image} style={[{ width: 150, height: 150}]} />
Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.
I think you mean to put the rolling of the random a,b,c, etc within the loop:
a = None # initialise
while not (a in winning_numbers):
# keep rolling an a until you get one not in winning_numbers
a = random.randint(1,30)
winning_numbers.append(a)
Otherwise, a
will be generated just once, and if it is in winning_numbers
already, it won't be added. Since the generation of a
is outside the while
(in your code), if a
is already in winning_numbers
then too bad, it won't be re-rolled, and you'll have one less winning number.
That could be what causes your error in if guess[i] == winning_numbers[i]
. (Your winning_numbers
isn't always of length 5).
To add to this, I've been doing a diagram application, and initially started out with canvas. The diagram consists of many nodes, and they can get quite big. The user can drag elements in the diagram around.
What I found was that on my Mac, for very large images, SVG is superior. I have a MacBook Pro 2013 13" Retina, and it runs the fiddle below quite well. The image is 6000x6000 pixels, and has 1000 objects. A similar construction in canvas was impossible to animate for me when the user was dragging objects around in the diagram.
On modern displays you also have to account for different resolutions, and here SVG gives you all of this for free.
Fiddle: http://jsfiddle.net/knutsi/PUcr8/16/
Fullscreen: http://jsfiddle.net/knutsi/PUcr8/16/embedded/result/
var wiggle_factor = 0.0;
nodes = [];
// create svg:
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('style', 'border: 1px solid black');
svg.setAttribute('width', '6000');
svg.setAttribute('height', '6000');
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink",
"http://www.w3.org/1999/xlink");
document.body.appendChild(svg);
function makeNode(wiggle) {
var node = document.createElementNS("http://www.w3.org/2000/svg", "g");
var node_x = (Math.random() * 6000);
var node_y = (Math.random() * 6000);
node.setAttribute("transform", "translate(" + node_x + ", " + node_y +")");
// circle:
var circ = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circ.setAttribute( "id","cir")
circ.setAttribute( "cx", 0 + "px")
circ.setAttribute( "cy", 0 + "px")
circ.setAttribute( "r","100px");
circ.setAttribute('fill', 'red');
circ.setAttribute('pointer-events', 'inherit')
// text:
var text = document.createElementNS("http://www.w3.org/2000/svg", "text");
text.textContent = "This is a test! ÅÆØ";
node.appendChild(circ);
node.appendChild(text);
node.x = node_x;
node.y = node_y;
if(wiggle)
nodes.push(node)
return node;
}
// populate with 1000 nodes:
for(var i = 0; i < 1000; i++) {
var node = makeNode(true);
svg.appendChild(node);
}
// make one mapped to mouse:
var bnode = makeNode(false);
svg.appendChild(bnode);
document.body.onmousemove=function(event){
bnode.setAttribute("transform","translate(" +
(event.clientX + window.pageXOffset) + ", " +
(event.clientY + window.pageYOffset) +")");
};
setInterval(function() {
wiggle_factor += 1/60;
nodes.forEach(function(node) {
node.setAttribute("transform", "translate("
+ (Math.sin(wiggle_factor) * 200 + node.x)
+ ", "
+ (Math.sin(wiggle_factor) * 200 + node.y)
+ ")");
})
},1000/60);
You can use jquery numeric for numbers.
The current version does allow what you're looking for but someone has changed the code a little bit and it works:
HTML
<input class="numeric" type="text" />
Javascript
$(".numeric").numeric({ decimal : ".", negative : false, scale: 3 });
This is the whole source.
And I've prepared this fiddle so you can see how it works.
You can by setting selectedIndex
to -1
using .prop
: http://jsfiddle.net/R9auG/.
For older jQuery versions use .attr
instead of .prop
: http://jsfiddle.net/R9auG/71/.
First reset.css
is the worst library you can use, because it removes the standard structure of HTML and displays everything you write just as text, after assigning the values of margin padding and other attributes to 0
. So for example you will find that <H1>
, will be the same as <H6>
.
On the other hand Normalize.css
uses the standard structure and also fixes almost all the errors existing in it. For example it fixes the problem with showing a form from one browser to another. Normalize fixes this by modifying this features so your elements will be shown the same on all browsers.
This answer pertains to slow Gradle build speeds for Windows 10 after you've already gotten the Xmx and Xms memory settings straightened out.
Windows Defender
As far as Windows Defender is concerned it's simply not enough to add folders / files to the Windows Defender exclusion list via "Files" or "Folders".
You must add directories pertaining to Android Studio / Gradle / Java (embedded JDK or Oracle JDK) as "Process" exclusions to Windows Defender :
This obviously comes with security implications.
The following describes more details pertaining to using a "Process" exclusion in Windows Defender (as opposed to adding a simple "File" or "Folder" exclusion) :
A file name with full path causes the particular binary file to be excluded, i.e. any files it touches, regardless of where the file is located, will not be scanned by Windows Defender. A file name without any path causes any binary file with this file name to be excluded regardless of its location. A path followed by a "*" (e.g. c:\my\private\tools*) causes any binaries under this path to be excluded. Any files touched by these processes will be excluded. This is different from a path exclusion, where files touched by any process under the excluded path is excluded.
The key here being....adding these exclusions as "Process" type exclusions takes into account "files the binary touches" as opposed to manually finding and excluding every file / folder that is generated by Android Studio / Gradle.
Windows File Indexing
Windows file indexing seems to also slow down Gradle builds. Turn off Windows File Indexing for the directories used by Gradle / Android Studio.
Here are my "Windows File Indexing" and "Windows Defender Process" exclusions :
C:\Program Files\Android\*
C:\Users\<yourUserAcct>\.android\*
C:\Users\<yourUserAcct>\.AndroidStudio3.0\*
C:\Users\<yourUserAcct>\.gradle\*
C:<pathToYourAndroidStudioProjectFolder>
$ man tr
NAME
tr - translate or delete characters
SYNOPSIS
tr [OPTION]... SET1 [SET2]
DESCRIPTION
Translate, squeeze, and/or delete characters from standard
input, writing to standard output.
In order to wipe all whitespace including newlines you can try:
cat file.txt | tr -d " \t\n\r"
You can also use the character classes defined by tr (credits to htompkins comment):
cat file.txt | tr -d "[:space:]"
For example, in order to wipe just horizontal white space:
cat file.txt | tr -d "[:blank:]"
If you would like the new data frame to have the same index and columns as an existing data frame, you can just multiply the existing data frame by zero:
df_zeros = df * 0
You Can Follow These Steps.
pip install jupyterthemes
or pip install --upgrade jupyterthemes
to upgrade to latest version of theme.jt -l
jt-t <themename>
for example jt -t solarizedl
I believe you are looking for:
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
I'm on XP. I've installed MySQL-5.6.10 manually from .zip
, no Windows auto-installer provided by MySQL site. The /bin
directory of my MySQL is in my PATH. So I start the server with mysqld --console
command, like this:
C:\Documents and Settings\User>mysqld --console
2013-04-12 14:39:19 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_times
tamp server option (see documentation for more details).
From now on it is running. And that cmd window is occupied. I open and use another one.
I've tried to use the answers from above but none of them can stop the server. Only errors are throw. So I stop the server with mysqladmin -u root shutdown
on the other cmd window or with Ctrl + C
on the cmd window it is running in. The latter works not so good as the former, sometimes I have to click Ctrl + C
twice or more.
The log of the shutdown process is like this:
2013-04-12 17:55:29 3968 [Note] Giving 0 client threads a chance to die gracefully
2013-04-12 17:55:29 3968 [Note] Event Scheduler: Purging the queue. 0 events
2013-04-12 17:55:29 3968 [Note] Shutting down slave threads
2013-04-12 17:55:29 3968 [Note] Forcefully disconnecting 0 remaining clients
2013-04-12 17:55:29 3968 [Note] Binlog end
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'partition'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_INSERTED'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_METRICS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMPMEM'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_CMP'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_LOCKS'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'INNODB_TRX'
2013-04-12 17:55:29 3968 [Note] Shutting down plugin 'InnoDB'
2013-04-12 17:55:29 3968 [Note] InnoDB: FTS optimize thread exiting.
2013-04-12 17:55:29 3968 [Note] InnoDB: Starting shutdown...
2013-04-12 17:55:30 3968 [Note] InnoDB: Shutdown completed; log sequence number 1719777
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'BLACKHOLE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'ARCHIVE'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MRG_MYISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MyISAM'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'MEMORY'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'CSV'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'sha256_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_old_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'mysql_native_password'
2013-04-12 17:55:30 3968 [Note] Shutting down plugin 'binlog'
2013-04-12 17:55:30 3968 [Note] mysqld: Shutdown complete
And I still don't know if it is 100% right way to shutdown the server, but it works :)
This can also happen while running the project in visual studio if your IIS Express has/is hosting an old/different project using the same port assignment.
To fix this, you can change the port assignment for this project or close IIS Express.
You can do like this:
#mydiv {
position: fixed;
height: 30px;
top: 0;
left: 0;
width: 100%;
}
This will create a div
, that will be fixed on top of your screen. - fixed
You should apply a "clearfix" to clear the parent element. Next thing, the h4 for the header title, extend all the way across the header, so after you apply clearfix, it will push down the child element causing the header div to have a larger height.
Here is a fix, just replace it with your code.
<div class="panel-heading clearfix">
<b>Panel header</b>
<div class="btn-group pull-right">
<a href="#" class="btn btn-default btn-sm">## Lock</a>
<a href="#" class="btn btn-default btn-sm">## Delete</a>
<a href="#" class="btn btn-default btn-sm">## Move</a>
</div>
</div>
Editted on 12/22/2015 - added .clearfix to heading div
Try this.... Replace body with parent selector
$('body').on('click', '#my-button', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
you must change Territory and click on save, after one minute your app will be available. No need to Remove from sale
Use list(str) to break into chars then import string and use string.ascii_uppercase to compare against.
Check the string module: http://docs.python.org/library/string.html
#!/bin/bash
set -e
# Settings
user=xxx
pass=xxx
dir=xxx
repo_src=xxx
repo_trg=xxx
src_branch=xxx
repo_base_url=https://$user:[email protected]/$user
repo_src_url=$repo_base_url/$repo_src.git
repo_trg_url=$repo_base_url/$repo_trg.git
echo "Clone Source..."
git clone --depth 1 -b $src_branch $repo_src_url $dir
echo "CD"
cd ./$dir
echo "Remove GIT"
rm -rf .git
echo "Init GIT"
git init
git add .
git commit -m "Initial Commit"
git remote add origin $repo_trg_url
echo "Push..."
git push -u origin master
You have to do bulk insert with format file:
BULK INSERT Employee FROM 'path\tempFile.csv '
WITH (FORMATFILE = 'path\tempFile.fmt');
where format file (tempFile.fmt) looks like this:
11.0
2
1 SQLCHAR 0 50 "\t" 2 Name SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 50 "\r\n" 3 Address SQL_Latin1_General_CP1_CI_AS
more details here - http://msdn.microsoft.com/en-us/library/ms179250.aspx
Also, it is very likely, that problem with proxy settings.
Any who didn't overcome Tomact starting problrem, - try in NetBeans choose No Proxy in the Tools -> Options -> General tab.
It helped me.
One has pretty much control on which information from the traceback to be displayed/logged when catching exceptions.
The code
with open("not_existing_file.txt", 'r') as text:
pass
would produce the following traceback:
Traceback (most recent call last):
File "exception_checks.py", line 19, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
As others already mentioned, you can catch the whole traceback by using the traceback module:
import traceback
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
traceback.print_exc()
This will produce the following output:
Traceback (most recent call last):
File "exception_checks.py", line 19, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
You can achieve the same by using logging:
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
logger.error(exception, exc_info=True)
Output:
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
File "exception_checks.py", line 27, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
You might not be interested in the whole traceback, but only in the most important information, such as Exception name and Exception message, use:
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
print("Exception: {}".format(type(exception).__name__))
print("Exception message: {}".format(exception))
Output:
Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'
CASE
is more like a switch statement. It has two syntaxes you can use. The first lets you use any compare statements you want:
CASE
WHEN user_role = 'Manager' then 4
WHEN user_name = 'Tom' then 27
WHEN columnA <> columnB then 99
ELSE -1 --unknown
END
The second style is for when you are only examining one value, and is a little more succinct:
CASE user_role
WHEN 'Manager' then 4
WHEN 'Part Time' then 7
ELSE -1 --unknown
END
If you know the arrays are of the same size it is provably faster to sort then compare
Arrays.sort(array1)
Arrays.sort(array2)
return Arrays.equals(array1, array2)
If you do not want to change the order of the data in the arrays then do a System.arraycopy
first.
It require to include Content-Type:application/json
in web api request header section when not mention any content then by default it is Content-Type:text/plain
passes to request.
Best way to test api on postman tool.
Maven can be considered as complete project development tool not just build tool like Ant. You should use Eclipse IDE with maven plugin to fix all your problems.
Here are few advantages of Maven, quoted from the Benefits of using Maven page:
Henning
- quick project setup, no complicated build.xml files, just a POM and go
- all developers in a project use the same jar dependencies due to centralized POM.
- getting a number of reports and metrics for a project "for free"
- reduce the size of source distributions, because jars can be pulled from a central location
Emmanuel Venisse
- a lot of goals are available so it isn't necessary to develop some specific build process part contrary to ANT we can reuse existing ANT tasks in build process with antrun plugin
Jesse Mcconnell
- Promotes modular design of code. by making it simple to manage mulitple projects it allows the design to be laid out into muliple logical parts, weaving these parts together through the use of dependency tracking in pom files.
- Enforces modular design of code. it is easy to pay lipservice to modular code, but when the code is in seperate compiling projects it is impossible to cross pollinate references between modules of code unless you specifically allow for it in your dependency management... there is no 'I'll just do this now and fix it later' implementations.
- Dependency Management is clearly declared. with the dependency management mechanism you have to try to screw up your jar versioning...there is none of the classic problem of 'which version of this vendor jar is this?' And setting it up on an existing project rips the top off of the existing mess if it exists when you are forced to make 'unknown' versions in your repository to get things up and running...that or lie to yourself that you know the actual version of ABC.jar.
- strong typed life cycle there is a strong defined lifecycle that a software system goes thru from the initiation of a build to the end... and the users are allowed to mix and match their system to the lifecycle instead of cobble together their own lifecycle.. this has the additional benefit of allowing people to move from one project to another and speak using the same vocabulary in terms of software building
Vincent Massol
- Greater momentum: Ant is now legacy and not moving fast ahead. Maven is forging ahead fast and there's a potential of having lots of high-value tools around Maven (CI, Dashboard project, IDE integration, etc).
Here is a util function modified (another post on stack) for get and post both. Make Util.js file.
let cachedData = null;
let cachedPostData = null;
const postServiceData = (url, params) => {
console.log('cache status' + cachedPostData );
if (cachedPostData === null) {
console.log('post-data: requesting data');
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then(response => {
cachedPostData = response.json();
return cachedPostData;
});
} else {
console.log('post-data: returning cachedPostData data');
return Promise.resolve(cachedPostData);
}
}
const getServiceData = (url) => {
console.log('cache status' + cachedData );
if (cachedData === null) {
console.log('get-data: requesting data');
return fetch(url, {})
.then(response => {
cachedData = response.json();
return cachedData;
});
} else {
console.log('get-data: returning cached data');
return Promise.resolve(cachedData);
}
};
export { getServiceData, postServiceData };
Usage like below in another component
import { getServiceData, postServiceData } from './../Utils/Util';
constructor(props) {
super(props)
this.state = {
datastore : []
}
}
componentDidMount = () => {
let posturl = 'yoururl';
let getdataString = { name: "xys", date:"today"};
postServiceData(posturl, getdataString)
.then(items => {
this.setState({ datastore: items })
console.log(items);
});
}
#define ID_LEN 5
char **orderedIds;
int i;
int variableNumberOfElements = 5; /* Hard coded here */
orderedIds = (char **)malloc(variableNumberOfElements * (ID_LEN + 1) * sizeof(char));
..
Another solution I found to work is to set a mousewheel handler on the inside container and make sure it doesn't propagate by setting its last parameter to false and stopping the event bubble.
document.getElementById('content').addEventListener('mousewheel',function(evt){evt.cancelBubble=true; if (evt.stopPropagation) evt.stopPropagation},false);
Scroll works fine in the inner container, but the event doesn't propagate to the body and so it does not scroll. This is in addition to setting the body properties overflow:hidden and height:100%.
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
StringBuilder cmd = new StringBuilder();
cmd.append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java ");
for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
cmd.append(jvmArg + " ");
}
cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" ");
cmd.append(Main.class.getName()).append(" ");
for (String arg : args) {
cmd.append(arg).append(" ");
}
Runtime.getRuntime().exec(cmd.toString());
System.exit(0);
}
}
Dedicated to all those who say it is impossible.
This program collects all information available to reconstruct the original commandline. Then, it launches it and since it is the very same command, your application starts a second time. Then we exit the original program, the child program remains running (even under Linux) and does the very same thing.
WARNING: If you run this, be aware that it never ends creating new processes, similar to a fork bomb.
You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.
You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.
If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.
In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.
If you are looking for each command separately
To export all the output of the command prompt in text files. Simply follow the following syntax.
C:> [syntax] >file.txt
The above command will create result of syntax in file.txt. Where new file.txt will be created on the current folder that you are in.
For example,
C:Result> dir >file.txt
To copy the whole session, Try this:
Copy & Paste a command session as follows:
1.) At the end of your session, click the upper left corner to display the menu.
Then select.. Edit -> Select all
2.) Again, click the upper left corner to display the menu.
Then select.. Edit -> Copy
3.) Open your favorite text editor and use Ctrl+V or your normal
Paste operation to paste in the text.
as per @anaximander s answer but your signup action should look more like
[HttpPost]
public ActionResult SignUp(Account account)
{
if(ModelState.IsValid){
//do something with account
return RedirectToAction("Index");
}
return View("SignUp");
}
It depends on how you set the defaults for the dropdown. Use selected value, but you have to set the selected value. For instance, I populate the datasource with the name and id field for the table/list. I set the selected value to the id field and the display to the name. When I select, I get the id field. I use this to search a relational table and find an entity/record.
Add these 2 lines
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
So you have:
// Do any additional setup after loading the view, typically from a nib.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
That will remove all the spaces and give you a grid layout:
If you want the first column to have a width equal to the screen width then add the following function:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if indexPath.row == 0
{
return CGSize(width: screenWidth, height: screenWidth/3)
}
return CGSize(width: screenWidth/3, height: screenWidth/3);
}
Grid layout will now look like (I've also added a blue background to first cell):
It looks like you have accidentally declared DataType
as an array rather than as a string.
Change line 3 to:
Dim DataType As String = myTableData.Rows(i).Item(1)
That should work.
before_filter/before_action: means anything to be executed before any action executes.
Both are same. they are just alias for each other as their behavior is same.
No. Pylint doesn't currently let you discriminate between doc-string warnings.
However, you can use Flake8 for all Python code checking along with the doc-string extension to ignore this warning.
Install the doc-string extension with pip (internally, it uses pydocstyle).
pip install flake8_docstrings
You can then just use the --ignore D100
switch. For example, flake8 file.py --ignore D100
Here are the ones I can find:
Sources:
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
I just encountered this problem on a virgin install with a system that has a bad clock battery (when I turn off the power, it resets the date/time. Syncing to time.windows.com again allowed me to run VS2010 successfully.
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
You probably need to some plugin like Jquery multiselect dropdown. Here is a demo.
Also you need to close your option tags like this:
<select name="test" multiple>
<option>123</option>
<option>456</option>
<option>789</option>
</select>
I followed these steps and it worked perfectly
Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r
Use the SETX command (note the 'x' suffix) to set variables that persist after the cmd window has been closed.
For example, to set an env var "foo" with value of "bar":
setx foo bar
Though it's worth reading the 'notes' that are displayed if you print the usage (setx /?
), in particular:
2) On a local system, variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window.
3) On a remote system, variables created or modified by this tool will be available at the next logon session.
In PowerShell, the [Environment]::SetEnvironmentVariable command.
function doSomething(){
if ($(this).hasClass('clickedTag')){
// code here
}
else {
// and here
}
}
$('.tag1').click(doSomething);
$('.tag2').click(doSomething);
// or, simplifying further
$(".tag1, .tag2").click(doSomething);
This will also work:
?$(".tag1, .tag2").click(function(){
alert("clicked");
});?
I prefer a separate function (approach #1) if there is a chance that logic will be reused.
See also How can I select an element with multiple classes? for handling multiple classes on the same item.
Off the top of my head, one way would be to grab all previous elements and count them.
$('td').click(function(){
var colIndex = $(this).prevAll().length;
var rowIndex = $(this).parent('tr').prevAll().length;
});
I was having tons of trouble with the return value, so I ended up just selecting stuff at the end.
The solution was just to select the result at the end and return the query result in your functinon.
In my case I was doing an exists check:
IF (EXISTS (SELECT RoleName FROM dbo.Roles WHERE @RoleName = RoleName))
SELECT 1
ELSE
SELECT 0
Then
using (SqlConnection cnn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "RoleExists";
return (int) cmd.ExecuteScalar()
}
You should be able to do the same thing with a string value instead of an int.
I like Lucas answer, but I would like to elaborate it a bit. There is a built-in function in termios.h
named cfmakeraw()
which man describes as:
cfmakeraw() sets the terminal to something like the "raw" mode of the
old Version 7 terminal driver: input is available character by
character, echoing is disabled, and all special processing of
terminal input and output characters is disabled. [...]
This basically does the same as what Lucas suggested and more, you can see the exact flags it sets in the man pages: termios(3).
int c = 0;
static struct termios oldTermios, newTermios;
tcgetattr(STDIN_FILENO, &oldTermios);
newTermios = oldTermios;
cfmakeraw(&newTermios);
tcsetattr(STDIN_FILENO, TCSANOW, &newTermios);
c = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldTermios);
switch (c) {
case 113: // q
printf("\n\n");
exit(0);
break;
case 105: // i
printf("insert\n");
break;
default:
break;
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
You need to use the select new
LINQ keyword to explicitly convert your tbcourse
entity into the custom type course
. Example of select new
:
var q = from o in db.Orders
where o.Products.ProductName.StartsWith("Asset") &&
o.PaymentApproved == true
select new { name = o.Contacts.FirstName + " " +
o.Contacts.LastName,
product = o.Products.ProductName,
version = o.Products.Version +
(o.Products.SubVersion * 0.1)
};
You should use the secondary constructor for File
to specify the directory in which it is to be symbolically created. This is important because the answers that say to create a file by prepending the directory name to original name, are not as system independent as this method.
Sample code:
String dirName = /* something to pull specified dir from input */;
String fileName = "test.txt";
File dir = new File (dirName);
File actualFile = new File (dir, fileName);
/* rest is the same */
Hope it helps.
$("input").on("keydown",function search(e) {
if(e.keyCode == 13) {
alert($(this).val());
}
});
jsFiddle example : http://jsfiddle.net/NH8K2/1/
in simple word your site has been blocked to access network. may be you have automated some script and it caused your whole website to be blocked. the better way to resolve this is contact that site and tell your issue. if issue is genuine they may consider unblocking
You could do it like this:
iterations = 10
variables = 2
output <- matrix(ncol=variables, nrow=iterations)
for(i in 1:iterations){
output[i,] <- runif(2)
}
output
and then turn it into a data.frame
output <- data.frame(output)
class(output)
what this does:
Careful with the eval, the JSON specs http://json.org/js.html recommend something like
var myObject = eval('(' + myJSONtext + ')');
And there may be some more gotchas. There is a plugin for jQuery that will take care of it, i guess:
Try this:
MessageBox.Show("Some text", "Some title",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Almost perfect solution, that automatically scales to dimensions of an element would be usage of CSS3 linear-gradient connected with calc() as shown below. Main drawback is of course compatibility. Code below works in Firefox 25 and Explorer 10 and 11, but in Chrome (I've tested v30 and v32 dev) there are some subtle problems with lines disappearing if they are too narrow. Moreover disappearing depends on the box dimensions – style below works for div { width: 100px; height: 100px}
, but fails for div { width: 200px; height: 200px}
for which in my tests 0.8px
in calculations needs to be replaced with at least 1.1048507095px
for diagonals to be shown and even then line rendering quality is quite poor. Let's hope this Chrome bug will be solved soon.
.crossed {_x000D_
background: _x000D_
linear-gradient(to top left,_x000D_
rgba(0,0,0,0) 0%,_x000D_
rgba(0,0,0,0) calc(50% - 0.8px),_x000D_
rgba(0,0,0,1) 50%,_x000D_
rgba(0,0,0,0) calc(50% + 0.8px),_x000D_
rgba(0,0,0,0) 100%),_x000D_
linear-gradient(to top right,_x000D_
rgba(0,0,0,0) 0%,_x000D_
rgba(0,0,0,0) calc(50% - 0.8px),_x000D_
rgba(0,0,0,1) 50%,_x000D_
rgba(0,0,0,0) calc(50% + 0.8px),_x000D_
rgba(0,0,0,0) 100%);_x000D_
}
_x000D_
<textarea class="crossed"></textarea>
_x000D_
press Cntl + Shift + C
select the element you wish to get its XPath
by clicking on it
right click
on the highlighted part in the console
copy
-> copy XPath
I think we will have to wait a couple of years more to see more progress. However, there are now more frameworks and tools available:
Here a list of 5 options:
At first it seems as if JNZ means jump if not Zero (0), as in jump if zero flag is 1/set.
But in reality it means Jump (if) not Zero (is set).
If 0 = not set and 1 = set then just remember:
JNZ Jumps if the zero flag is not set (0)
Express version:
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
Optional parameter are very much handy, you can declare and use them easily using express:
app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
console.log("category Id: "+req.params.cId);
console.log("product ID: "+req.params.pId);
if (req.params.batchNo){
console.log("Batch No: "+req.params.batchNo);
}
});
In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'
Now I can call with only categoryId and productId or with all three-parameter.
http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987
GNU GetOpt.
A simple example using GetOpt:
// C/C++ Libraries:
#include <string>
#include <iostream>
#include <unistd.h>
// Namespaces:
using namespace std;
int main(int argc, char** argv) {
int opt;
bool flagA = false;
bool flagB = false;
// Shut GetOpt error messages down (return '?'):
opterr = 0;
// Retrieve the options:
while ( (opt = getopt(argc, argv, "ab")) != -1 ) { // for each option...
switch ( opt ) {
case 'a':
flagA = true;
break;
case 'b':
flagB = true;
break;
case '?': // unknown option...
cerr << "Unknown option: '" << char(optopt) << "'!" << endl;
break;
}
}
// Debug:
cout << "flagA = " << flagA << endl;
cout << "flagB = " << flagB << endl;
return 0;
}
You can also use optarg if you have options that accept arguments.
We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.
On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:
### log just the SQL
log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug
However, the JDBC bind parameters are not being logged.
With pure CSS, nothing fancy with :before
and :after
, no transforms, you can turn off the default appearance and then style it with an inline background image like the following example. This works in Chrome, Firefox, Safari, and now Edge (Chromium Edge).
INPUT[type=checkbox]:focus
{
outline: 1px solid rgba(0, 0, 0, 0.2);
}
INPUT[type=checkbox]
{
background-color: #DDD;
border-radius: 2px;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
width: 17px;
height: 17px;
cursor: pointer;
position: relative;
top: 5px;
}
INPUT[type=checkbox]:checked
{
background-color: #409fd6;
background: #409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
_x000D_
<form>
<label><input type="checkbox"> I Agree To Terms & Conditions</label>
</form>
_x000D_
You can use this
First You can get a Buffer/List of S3 Paths :
import scala.collection.JavaConverters._
import java.util.ArrayList
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.ObjectListing
import com.amazonaws.services.s3.model.S3ObjectSummary
import com.amazonaws.services.s3.model.ListObjectsRequest
def listFiles(s3_bucket:String, base_prefix : String) = {
var files = new ArrayList[String]
//S3 Client and List Object Request
var s3Client = new AmazonS3Client();
var objectListing: ObjectListing = null;
var listObjectsRequest = new ListObjectsRequest();
//Your S3 Bucket
listObjectsRequest.setBucketName(s3_bucket)
//Your Folder path or Prefix
listObjectsRequest.setPrefix(base_prefix)
//Adding s3:// to the paths and adding to a list
do {
objectListing = s3Client.listObjects(listObjectsRequest);
for (objectSummary <- objectListing.getObjectSummaries().asScala) {
files.add("s3://" + s3_bucket + "/" + objectSummary.getKey());
}
listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());
//Removing Base Directory Name
files.remove(0)
//Creating a Scala List for same
files.asScala
}
Now Pass this List object to the following piece of code, note : sc is an object of SQLContext
var df: DataFrame = null;
for (file <- files) {
val fileDf= sc.textFile(file)
if (df!= null) {
df= df.unionAll(fileDf)
} else {
df= fileDf
}
}
Now you got a final Unified RDD i.e. df
Optional, And You can also repartition it in a single BigRDD
val files = sc.textFile(filename, 1).repartition(1)
Repartitioning always works :D
Use negative lookahead:
^(?!.*ab).*$
UPDATE: In the comments below, I stated that this approach is slower than the one given in Peter's answer. I've run some tests since then, and found that it's really slightly faster. However, the reason to prefer this technique over the other is not speed, but simplicity.
The other technique, described here as a tempered greedy token, is suitable for more complex problems, like matching delimited text where the delimiters consist of multiple characters (like HTML, as Luke commented below). For the problem described in the question, it's overkill.
For anyone who's interested, I tested with a large chunk of Lorem Ipsum text, counting the number of lines that don't contain the word "quo". These are the regexes I used:
(?m)^(?!.*\bquo\b).+$
(?m)^(?:(?!\bquo\b).)+$
Whether I search for matches in the whole text, or break it up into lines and match them individually, the anchored lookahead consistently outperforms the floating one.
To list all local groups which have users assigned to them, use this command:
cut -d: -f1 /etc/group | sort
For more info- > Unix groups, Cut command, sort command
Her is another R base
approach:
From your example: Some date:
Some_date<-"01/01/1979"
We tell R, "That is a Date"
Some_date<-as.Date(Some_date)
We extract the month:
months(Some_date)
output: [1] "January"
Finally, we can convert it to a numerical variable:
as.numeric(as.factor(months(Some_date)))
outpt: [1] 1
List<Object> list = new ArrayList();
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext();) {
Object obj= iterator.next();
if (obj.getId().equals("1")) {
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.
The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here
If using ASP.NET Core, you can adjust the accepted answer to:
<a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, @Context.Request.Scheme)">
<span>Clients</span>
</a>
replacing @Request.Url.Scheme
with @Context.Request.Scheme
I played a long time with things like ls -1 | xargs -P
to parallelize my playbooks runs. But to get a prettier display, and simplicity I wrote a simple Python tool to do it, ansible-parallel.
It goes like this:
pip install ansible-parallel
ansible-parallel *.yml
To answer precisely to the original question (how to run some tasks first, and the rest in parallel), it can be solved by removing the 3 includes and running:
ansible-playbook say_hi.yml
ansible-parallel load_balancers.yml webservers.yml dbservers.yml
sklearn.cross_validation
is now changed to sklearn.model_selection
Just use
from sklearn.model_selection import train_test_split
I think that will work.
Suppose I have Hashmap with key datatype as KeyDataType and value datatype as ValueDataType
HashMap<KeyDataType,ValueDataType> list;
Add all items you needed to it. Now you can retrive all hashmap keys to a list by.
KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);
So, now you got your all keys in an array mkeys[]
you can now retrieve any value by calling
list.get(mkeys[position]);