After instantiating the connection, open it.
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Also, avoid building SQL statements by just appending strings. It's better if you use parameters, that way you win on performance, your program is not prone to SQL injection attacks and your program is more stable. For example:
str_carSql = "insert into members_car
(car_id, member_id, model, color, chassis_id, plate_number, code)
values
(@id,@m_id,@model,@color,@ch_id,@pt_num,@code)"
And then you do this:
sqlCommand.Parameters.AddWithValue("@id",TextBox20.Text)
sqlCommand.Parameters.AddWithValue("@m_id",TextBox23.Text)
' And so on...
Then you call:
sqlCommand.ExecuteNonQuery()
I'll write my answer in a didactic manner...
First type into your Python interpreter:
import this
then, go and take a look to the file this.py
in your Lib directory within your Python distribution and try to understand what it does.
After that, take a look to the eval
function in the documentation:
help(eval)
Now you should have found a funny way to protect your code. But beware, because that only works for people that are less intelligent than you! (and I'm not trying to be offensive, anyone smart enough to understand what you did could reverse it).
Change it to:
<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>
Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.
The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:
<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>
Oh and just for completeness, you should really prefer classes to direct CSS styles.
Step 1: Change build.grade
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
}
dependencies {
...
compile 'com.android.support:multidex:1.0.0'
}
Step 2: Setting on the Application class
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MultiDex.install(this);
}
}
Step 3: Change grade.properties
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
It will work!. Thanks.
You need to turn this into a string. You can do this using the stringify method in the JSON2 library.
The code would look something like:
var myJSONText = JSON.stringify(myObject);
So
['Location Zero', 'Location One', 'Location Two'];
Will become:
"['Location Zero', 'Location One', 'Location Two']"
You'll have to refer to a PHP guru on how to handle this on the server. I think other answers here intimate a solution.
Data can be returned from the server in a similar way. I.e. you can turn it back into an object.
var myObject = JSON.parse(myJSONString);
I had a similar issue which i solved by making two changes
added below entry in application.yaml file
spring:
jackson:
serialization.write_dates_as_timestamps: false
add below two annotations in pojo
sample example
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class Customer {
//your fields ...
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
protected LocalDate birthdate;
}
then the following json requests worked for me
{
"birthdate": "2019-11-28"
}
{
"birthdate":[2019,11,18]
}
Hope it helps!!
As user 'Skip Head' already pointed out, csv or a any table file format would be a better fitt in your case.
If it is an option for you, maybe this Table implementation might interest you.
You can create a StreamReader
around the stream, then call StreamReader.ReadToEnd()
.
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();
Another way to look at it is to consider git rebase master
as:
Rebase the current branch on top of
master
Here , 'master
' is the upstream branch, and that explain why, during a rebase, ours
and theirs
are reversed.
You cannot load images directly with @2x
or @3x
, system selects appropriate image automatically, just specify the name using UIImage
:
UIImage(named: "green-square-Retina")
scp -r <directory> <username>@<targethost>:<targetdir>
Following looks very simple to me:
model.layers[idx].output
Above is a tensor object, so you can modify it using operations that can be applied to a tensor object.
For example, to get the shape model.layers[idx].output.get_shape()
idx
is the index of the layer and you can find it from model.summary()
Assuming you are working with a newly returned ResultSet
whose cursor is pointing before the first row, an easier way to check this is to just call isBeforeFirst()
. This avoids having to back-track if the data is to be read.
As explained in the documentation, this returns false if the cursor is not before the first record or if there are no rows in the ResultSet.
if (!resultSet.isBeforeFirst() ) {
System.out.println("No data");
}
The new recommend way in Python3 is to use pathlib:
from pathlib import Path
mydir = Path("path/to/my/dir")
for file in mydir.glob('*.mp4'):
print(file.name)
# do your stuff
Instead of *.mp4
you can use any filter, even a recursive one like **/*.mp4
. If you want to use more than one extension, you can simply iterate all with *
or **/*
(recursive) and check every file's extension with file.name.endswith(('.mp4', '.webp', '.avi', '.wmv', '.mov'))
To download any artifact use
mvn dependency:get -Dartifact=groupId:artifactId:version:packaging:classifier
For Groovy sources this would be
mvn dependency:get -Dartifact=org.codehaus.groovy:groovy-all:2.4.6:jar:sources
For Groovy's javadoc you would use
mvn dependency:get -Dartifact=org.codehaus.groovy:groovy-all:2.4.6:jar:javadoc
This puts the given artifact into your local Maven repository, i.e. usually $HOME/.m2/repository
.
dependency:sources
just downloads the project dependencies' sources, not the plugins sources nor the sources of dependencies defined inside plugins.
If you want to read text of any element using javascript executor, you can do something like following code:
WebElement ele = driver.findElement(By.xpath("//div[@class='infaCompositeViewTitle']"));
String assets = (String) js.executeScript("return arguments[0].getElementsByTagName('span')[1].textContent;", ele);
In this example, I have following HTML fragment and I am reading "156".
<div class="infaCompositeViewTitle">
<span>All Assets</span>
<span>156</span>
</div>
That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:
JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }
If you know it's a single-element Map then you can directly access the link
:
def data = userJson.values().iterator().next()
String link = data.link
And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:
String id = '212315952136472'
...
String link = userJson[id].link
If you have access to a console in the context you are investigating, you can determine which version you are running by printing the value of the global constant RUBY_VERSION
.
You asked about performance. See this perf test comparing 'concat', '+' and 'join' - in short the + operator wins by far.
In my case I had two different lists, with a common identifier, kind of like a foreign key. The second solution cited by "nzrytmn":
var result = list1.Where(p => !list2.Any(x => x.ID == p.ID && x.property1 == p.property1)).ToList();
Was the one that best fit in my situation. I needed to load a DropDownList without the records that had already been registered.
Thank you !!!
This is my code:
t1 = new T1();
t2 = new T2();
List<T1> list1 = t1.getList();
List<T2> list2 = t2.getList();
ddlT3.DataSource= list2.Where(s => !list1.Any(p => p.Id == s.ID)).ToList();
ddlT3.DataTextField = "AnyThing";
ddlT3.DataValueField = "IdAnyThing";
ddlT3.DataBind();
Try this:
$('#id').change();
Works for me.
On one line together with setting the value:
$('#id').val(16).change();
It's because your '/new_sandbox/'
begins with a /
and thus is assumed to be relative to the root directory. Remove the leading /
.
echo "1 2 3 4 5 6" | awk '{ $NF = ""; print $0}'
this one uses awk to print all except the last field
I'm going to answer the literal question: no, there isn't a good reason you see VARCHAR(255) used so often (there are indeed reasons, as discussed in the other answers, just not good ones). You won't find many examples of projects that have failed catastrophically because the architect chose VARCHAR(300) instead of VARCHAR(255). This would be an issue of near-total insignificance even if you were talking about CHAR instead of VARCHAR.
Well in my case the following work fine
<div class="card-body p-2">
<div class="d-flex flex-row justify-content-center">
<div style="margin: auto;">
<input type="text" autocomplete="off"
style="max-width:150px!important; "
class="form-control form-control-sm font-weight-bold align-self-center w-25" id="dtTechState">
</div>
</div>
</div>
To use alternate credentials for a single operation, use the --username
and --password
switches for svn
.
To clear previously-saved credentials, delete ~/.subversion/auth
. You'll be prompted for credentials the next time they're needed.
These settings are saved in the user's home directory, so if you're using a shared account on "this laptop", be careful - if you allow the client to save your credentials, someone can impersonate you. The first option I provided is the better way to go in this case. At least until you stop using shared accounts on computers, which you shouldn't be doing.
To change credentials you need to do:
rm -rf ~/.subversion/auth
svn up
( it'll ask you for new username & password )If you're using getApplicationContext()
as Context
in Activity for the dialog like this
Dialog dialog = new Dialog(getApplicationContext());
then use YourActivityName.this
Dialog dialog = new Dialog(YourActivityName.this);
Without examples of the dataset of staging this is a shot in the dark, but have you tried something like this?
update PRODUCTION p,
staging s
set p.name = s.name
p.count = s.count
where p.id = s.id
This would work assuming the id column matches on both tables.
//Client
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String hostname = "localhost";
int port = 6789;
// declaration section:
// clientSocket: our client socket
// os: output stream
// is: input stream
Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;
// Initialization section:
// Try to open a socket on the given port
// Try to open input and output streams
try {
clientSocket = new Socket(hostname, port);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on the given port
if (clientSocket == null || os == null || is == null) {
System.err.println( "Something is wrong. One variable is null." );
return;
}
try {
while ( true ) {
System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String keyboardInput = br.readLine();
os.writeBytes( keyboardInput + "\n" );
int n = Integer.parseInt( keyboardInput );
if ( n == 0 || n == -1 ) {
break;
}
String responseLine = is.readLine();
System.out.println("Server returns its square as: " + responseLine);
}
// clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
//Server
import java.io.*;
import java.net.*;
public class Server1 {
public static void main(String args[]) {
int port = 6789;
Server1 server = new Server1( port );
server.startServer();
}
// declare a server socket and a client socket for the server
ServerSocket echoServer = null;
Socket clientSocket = null;
int port;
public Server1( int port ) {
this.port = port;
}
public void stopServer() {
System.out.println( "Server cleaning up." );
System.exit(0);
}
public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}
System.out.println( "Waiting for connections. Only one connection is allowed." );
// Create a socket object from the ServerSocket to listen and accept connections.
// Use Server1Connection to process the connection.
while ( true ) {
try {
clientSocket = echoServer.accept();
Server1Connection oneconnection = new Server1Connection(clientSocket, this);
oneconnection.run();
}
catch (IOException e) {
System.out.println(e);
}
}
}
}
class Server1Connection {
BufferedReader is;
PrintStream os;
Socket clientSocket;
Server1 server;
public Server1Connection(Socket clientSocket, Server1 server) {
this.clientSocket = clientSocket;
this.server = server;
System.out.println( "Connection established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop = false;
while (true) {
line = is.readLine();
System.out.println( "Received " + line );
int n = Integer.parseInt(line);
if ( n == -1 ) {
serverStop = true;
break;
}
if ( n == 0 ) break;
os.println("" + n*n );
}
System.out.println( "Connection closed." );
is.close();
os.close();
clientSocket.close();
if ( serverStop ) server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
}
There is an easy workaround for this problem
What you need to do, is format your dates as DD/MM/YYYY (or whichever way around you like)
Insert a column next to the time and date columns, put a formula in this column that adds them together. e.g. =A5+B5.
Format this inserted column into DD/MM/YYYY hh:mm:ss which can be found in the custom category on the formatting section
Plot a scatter graph
Badabing badaboom
If you are unhappy with this workaround, learn to use GNUplot :)
Under normal circumstances,out of bound of array when you encounter the error. So,check uo your array subscript.
Would it not be better to use java.util.Observable
and java.util.Observer
that will cause the table to update?
This is an old topic and I'd like to add my understanding here to expand the knowledge of this interesting topic.
The key difference between REM and :: is:
REM is a command itself, while :: is NOT.
We can treat :: as a token that as soon as CMD parser encounters the first non-blank space in a line is this :: token, it will just skip the whole line and read next line. That's why REM should be followed by at least a blank space to be able to function as a comment for the line, while :: does not need any blank space behind it.
That REM is a command itself can be best understood from the following FOR syntax
The basic FOR syntax is as follows
FOR %v in (set) DO <Command> [command param]
here <Command>
can be any valid command
So we can write the following valid command line as rem
is a command
FOR %i in (1,2,3) DO rem echo %i
However, we CANNOT write the following line as ::
is not a command
FOR %i in (1,2,3) DO :: echo %i
Take a look at archive.org
You can find almost everything about the past of a website there.
No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).
For constructors, See Effective Java: Programming Language Guide's Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.
You can do something like this as demonstrated in perlfaq4:
sub uniq {
my %seen;
grep !$seen{$_}++, @_;
}
my @array = qw(one two three two three);
my @filtered = uniq(@array);
print "@filtered\n";
Outputs:
one two three
If you want to use a module, try the uniq
function from List::MoreUtils
This related to these 2 topics below, I want get both GetHtmlErrorMessage and Session on Error page.
Session is null after ResponseRewrite
Why is HttpContext.Session null when redirectMode = ResponseRewrite
I tried and see solution which no need Server.Transfer() or Response.Redirect()
First: remove ResponseRewrite in web.config
Web.config
<customErrors defaultRedirect="errorHandler.aspx" mode="On" />
Then Global.asax
void Application_Error(object sender, EventArgs e)
{
if(Context.IsCustomErrorEnabled)
{
Exception ex = Server.GetLastError();
Application["TheException"] = ex; //store the error for later
}
}
Then errorHandler.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string htmlErrorMessage = string.Empty ;
Exception ex = (Exception)Application["TheException"];
string yourSessionValue = HttpContext.Current.Session["YourSessionId"].ToString();
//continue with ex to get htmlErrorMessage
if(ex.GetHtmlErrorMessage() != null){
htmlErrorMessage = ex.GetHtmlErrorMessage();
}
// continue your code
}
For references
http://www.developer.com/net/asp/article.php/3299641/ServerTransfer-Vs-ResponseRedirect.htm
.btn{
font-size: 20px;
color:black;
}
You can use isLetter(char c) static method of Character class in Java.lang .
public boolean isAlpha(String s) {
char[] charArr = s.toCharArray();
for(char c : charArr) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
With re-encoding:
ffmpeg -y -i seeing_noaudio.mp4 -vf "setpts=1.25*PTS" -r 24 seeing.mp4
Without re-encoding:
First step - extract video to raw bitstream
ffmpeg -y -i seeing_noaudio.mp4 -c copy -f h264 seeing_noaudio.h264
Remux with new framerate
ffmpeg -y -r 24 -i seeing_noaudio.h264 -c copy seeing.mp4
Despite using zip(*iterable)
to transpose a nested list, you can also use the following if the nested lists vary in length:
map(None, *[(1,2,3,), (4,5,), (6,)])
results in:
[(1, 4, 6), (2, 5, None), (3, None, None)]
The first column is thus:
map(None, *[(1,2,3,), (4,5,), (6,)])[0]
#>(1, 4, 6)
I've had better luck with calling the gotoDate
in the viewRender
callback:
$('#calendar').fullCalendar({
firstDay: 0,
defaultView: 'basicWeek',
header: {
left: '',
center: 'basicDay,basicWeek,month',
right: 'today prev,next'
},
viewRender: function(view, element) {
$('#calendar').fullCalendar( 'gotoDate', 2014, 4, 24 );
}
});
Calling gotoDate
outside of the callback didn't have the expected results due to a race condition.
I wrote a batch script a while ago that allows you to pick a file extension to delete. The script will look in the folder it is in and all subfolders for any file with that extension and delete it.
@ECHO OFF
CLS
SET found=0
ECHO Enter the file extension you want to delete...
SET /p ext="> "
IF EXIST *.%ext% ( rem Check if there are any in the current folder :)
DEL *.%ext%
SET found=1
)
FOR /D /R %%G IN ("*") DO ( rem Iterate through all subfolders
IF EXIST %%G CD %%G
IF EXIST *.%ext% (
DEL *.%ext%
SET found=1
)
)
IF %found%==1 (
ECHO.
ECHO Deleted all .%ext% files.
ECHO.
) ELSE (
ECHO.
ECHO There were no .%ext% files.
ECHO Nothing has been deleted.
ECHO.
)
PAUSE
EXIT
Hope this comes in useful to anyone who wants it :)
You need to transform the object you are getting back into an array in the format that jQueryUI expects.
You can use $.map
to transform the dealers
object into that array.
$('#dealerName').autocomplete({
source: function (request, response) {
$.getJSON("/example/location/example.json?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
minLength: 2,
delay: 100
});
Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label
and value
properties that $.map
's callback function return.
Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:
label
property, a value
property, or both, orIn other words, if you can format the data like this:
[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]
or this:
["dealer 5", "dealer 6"]
Then your JavaScript becomes much simpler:
$('#dealerName').autocomplete({
source: "/example/location/example.json"
});
You can use path.parse(path), for example
const path = require('path');
const { ext } = path.parse('/home/user/dir/file.txt');
Timezones. You have to deal with them, by using getTimezoneOffset()
if you want your visitors from around the wolrd to get the same time.
Try this http://jsfiddle.net/cxyms/2/, it works for me, but I'm not sure will it work with other timezones.
var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var eventTime = new Date();
eventTime.setTime(366549200);
var Offset = new Date(eventTime.getTimezoneOffset()*60000)
var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);
i also have a solution with standard inputs and outputs
#include<stdio.h>
#include<malloc.h>
int main()
{
char *str,ch;
int size=10,len=0;
str=realloc(NULL,sizeof(char)*size);
if(!str)return str;
while(EOF!=scanf("%c",&ch) && ch!="\n")
{
str[len++]=ch;
if(len==size)
{
str = realloc(str,sizeof(char)*(size+=10));
if(!str)return str;
}
}
str[len++]='\0';
printf("%s\n",str);
free(str);
}
A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.
Just my take on this, there are two methods that are easy to understand of all the given options. So my main criteria is have very readable code, not exceptionally fast code. To keep code understandable, i prefer to given possibilities:
The fact that "var <= var2.keys()" executes faster in my testing below, i prefer this one.
import timeit
timeit.timeit('var <= var2.keys()', setup='var={"managed_ip", "hostname", "fqdn"}; var2= {"zone": "test-domain1.var23.com", "hostname": "bakje", "api_client_ip": "127.0.0.1", "request_data": "", "request_method": "GET", "request_url": "hvar2p://127.0.0.1:5000/test-domain1.var23.com/bakje", "utc_datetime": "04-Apr-2019 07:01:10", "fqdn": "bakje.test-domain1.var23.com"}; var={"managed_ip", "hostname", "fqdn"}')
0.1745898080000643
timeit.timeit('var.issubset(var2)', setup='var={"managed_ip", "hostname", "fqdn"}; var2= {"zone": "test-domain1.var23.com", "hostname": "bakje", "api_client_ip": "127.0.0.1", "request_data": "", "request_method": "GET", "request_url": "hvar2p://127.0.0.1:5000/test-domain1.var23.com/bakje", "utc_datetime": "04-Apr-2019 07:01:10", "fqdn": "bakje.test-domain1.var23.com"}; var={"managed_ip", "hostname", "fqdn"};')
0.2644960229999924
As a temporary tweak ( not permanent )
On Mac you would need to create your own shortcuts ..
Its easy. my set:
CMD + Wheel-up for increase font size
CMD + Wheel-down for decreasing font size
Prefernces => Keymap => Increase Font size/decrease Font size/Reset Font size
Good luck,'.
I use BC3 for my git diff, but I'd also add vscode to the list of useful git diff tools. Some users prefer vscode over vs ide experience.
git config --global diff.tool vscode
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE"
Use Subscript Generating Functions.
http://www.postgresql.org/docs/current/static/functions-srf.html#FUNCTIONS-SRF-SUBSCRIPTS
For example:
SELECT
id
, elements[i] AS elem
, i AS nr
FROM
( SELECT
id
, elements
, generate_subscripts(elements, 1) AS i
FROM
( SELECT
id
, string_to_array(elements, ',') AS elements
FROM
myTable
) AS foo
) bar
;
More simply:
SELECT
id
, unnest(elements) AS elem
, generate_subscripts(elements, 1) AS nr
FROM
( SELECT
id
, string_to_array(elements, ',') AS elements
FROM
myTable
) AS foo
;
Try this from the box you are pushing from
ssh [email protected]
You should then get a welcome response from github and will be fine to then push.
It seems like it exists a bug in jQuery reported here : http://bugs.jquery.com/ticket/13183 that breaks the Fancybox script.
Also check https://github.com/fancyapps/fancyBox/issues/485 for further reference.
As a workaround, rollback to jQuery v1.8.3 while either the jQuery bug is fixed or Fancybox is patched.
UPDATE (Jan 16, 2013): Fancybox v2.1.4 has been released and now it works fine with jQuery v1.9.0.
For fancybox v1.3.4- you still need to rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.
UPDATE (Jan 17, 2013): Workaround for users of Fancybox v1.3.4 :
Patch the fancybox js file to make it work with jQuery v1.9.0 as follow :
Find around the line 29 where it says :
isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
and replace it by (EDITED March 19, 2013: more accurate filter):
isIE6 = navigator.userAgent.match(/msie [6]/i) && !window.XMLHttpRequest,
UPDATE (March 19, 2013): Also replace $.browser.msie
by navigator.userAgent.match(/msie [6]/i)
around line 615 (and/or replace all $.browser.msie
instances, if any), thanks joofow
... that's it!
Or download the already patched version from HERE (UPDATED March 19, 2013 ... thanks fairylee for pointing out the extra closing bracket)
NOTE: this is an unofficial patch and is unsupported by Fancybox's author, however it works as is. You may use it at your own risk ;)
Optionally, you may rather rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.
That would be the item property: http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
Maybe something like this would work:
public T Item[int index, int y]
{
//Then do whatever you need to return/set here.
get; set;
}
I know its not regex but any way...
This is example with node and npm package email-existence this is ultimate checking if email exist and if its in the right form :)
This will ping the email if its responding if it got no response it will return false or else true.
function doesEmailExist(email) {
var emailExistence = require('email-existence');
return emailExistence.check(email,function (err,status) {
if (status) {
return status;
}
else {
throw new Error('Email does not exist');
}
});
}
Just use:
do
{
//enter code here
} while ( !condition );
So what this does is, it moves your 'check for condition' part to the end, since the while
is at the end. So it only checks the condition after running the code, just like how you want it
Had the same issue on my HTC Incredible S. The problem was that I used a third party docking station to connect. Connecting the phone directly solved the problem.
It sounds like you need to make use of advanced where clauses.
Given that search in field1
and field2
is constant we will leave them as is, but we are going to adjust your search in datefield
a little.
Try this:
$query = Model::where('field1', 1)
->whereNull('field2')
->where(function ($query) {
$query->where('datefield', '<', $date)
->orWhereNull('datefield');
}
);
If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql()
to the end of your eloquent query to generate the SQL.
If the user exists you can get the user in user_object
else user_object
will be None
.
try:
user_object = User.objects.get(email = cleaned_info['username'])
except User.DoesNotExist:
user_object = None
if user_object:
# user exist
pass
else:
# user does not exist
pass
By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.
I used class (strongly-typed version of Enum with parsing and performance improvements). I found it on GitHub, and it should work for .NET 3.5 too. It has some memory overhead since it buffers a dictionary.
StatusEnum MyStatus = Enum<StatusEnum>.Parse("Active");
The blogpost is Enums – Better syntax, improved performance and TryParse in NET 3.5.
And code: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs
On Bootstrap5
Like noticed in the docu you can use the "data-bs-parent=.." attribute
If parent is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior - this is dependent on the card class). The attribute has to be set on the target collapsible area.
I've written a fairly comprehensive article about this very topic and also developed a pop-in library for MVVM Dialogs. Strict adherence to MVVM is not only possible but very clean when implemented properly, and it can be easily extended to third-party libraries that don't adhere to it themselves:
https://www.codeproject.com/Articles/820324/Implementing-Dialog-Boxes-in-MVVM
I've seen several approaches to working around the bug, and I ran some timing tests to see what works for speed (http://jsfiddle.net/5dwwy/)
In this approach, the razor syntax is directly assigned to the variable. This is what throws the error. As a baseline, the JavaScript speed test simply does a straight assignment of a number to a variable.
In this approach, we wrap the razor syntax in a call to the `Number` constructor, as in `Number(@ViewBag.Value)`.
In this approach, the razor syntax is put inside quotes and passed to the `parseInt` function.
In this approach, a function is created that simply takes the razor syntax as a parameter and returns it.
In this approach, the function performs some basic type checking (looking for null, basically) and returns the value if it isn't null.
Using each approach mentioned above, a for-loop
repeats each function call 10M times, getting the total time for the entire loop. Then, that for-loop is repeated 30 times to obtain an average time per 10M actions. These times were then compared to each other to determine which actions were faster than others.
Note that since it is JavaScript running, the actual numbers other people receive will differ, but the importance is not in the actual number, but how the numbers compare to the other numbers.
Using the Direct assignment approach, the average time to process 10M assignments was 98.033ms. Using the Number
constructor yielded 1554.93ms per 10M. Similarly, the parseInt
method took 1404.27ms. The two function calls took 97.5ms for the simple function and 101.4ms for the more complex function.
The cleanest code to understand is the Direct assignment. However, because of the bug in Visual Studio, this reports an error and could cause issues with Intellisense and give a vague sense of being wrong.
The fastest code was the simple function call, but only by a slim margin. Since I didn't do further analysis, I do not know if this difference has a statistical significance. The type-checking function was also very fast, only slightly slower than a direct assignment, and includes the possibility that the variable may be null. It's not really practical, though, because even the basic function will return undefined if the parameter is undefined (null in razor syntax).
Parsing the razor value as an int and running it through the constructor were extremely slow, on the order of 15x slower than a direct assignment. Most likely the Number
constructor is actually internally calling parseInt
, which would explain why it takes longer than a simple parseInt
. However, they do have the advantage of being more meaningful, without requiring an externally-defined (ie somewhere else in the file or application) function to execute, with the Number
constructor actually minimizing the visible casting of an integer to a string.
Bottom line, these numbers were generated running through 10M iterations. On a single item, the speed is incalculably small. For most, simply running it through the Number
constructor might be the most readable code, despite being the slowest.
A ClassCastException
ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example
Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;
This works because an apple 'is a' fruit. However if we reverse this.
Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;
This will throw a ClasCastException because a Fruit is not (always) an Apple.
It is good practice to guard any explicit casts with an instanceof
check first:
if (myApple instanceof Fruit) {
Fruit myFruit = (Fruit)myApple;
}
I made this slight modification to Matt's script to enable it to run from within a single script (just add this to the beginning of any script requiring UAC invocation), but read below the code for an even better solution that I've found on a blog:
:: ### START UAC SCRIPT ###
if "%2"=="firstrun" exit
cmd /c "%0" null firstrun
if "%1"=="skipuac" goto skipuacstart
:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )
:getPrivileges
if '%1'=='ELEV' (shift & goto gotPrivileges)
setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs"
ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs"
"%temp%\OEgetPrivileges.vbs"
exit /B
:gotPrivileges
setlocal & pushd .
cd /d %~dp0
cmd /c "%0" skipuac firstrun
cd /d %~dp0
:skipuacstart
if "%2"=="firstrun" exit
:: ### END UAC SCRIPT ###
:: ### START OF YOUR OWN BATCH SCRIPT BELOW THIS LINE ###
My modification uses two file arguments as you can see, which isn't particularly elegant but does the job (and you can always hide them away at the tail end by reserving the first few arguments using dummy placeholders). Additionally, AFAIK Matt's script doesn't support spaces in file paths and this limitation also applies to my modification of this script.
This issue seems to be inherent in the way VBS handles these paths but on the below link there's an even better VBS-based solution for invoking UAC that runs from within a single script without the need for a workaround like this using file arguments and that also supports spaces in file paths:
http://pcloadletter.co.uk/2012/12/11/uac-elevation-for-batch-script/
The script on this link makes slightly different VBS calls as you'll notice, which for some reason circumvents the issue with spaces.
I needed this for something as simple as redirecting all http
traffic from the default apache home page on my server to one served over https
.
Since I'm still quite green when it comes to configuring apache, I prefer to avoid using mod_rewrite
directly and instead went for something simpler like this:
<VirtualHost *:80>
<Location "/">
Redirect permanent "https://%{HTTP_HOST}%{REQUEST_URI}"
</Location>
</VirtualHost>
<VirtualHost *:443>
DocumentRoot "/var/www/html"
SSLEngine on
...
</VirtualHost>
I like this because it allowed me to use apache variables and that way I didn't have to specify the actual host name since it's just an IP address without an associated domain name.
References: https://stackoverflow.com/a/40291044/2089675
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
Update: you can read the more complex answer, which contains more methods and information.
There exists a couple of scripts, which can be used as simple package managers. But as far as I know, none of them allows you to upgrade packages, because it’s not an easy task on Windows since there is not possible to overwrite files in use. So you have to close all Cygwin instances first and then you can use Cygwin’s native setup.exe (which itself does the upgrade via “replace after reboot” method, when files are in use).
The best one for me. Simply because it’s one of the most recent. It works correctly for both platforms - x86 and x86_64. There exists a lot of forks with some additional features. For example the kou1okada fork is one of improved versions.
It has also command line mode. Moreover it allows you to upgrade all installed packages at once.
setup.exe-x86_64.exe -q --packages=bash,vim
Example use:
setup.exe-x86_64.exe -q --packages="bash,vim"
You can create an alias for easier use, for example:
alias cyg-get="/cygdrive/d/path/to/cygwin/setup-x86_64.exe -q -P"
Then you can for example install the Vim package with:
cyg-get vim
I have a couple of different patterns that I use. I use the ExpectedException
attribute most of the time when an exception is expected. This suffices for most cases, however, there are some cases when this is not sufficient. The exception may not be catchable - since it's thrown by a method that is invoked by reflection - or perhaps I just want to check that other conditions hold, say a transaction is rolled back or some value has still been set. In these cases I wrap it in a try/catch
block that expects the exact exception, does an Assert.Fail
if the code succeeds and also catches generic exceptions to make sure that a different exception is not thrown.
First case:
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void MethodTest()
{
var obj = new ClassRequiringNonNullParameter( null );
}
Second case:
[TestMethod]
public void MethodTest()
{
try
{
var obj = new ClassRequiringNonNullParameter( null );
Assert.Fail("An exception should have been thrown");
}
catch (ArgumentNullException ae)
{
Assert.AreEqual( "Parameter cannot be null or empty.", ae.Message );
}
catch (Exception e)
{
Assert.Fail(
string.Format( "Unexpected exception of type {0} caught: {1}",
e.GetType(), e.Message )
);
}
}
I had to use the transparent keyword to get the color I chose with my initial
fig=figure(facecolor='black')
like this:
savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True)
Android studio doesn't use Maven
, it use Gradle
, you can open your build.gradle
the route should be: /app/build.gradle
and add the Gradle dependency that shows on the repo:
The build.gradle
has a dependencies
section:
dependencies {
//here add your dependency
}
The repo says that you need to add this dependency:
compile 'com.foursquare:foursquare-android-oauth:1.0.3'
only add that line to your dependencies
on buil.gradle
, save the file, and android will rebuild the project, that's all
I tried this, it worked for me:
declare @b2 VARBINARY(MAX)
set @b2 = 0x54006800690073002000690073002000610020007400650073007400
SELECT CONVERT(nVARCHAR(1000), @b2, 0);
You can either post HTML form to URL, which is mapped to servlet or insert your data in HttpServletRequest object you pass to jsp page.
MySQL has discontinued drop database command from mysql client shell. Need to use mysqladmin to drop a database.
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
You can use like this, it works!
WebProxy proxy = new WebProxy
{
Address = new Uri(""),
Credentials = new NetworkCredential("", "")
};
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
HttpClient client = new HttpClient(httpClientHandler);
HttpResponseMessage response = await client.PostAsync("...");
You could do
<body onload="window.print()">
...
</body>
Follow the example --
songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]
print("===========================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')
playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')
# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))
This is the solution for me
File currentDir = new File("");
int(hexstring, 16)
does the trick, and works with and without the 0x prefix:
>>> int("a", 16)
10
>>> int("0xa", 16)
10
To go to location WITH PIN on it, use:
String uri = "http://maps.google.com/maps?q=loc:" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
for without pin, use this in uri:
String uri = "geo:" + destinationLatitude + "," + destinationLongitude;
Cookies are basically text, so you can store an array by encoding it as a JSON string (see json_encode
). Be aware that there is a limit on the length of the string you can store though.
I found Serge's answer to be very promising, but I also encountered performance issues with it as-written. However, when I restructured it to use temporary tables and not include double CTE tables, the performance went from 1 minute 40 seconds to sub-second for 1000 combined records. Here it is for anyone who needs to do this without FOR XML on older versions of SQL Server:
DECLARE @STRUCTURED_VALUES TABLE (
ID INT
,VALUE VARCHAR(MAX) NULL
,VALUENUMBER BIGINT
,VALUECOUNT INT
);
INSERT INTO @STRUCTURED_VALUES
SELECT ID
,VALUE
,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY VALUE) AS VALUENUMBER
,COUNT(*) OVER (PARTITION BY ID) AS VALUECOUNT
FROM RAW_VALUES_TABLE;
WITH CTE AS (
SELECT SV.ID
,SV.VALUE
,SV.VALUENUMBER
,SV.VALUECOUNT
FROM @STRUCTURED_VALUES SV
WHERE VALUENUMBER = 1
UNION ALL
SELECT SV.ID
,CTE.VALUE + ' ' + SV.VALUE AS VALUE
,SV.VALUENUMBER
,SV.VALUECOUNT
FROM @STRUCTURED_VALUES SV
JOIN CTE
ON SV.ID = CTE.ID
AND SV.VALUENUMBER = CTE.VALUENUMBER + 1
)
SELECT ID
,VALUE
FROM CTE
WHERE VALUENUMBER = VALUECOUNT
ORDER BY ID
;
If you mean using a literal, you simply have to create a binary string:
insert into Files (FileId, FileData) values (1, 0x010203040506)
And you will have a record with a six byte value for the FileData field.
You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).
You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).
In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.
DateTime.Now.DayOfWeek
quite easy to guess actually.
for any given date:
DateTime dt = //....
DayOfWeek dow = dt.DayOfWeek; //enum
string str = dow.ToString(); //string
Using the Java 8 Streams API.
List<Value> values = map.values().stream().collect(Collectors.toList());
When the directory already exist:
mkdir -m 777 /path/to/your/dir
When the directory does not exist and you want to create the parent directories:
mkdir -m 777 -p /parent/dirs/to/create/your/dir
From back side with Spring Boot I've used custom BasicAuthenticationEntryPoint:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests()
...
.antMatchers(PUBLIC_AUTH).permitAll()
.and().httpBasic()
// https://www.baeldung.com/spring-security-basic-authentication
.authenticationEntryPoint(authBasicAuthenticationEntryPoint())
...
@Bean
public BasicAuthenticationEntryPoint authBasicAuthenticationEntryPoint() {
return new BasicAuthenticationEntryPoint() {
{
setRealmName("pirsApp");
}
@Override
public void commence
(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
if (request.getRequestURI().equals(PUBLIC_AUTH)) {
response.sendError(HttpStatus.PRECONDITION_FAILED.value(), "Wrong credentials");
} else {
super.commence(request, response, authEx);
}
}
};
}
So normally you would create a backing variable in the class and toggle it on click and tie a class binding to the variable. Something like:
@Component(
selector:'foo',
template:`<a (click)="onClick()"
[class.selected]="wasClicked">Link</a>
`)
export class MyComponent {
wasClicked = false;
onClick() {
this.wasClicked= !this.wasClicked;
}
}
You can also use PHP's error_reporting();
// Disable it all for current call
error_reporting(0);
If you want to ignore errors from one function only, you can prepend a @
symbol.
@any_function(); // Errors are ignored
def doAppend( size=10000 ):
result = []
for i in range(size):
message= "some unique object %d" % ( i, )
result.append(message)
return result
def doAllocate( size=10000 ):
result=size*[None]
for i in range(size):
message= "some unique object %d" % ( i, )
result[i]= message
return result
Results. (evaluate each function 144 times and average the duration)
simple append 0.0102
pre-allocate 0.0098
Conclusion. It barely matters.
Premature optimization is the root of all evil.
SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.
As it happens, you are close. Just need leading+trailing wildcards and move the NOT
WHERE whatever NOT LIKE '%[a-z0-9]%'
STDERR can be captured with some redirection magic:
$ { error=$( { { ls -ld /XXXX /bin | tr o Z ; } 1>&3 ; } 2>&1); } 3>&1
lrwxrwxrwx 1 rZZt rZZt 7 Aug 22 15:44 /bin -> usr/bin/
$ echo $error
ls: cannot access '/XXXX': No such file or directory
Note that piping of STDOUT of the command (here ls
) is done inside the innermost {
}
. If you're executing a simple command (eg, not a pipe), you could remove these inner braces.
You can't pipe outside the command as piping makes a subshell in bash
and zsh
, and the assignment to the variable in the subshell wouldn't be available to the current shell.
In bash
, it would be better not to assume that file descriptor 3 is unused:
{ error=$( { { ls -ld /XXXX /bin | tr o Z ; } 1>&$tmp ; } 2>&1); } {tmp}>&1;
exec {tmp}>&- # With this syntax the FD stays open
Note that this doesn't work in zsh
.
Thanks to this answer for the general idea.
if I have understood correct the question :
<!DOCTYPE HTML>_x000D_
<HEAD>_x000D_
<TITLE>Passing values</TITLE>_x000D_
<style>_x000D_
</style>_x000D_
</HEAD>_x000D_
Give a number :<input type="number" id="num"><br>_x000D_
<button onclick="MyFunction(num.value)">Press button...</button>_x000D_
<script>_x000D_
function MyFunction(num) {_x000D_
document.write("<h1>You gave "+num+"</h1>");_x000D_
}_x000D_
</script>_x000D_
</BODY>_x000D_
</HTML>
_x000D_
I solved it by doing the following:
In Visual studio I went in Project -> Project Dependencies
I selected the XXX.Test
solution and told it that it also depends on the XXX
solution to make the post-build
events in the XXX.Test
solution not generate this error (exit with code 4
).
You cannot access elements of an empty vector by subscript.
Always check that the vector is not empty & the index is valid while using the []
operator on std::vector
.
[]
does not add elements if none exists, but it causes an Undefined Behavior if the index is invalid.
You should create a temporary object of your structure, fill it up and then add it to the vector, using vector::push_back()
subject subObj;
subObj.name = s1;
sub.push_back(subObj);
I know this is an old post and you marked the question as answered. I was looking for the same thing recently and I found the histedit
extension very useful. The process is explained here:
http://knowledgestockpile.blogspot.com/2010/12/changing-commit-message-of-revision-in.html
Replace <p> </p>
with
Add as many
as needed.
I solved the same problem by this. Just sharing it.
This is a modern solution I cooked up using font-awesome. Vendor extensions have been omitted for brevity.
HTML
<fieldset>
<label for="color">Select Color</label>
<div class="select-wrapper">
<select id="color">
<option>Red</option>
<option>Blue</option>
<option>Yellow</option>
</select>
<i class="fa fa-chevron-down"></i>
</div>
</fieldset>
SCSS
fieldset {
.select-wrapper {
position: relative;
select {
appearance: none;
position: relative;
z-index: 1;
background: transparent;
+ i {
position: absolute;
top: 40%;
right: 15px;
}
}
}
If your select element has a defined background color, then this won't work as this snippet essentially places the Chevron icon behind the select element (to allow clicking on top of the icon to still initiate the select action).
However, you can style the select-wrapper to the same size as the select element and style its background to achieve the same effect.
Check out my CodePen for a working demo that shows this bit of code on both a dark and light themed select box using a regular label and a "placeholder" label and other cleaned up styles such as borders and widths.
P.S. This is an answer I had posted to another, duplicate question earlier this year.
You're using S_ISREG()
and S_ISDIR()
correctly, you're just using them on the wrong thing.
In your while((dit = readdir(dip)) != NULL)
loop in main
, you're calling stat
on currentPath
over and over again without changing currentPath
:
if(stat(currentPath, &statbuf) == -1) {
perror("stat");
return errno;
}
Shouldn't you be appending a slash and dit->d_name
to currentPath
to get the full path to the file that you want to stat
? Methinks that similar changes to your other stat
calls are also needed.
Use PE Explorer click here to know more and download
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
If you're using .NET 4 or above and you don't want to reference System.Web
, you can use WebUtility.HtmlEncode
from System
var encoded = WebUtility.HtmlEncode(unencoded);
This has the same effect as HttpUtility.HtmlEncode
and should be preferred over System.Security.SecurityElement.Escape
.
For Mac .app
bundles, you should install them via cask, if available, as using symlinks can cause issues. You may even get the following warning if you brew linkapps
:
Unfortunately
brew linkapps
cannot behave nicely with e.g. Spotlight using either aliases or symlinks and Homebrew formulae do not build "proper".app
bundles that can be relocated. Instead, please consider usingbrew cask
and migrate formulae using.app
s to casks.
For MacVim, you can install with:
brew cask install macvim
You should then be able to launch MacVim like you do any other macOS app, including mvim
or open -a MacVim
from a terminal session.
UPDATE: A bit of clarification about brew
and brew cask
. In a nutshell, brew
handles software at the unix level, whereas brew cask
extends the functionality of brew
into the macOS domain for additional functionality such as handling the location of macOS app bundles. Remember that brew
is also implemented on Linux so it makes sense to have this division. There are other resources that explain the difference in more detail, such as What is the difference between brew
and brew cask
?
so I won't say much more here.
For testing how to insert the double quotes in MySQL using the terminal, you can use the following way:
TableName(Name,DString) - > Schema
insert into TableName values("Name","My QQDoubleQuotedStringQQ")
After inserting the value you can update the value in the database with double quotes or single quotes:
update table TableName replace(Dstring, "QQ", "\"")
To clarify Marc's and John Kugelman's answers, you could use:
$('#selectBox option').eq(3).attr('selected', 'selected')
get()
will not work if used in the way specified because it gets the DOM object, not a jQuery object, so the following solution will not work:
$('#selectBox option').get(3).attr('selected', 'selected')
eq()
gets filters the jQuery set to that of the element with the specified index. It's clearer than $($('#selectBox option').get(3))
. It's not all that efficient. $($('#selectBox option')[3])
is more efficient (see test case).
You don't actually need the jQuery object though. This will do the trick:
$('#selectBox option')[3].selected = true;
The attribute "selected" is not how you specify a selected radio button (in Firefox and Chrome at least). Use the "checked" attribute:
$('#selectBox option')[3].checked = true;
The same goes for check-boxes.
Assign the response to a value and test the attributes of it. These should tell you something useful.
response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
use $unwind you will get the first object instead of array of objects
query:
db.getCollection('vehicles').aggregate([
{
$match: {
status: "AVAILABLE",
vehicleTypeId: {
$in: Array.from(newSet(d.vehicleTypeIds))
}
}
},
{
$lookup: {
from: "servicelocations",
localField: "locationId",
foreignField: "serviceLocationId",
as: "locations"
}
},
{
$unwind: "$locations"
}
]);
result:
{
"_id" : ObjectId("59c3983a647101ec58ddcf90"),
"vehicleId" : "45680",
"regionId" : 1.0,
"vehicleTypeId" : "10TONBOX",
"locationId" : "100",
"description" : "Isuzu/2003-10 Ton/Box",
"deviceId" : "",
"earliestStart" : 36000.0,
"latestArrival" : 54000.0,
"status" : "AVAILABLE",
"accountId" : 1.0,
"locations" : {
"_id" : ObjectId("59c3afeab7799c90ebb3291f"),
"serviceLocationId" : "100",
"regionId" : 1.0,
"zoneId" : "DXBZONE1",
"description" : "Masafi Park Al Quoz",
"locationPriority" : 1.0,
"accountTypeId" : 0.0,
"locationType" : "DEPOT",
"location" : {
"makani" : "",
"lat" : 25.123091,
"lng" : 55.21082
},
"deliveryDays" : "MTWRFSU",
"timeWindow" : {
"timeWindowTypeId" : "1"
},
"address1" : "",
"address2" : "",
"phone" : "",
"city" : "",
"county" : "",
"state" : "",
"country" : "",
"zipcode" : "",
"imageUrl" : "",
"contact" : {
"name" : "",
"email" : ""
},
"status" : "",
"createdBy" : "",
"updatedBy" : "",
"updateDate" : "",
"accountId" : 1.0,
"serviceTimeTypeId" : "1"
}
}
{
"_id" : ObjectId("59c3983a647101ec58ddcf91"),
"vehicleId" : "81765",
"regionId" : 1.0,
"vehicleTypeId" : "10TONBOX",
"locationId" : "100",
"description" : "Hino/2004-10 Ton/Box",
"deviceId" : "",
"earliestStart" : 36000.0,
"latestArrival" : 54000.0,
"status" : "AVAILABLE",
"accountId" : 1.0,
"locations" : {
"_id" : ObjectId("59c3afeab7799c90ebb3291f"),
"serviceLocationId" : "100",
"regionId" : 1.0,
"zoneId" : "DXBZONE1",
"description" : "Masafi Park Al Quoz",
"locationPriority" : 1.0,
"accountTypeId" : 0.0,
"locationType" : "DEPOT",
"location" : {
"makani" : "",
"lat" : 25.123091,
"lng" : 55.21082
},
"deliveryDays" : "MTWRFSU",
"timeWindow" : {
"timeWindowTypeId" : "1"
},
"address1" : "",
"address2" : "",
"phone" : "",
"city" : "",
"county" : "",
"state" : "",
"country" : "",
"zipcode" : "",
"imageUrl" : "",
"contact" : {
"name" : "",
"email" : ""
},
"status" : "",
"createdBy" : "",
"updatedBy" : "",
"updateDate" : "",
"accountId" : 1.0,
"serviceTimeTypeId" : "1"
}
}
there are some mistasks in demo http://jsfiddle.net/brandonzylstra/hjk9mvcy/ mentioned by https://stackoverflow.com/users/241142/iconoclast.
in his demo, add these code will works:
setTimeout(() => {
console.log(EntryElm[0].offsetWidth)
}, 0)
Binding = your textual representation of a specific column gets mapped to a physical column in some table, in some database, on some server.
Multipart identifier could be: MyDatabase.dbo.MyTable. If you get any of these identifiers wrong, then you have a multipart identifier that cannot be mapped.
The best way to avoid it is to write the query right the first time, or use a plugin for management studio that provides intellisense and thus help you out by avoiding typos.
for i in {1..600}
do
n=$(($i%5))
wget http://example.com/search/link$n
done
First, you have to locate the project directory in cmd After this fire below command and 'first_laravel_app' is the project name you can replace it with your own project name.
composer create-project laravel/laravel first_laravel_app --prefer-dist
EDIT
I want to add the reason that your IF
statement seems to not work. When you do an EXISTS
on an aggregate, it's always going to be true
. It returns a value even if the ID
doesn't exist. Sure, it's NULL
, but its returning it. Instead, do this:
if exists(select 1 from table where id = 4)
and you'll get to the ELSE
portion of your IF
statement.
Now, here's a better, set-based solution:
update b
set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
on b.id = a.id
where
b.id = yourid
This has the benefit of being able to run on the entire table rather than individual ids.
Here it is:
s = "123"
try:
i = int(s)
except ValueError as verr:
pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
pass # do job to handle: Exception occurred while converting to int
To my surprise you do not need users-permission CONTACT_READ to read the names and some basic information (Is the contact starred, what was the last calling time). However you do need permission to read the details of the contact like phone number.
Use document.scrollTop
to change the position of the document. Set the scrollTop
of the document
equal to the bottom
of the featured section of your site
This was a problem with the user having deny privileges as well; in my haste to grant permissions I basically gave the user everything. And deny was killing it. So as soon as I removed those permissions it worked.
Call getActivity() method inside the onActivityCreated()
RDDs extend the Serialisable interface, so this is not what's causing your task to fail. Now this doesn't mean that you can serialise an RDD
with Spark and avoid NotSerializableException
Spark is a distributed computing engine and its main abstraction is a resilient distributed dataset (RDD), which can be viewed as a distributed collection. Basically, RDD's elements are partitioned across the nodes of the cluster, but Spark abstracts this away from the user, letting the user interact with the RDD (collection) as if it were a local one.
Not to get into too many details, but when you run different transformations on a RDD (map
, flatMap
, filter
and others), your transformation code (closure) is:
You can of course run this locally (as in your example), but all those phases (apart from shipping over network) still occur. [This lets you catch any bugs even before deploying to production]
What happens in your second case is that you are calling a method, defined in class testing
from inside the map function. Spark sees that and since methods cannot be serialized on their own, Spark tries to serialize the whole testing
class, so that the code will still work when executed in another JVM. You have two possibilities:
Either you make class testing serializable, so the whole class can be serialized by Spark:
import org.apache.spark.{SparkContext,SparkConf}
object Spark {
val ctx = new SparkContext(new SparkConf().setAppName("test").setMaster("local[*]"))
}
object NOTworking extends App {
new Test().doIT
}
class Test extends java.io.Serializable {
val rddList = Spark.ctx.parallelize(List(1,2,3))
def doIT() = {
val after = rddList.map(someFunc)
after.collect().foreach(println)
}
def someFunc(a: Int) = a + 1
}
or you make someFunc
function instead of a method (functions are objects in Scala), so that Spark will be able to serialize it:
import org.apache.spark.{SparkContext,SparkConf}
object Spark {
val ctx = new SparkContext(new SparkConf().setAppName("test").setMaster("local[*]"))
}
object NOTworking extends App {
new Test().doIT
}
class Test {
val rddList = Spark.ctx.parallelize(List(1,2,3))
def doIT() = {
val after = rddList.map(someFunc)
after.collect().foreach(println)
}
val someFunc = (a: Int) => a + 1
}
Similar, but not the same problem with class serialization can be of interest to you and you can read on it in this Spark Summit 2013 presentation.
As a side note, you can rewrite rddList.map(someFunc(_))
to rddList.map(someFunc)
, they are exactly the same. Usually, the second is preferred as it's less verbose and cleaner to read.
EDIT (2015-03-15): SPARK-5307 introduced SerializationDebugger and Spark 1.3.0 is the first version to use it. It adds serialization path to a NotSerializableException. When a NotSerializableException is encountered, the debugger visits the object graph to find the path towards the object that cannot be serialized, and constructs information to help user to find the object.
In OP's case, this is what gets printed to stdout:
Serialization stack:
- object not serializable (class: testing, value: testing@2dfe2f00)
- field (class: testing$$anonfun$1, name: $outer, type: class testing)
- object (class testing$$anonfun$1, <function1>)
There are several helpful bits of code for this.
Place your cursor in a merged cell and ask these questions in the Immidiate Window:
Is the activecell a merged cell?
? Activecell.Mergecells
True
How many cells are merged?
? Activecell.MergeArea.Cells.Count
2
How many columns are merged?
? Activecell.MergeArea.Columns.Count
2
How many rows are merged?
? Activecell.MergeArea.Rows.Count
1
What's the merged range address?
? activecell.MergeArea.Address
$F$2:$F$3
To keep this simple, I just changed the directory from which I was importing the data to a local folder on the server.
I had the file located on a shared folder, I just copied my files to "c:\TEMP\Reports" on my server (updated the query to BULK INSERT from the new folder). The Agent task completed successfully :)
Finally after a long time I'm able to BULK Insert automatically via agent job.
Best regards.
It means you're calling http from https. You can use src="//url.to/script.js"
in your script tag and it will auto-detect.
Alternately you can use use https in your src
even if you will be publishing it to a http page. This will avoid the potential issue mentioned in the comments.
Java 8...
String joined = String.join("+", list);
Documentation: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-
You can use a very nice tool called Stetho
by adding this to build.gradle
file:
compile 'com.facebook.stetho:stetho:1.4.1'
And initialized it inside your Application
or Activity
onCreate()
method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Stetho.initializeWithDefaults(this);
setContentView(R.layout.activity_main);
}
Then you can view the db records in chrome in the address:
chrome://inspect/#devices
For more details you can read my post: How to view easily your db records
There's no property you can flip to make this just happen magically. Look at the events for the form and it becomes fairly trivial to implement this by setting this.Top
and this.Left
. Specifically you'll want to look at MouseDown
, MouseUp
and MouseMove
.
public function updtitle()
{
$data = array(
'table_name' => 'your_table_name_to_update', // pass the real table name
'id' => $this->input->post('id'),
'title' => $this->input->post('title')
);
$this->load->model('Updmodel'); // load the model first
if($this->Updmodel->upddata($data)) // call the method from the model
{
// update successful
}
else
{
// update not successful
}
}
public function upddata($data) {
extract($data);
$this->db->where('emp_no', $id);
$this->db->update($table_name, array('title' => $title));
return true;
}
The active record query is similar to
"update $table_name set title='$title' where emp_no=$id"
I also experienced this error when working with CMake:
No CMAKE_C_COMPILER could be found.
No CMAKE_CXX_COMPILER could be found.
The 'warning' box in the MSDN library article Visual C++ in Visual Studio 2015 gave me the help that I needed.
Visual Studio 2015 doesn't come with C++ installed by default. So, creating a new C++ project will prompt you to download the necessary C++ components.
According to the php manual, the finfo-file function is best way to do this. However, you will need to install the FileInfo PECL extension.
If the extension is not an option, you can use the outdated mime_content_type function.
I found this piece of code somewhere in the web. Maybe it helps you and I give you an update so far I accomodated it for the same purpose... Maybe I don't.... who the futt knows... with all the nogodders and dobedders in here :-/
function runVLC(target, stream)
{
var support=true
var addr='rtsp://' + window.location.hostname + stream
if ($.browser.msie){
$(target).html('<object type = "application/x-vlc-plugin"' + 'version =
"VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' +
'events = "true"' + 'id = "vlc"></object>')
}
else if ($.browser.mozilla || $.browser.webkit){
$(target).html('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' +
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' +
'width="660" height="372"' +
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' +
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' +
'branding="false"' + 'controls="false"' + 'aspectRatio="16:9"' +
'target="whatever.mp4"></embed>')
}
else{
support=false
$(target).empty().html('<div id = "dialog_error">Error: browser not supported!</div>')
}
if (support){
var vlc = document.getElementById('vlc')
if (vlc){
var opt = new Array(':network-caching=300')
try{
var id = vlc.playlist.add(addr, '', opt)
vlc.playlist.playItem(id)
}
catch (e){
$(target).empty().html('<div id = "dialog_error">Error: ' + e + '<br>URL: ' + addr +
'</div>')
}
}
}
}
/* $(target + ' object').css({'width': '100%', 'height': '100%'}) */
Greets
Gee
I reduce the whole crap now to:
function runvlc(){
var target=$('body')
var error=$('#dialog_error')
var support=true
var addr='rtsp://../html/media/video/TESTCARD.MP4'
if (navigator.userAgent.toLowerCase().indexOf("msie")!=-1){
target.append('<object type = "application/x-vlc-plugin"' + 'version = "
VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' +
'events = "true"' + 'id = "vlc"></object>')
}
else if (navigator.userAgent.toLowerCase().indexOf("msie")==-1){
target.append('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' +
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' +
'width="660" height="372"' +
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' +
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' +
'branding="false"' +
'controls="false"' + 'aspectRatio="16:9"' + 'target="whatever.mp4">
</embed>')
}
else{
support=false
error.empty().html('Error: browser not supported!')
error.show()
if (support){
var vlc=document.getElementById('vlc')
if (vlc){
var options=new Array(':network-caching=300') /* set additional vlc--options */
try{ /* error handling */
var id = vlc.playlist.add(addr,'',options)
vlc.playlist.playItem(id)
}
catch (e){
error.empty().html('Error: ' + e + '<br>URL: ' + addr + '')
error.show()
}
}
}
}
};
Didn't get it to work in ie as well... 2b continued...
Greets
Gee
I don't see any problem, unless you are not managing them using a connection pool.
If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
Make #site_nav_global_primary
positioned as fixed and set width to 100 % and desired height.
Your error is in resultCode = Activity.RESULT_CANCELED
, you should instance like resultCode == Activity.RESULT_CANCELED
==
If you don't need the code to be portable to old unices, you can use clock_gettime(), which will give you the time in nanoseconds (if your processor supports that resolution). It's POSIX, but from 2001.
Try this ( also corrected check for upper case and lower case, it had a bug since you grouped them as [a-zA-Z] it only looks for atleast one lower or upper. So separated them out ):
(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)^(.{8,15})$
Update: I found that the regex doesn't really work as expected and this is not how it is supposed to be written too!
Try something like this:
(?=^.{8,15}$)(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?!.*\s).*$
(Between 8 and 15 inclusive, contains atleast one digit, atleast one upper case and atleast one lower case and no whitespace.)
And I think this is easier to understand as well.
I spent most of last week at a university library studying debugging of concurrent code. The central problem is concurrent code is non-deterministic. Typically, academic debugging has fallen into one of three camps here:
Now, as above commentators have noticed, you can design your concurrent system into a more deterministic state. However, if you don't do that properly, you're just back to designing a sequential system again.
My suggestion would be to focus on having a very strict design protocol about what gets threaded and what doesn't get threaded. If you constrain your interface so that there is minimal dependancies between elements, it is much easier.
Good luck, and keep working on the problem.
I found emailonacid.com today (beta, currently free†) - have only played with it a little but so far so good. It simulates the following clients:
The very helpful thing about this service is it tells you what code is not supported in which client.
†Edit: Not free anymore, but provides a 7 day free trial.
Simple solution without using delegate:
TEXT_FIELD.addTarget(self, action: #selector(editingChanged(sender:)), for: .editingChanged)
@objc private func editingChanged(sender: UITextField) {
if let text = sender.text, text.count >= MAX_LENGHT {
sender.text = String(text.dropLast(text.count - MAX_LENGHT))
return
}
}
I wrote an article on this on my blog: http://www.ebenmonney.com/blog/how-to-implement-remember-me-functionality-using-token-based-authentication-and-localstorage-in-a-web-application .
Using a library I created storageManager
you can achieve this as follows:
storageManager.savePermanentData('data', 'key'): //saves permanent data
storageManager.saveSyncedSessionData('data', 'key'); //saves session data to all opened tabs
storageManager.saveSessionData('data', 'key'); //saves session data to current tab only
storageManager.getData('key'); //retrieves data
There are other convenient methods as well to handle other scenarios as well
If you are facing this issue in a .ts file which is only there to provide you some constant values, then you can just
rename your .ts file to .js file
and the error will not come again.
For me the following worked on Jenkins 2.190.1 and was much simpler than some of the other workarounds:
matcher = manager.getLogMatcher('^.*Text we want comes next: (.*)$');
if (matcher.matches()) {
def myVar = matcher.group(1);
def envVar = new EnvVars([MY_ENV_VAR: myVar]);
def newEnv = Environment.create(envVar);
manager.build.environments.add(0, newEnv);
// now the matched text from the LogMatcher is passed to an
// env var we can access at $MY_ENV_VAR in post build steps
}
This was using the Groovy Script plugin with no additional changes to Jenkins.
I have noticed this behavior before as well. I have noticed that the SelectedIndex property doesn't cause the same bug. If you can restructure your ViewModel to expose the index of the selected item, and bind to that, you should be good to go.
You should retrieve RecyclerView
in a Fragment
after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
final FragmentActivity c = getActivity();
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
new Thread(new Runnable() {
@Override
public void run() {
final RecyclerAdapter adapter = new RecyclerAdapter(c);
c.runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerView.setAdapter(adapter);
}
});
}
}).start();
return view;
}
If you have a solution open, and TFS is down, you might have trouble going into offline mode. If you close and reopen your solution, a nice little dialog will appear asking you if you want to Go Offline.
Alternatively if you don't want to close/reopen the solution, (as suggested by Bernie) you can install the TFS Go-Offline plugin, then click:
TEAM -> Go Offline
I came across this question, and I will add my solution for those who may be looking for something similar. My approach was just to make a random file name from ascii
characters. It will be unique with a good probability.
from random import sample
from string import digits, ascii_uppercase, ascii_lowercase
from tempfile import gettempdir
from os import path
def rand_fname(suffix, length=8):
chars = ascii_lowercase + ascii_uppercase + digits
fname = path.join(gettempdir(), 'tmp-'
+ ''.join(sample(chars, length)) + suffix)
return fname if not path.exists(fname) \
else rand_fname(suffix, length)
There is a new option called validateStatus
in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:
const {status} = axios.get('foo.com', {validateStatus: () => true})
In Urlmon.dll, there's a function called FindMimeFromData
.
From the documentation
MIME type detection, or "data sniffing," refers to the process of determining an appropriate MIME type from binary data. The final result depends on a combination of server-supplied MIME type headers, file extension, and/or the data itself. Usually, only the first 256 bytes of data are significant.
So, read the first (up to) 256 bytes from the file and pass it to FindMimeFromData
.
This worked for me
open config.inc.php file in phpmyadmin root, set auth type from cookie to config
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = ''; // leave blank if no password
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
I understand the question as this: you want to completely replace the contents of one file (or a selection) from upstream. You don't want to affect the index directly (so you would go through add + commit as usual).
Simply do
git checkout remote/branch -- a/file b/another/file
If you want to do this for extensive subtrees and instead wish to affect the index directly use
git read-tree remote/branch:subdir/
You can then (optionally) update your working copy by doing
git checkout-index -u --force
In my case the only working solution to check if last arguments exists is:
if [[ "$7" == '' ]] ; then
echo "error"
exit
fi
If we use a template-light-solution (as shown above) like the following:
namespace std {
template<typename T>
std::string to_string(const T &n) {
std::ostringstream s;
s << n;
return s.str();
}
}
Unfortunately, we will have problems in some cases. For example, for static const members:
hpp
class A
{
public:
static const std::size_t x = 10;
A();
};
cpp
A::A()
{
std::cout << std::to_string(x);
}
And linking:
CMakeFiles/untitled2.dir/a.cpp.o:a.cpp:(.rdata$.refptr._ZN1A1xE[.refptr._ZN1A1xE]+0x0): undefined reference to `A::x'
collect2: error: ld returned 1 exit status
Here is one way to solve the problem (add to the type size_t):
namespace std {
std::string to_string(size_t n) {
std::ostringstream s;
s << n;
return s.str();
}
}
HTH.
If you look into the source of java.lang.Runtime, you'll see exec finally call protected method: execVM, which means it uses Virtual memory. So for Unix-like system, VM depends on amount of swap space + some ratio of physical memory.
Michael's answer did solve your problem but it might (or to say, would eventually) cause the O.S. deadlock in memory allocation issue since 1 tell O.S. less careful of memory allocation & 0 is just guessing & obviously that you are lucky that O.S. guess you can have memory THIS TIME. Next time? Hmm.....
Better approach is that you experiment your case & give a good swap space & give a better ratio of physical memory used & set value to 2 rather than 1 or 0.
I got this error on my ASP.Net 4.5 app on Windows Server 2012 R2.
Go to start menu -> "Turn windows features on or off". A wizard popped up for me.
Click Next to Server Roles
I had to check these to get this to work, located under Web Server IIS->Web Server-> Application Development (these are based on Jeremy Cook's answer above):
Then click next to Features and make sure the following is checked:
Then click next and Install. At this point, the error went away for me. Good luck!
I found the solution : it's the 9th byte of this key :
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections] "DefaultConnectionSettings"=hex:3c,00,00,00,1f,00,00,00,05,00,00,00,00,00,00, 00,00,00,00,00,00,00,00,00,01,00,00,00,1f,00,00,00,68,74,74,70,3a,2f,2f,31, 34,34,2e,31,33,31,2e,32,32,32,2e,31,36,37,2f,77,70,61,64,2e,64,61,74,90,0e, 1e,66,d3,88,c5,01,01,00,00,00,8d,a8,4e,9e,00,00,00,00,00,00,00,00
It's a bitfield:
Mask 0x8 to turn it off, i.e., subtract 8 if it's higher than 8.
Thanks to Jamie on google groups.
Update
Based on the VBScript by WhoIsRich combined with details in this answer, here's a PowerShell script to amend these & related settings:
function Set-ProxySettings {
[CmdletBinding()]
param ( #could improve with parameter sets
[Parameter(Mandatory = $false)]
[bool]$AutomaticDetect = $true
,
[Parameter(Mandatory = $false)]
[bool]$UseProxyForLAN = $false
,
[Parameter(Mandatory = $false)]
[AllowNull()][AllowEmptyString()]
[string]$ProxyAddress = $null
,
[Parameter(Mandatory = $false)]
[int]$ProxyPort = 8080 #closest we have to a default port for proxies
,
[AllowNull()][AllowEmptyString()]
[bool]$UseAutomaticConfigurationScript = $false
)
begin {
[string]$ProxyRegRoot = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
[string]$DefaultConnectionSettingsPath = (Join-Path $ProxyRegRoot 'Connections')
[byte]$MaskProxyEnabled = 2
[byte]$MaskUseAutomaticConfigurationScript = 4
[byte]$MaskAutomaticDetect = 8
[int]$ProxyConnectionSettingIndex = 8
}
process {
#this setting is affected by multiple options, so fetch once here
[byte[]]$DefaultConnectionSettings = Get-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' | Select-Object -ExpandProperty 'DefaultConnectionSettings'
#region auto detect
if($AutomaticDetect) {
Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 1
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskAutomaticDetect
} else {
Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 0
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskAutomaticDetect)
}
#endregion
#region defined proxy
if($UseProxyForLAN) {
if(-not ([string]::IsNullOrWhiteSpace($ProxyAddress))) {
Set-ItemProperty -Path $ProxyRegRoot -Name ProxyServer -Value ("{0}:{1}" -f $ProxyAddress,$ProxyPort)
}
Set-ItemProperty -Path $ProxyRegRoot -Name ProxyEnable -Value 1
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskProxyEnabled
} else {
Set-ItemProperty -Path $ProxyRegRoot -Name ProxyEnable -Value 0
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskProxyEnabled)
}
#endregion
#region config script
if($UseAutomaticConfigurationScript){
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskUseAutomaticConfigurationScript
}else{
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskUseAutomaticConfigurationScript)
}
#endregion
#persist the updates made above
Set-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' -Value $DefaultConnectionSettings
}
}
Any way to do this without manually re-installing the packages in a new virtualenv to get their dependencies ? This would be error-prone and I'd like to automate the process of cleaning the virtualenv from no-longer-needed old dependencies.
That's what pip-tools package is for (from https://github.com/jazzband/pip-tools):
$ pip install --upgrade pip # pip-tools needs pip==6.1 or higher (!)
$ pip install pip-tools
Suppose you have a Flask project, and want to pin it for production. Write the following line to a file:
# requirements.in
Flask
Now, run pip-compile requirements.in:
$ pip-compile requirements.in
#
# This file is autogenerated by pip-compile
# Make changes in requirements.in, then run this to update:
#
# pip-compile requirements.in
#
flask==0.10.1
itsdangerous==0.24 # via flask
jinja2==2.7.3 # via flask
markupsafe==0.23 # via jinja2
werkzeug==0.10.4 # via flask
And it will produce your requirements.txt
, with all the Flask dependencies (and all underlying dependencies) pinned. Put this file under version control as well and periodically re-run pip-compile
to update the packages.
Now that you have a requirements.txt
, you can use pip-sync
to update your virtual env to reflect exactly what's in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt
contents.
$ pip-sync
Uninstalling flake8-2.4.1:
Successfully uninstalled flake8-2.4.1
Collecting click==4.1
Downloading click-4.1-py2.py3-none-any.whl (62kB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 65kB 1.8MB/s
Found existing installation: click 4.0
Uninstalling click-4.0:
Successfully uninstalled click-4.0
Successfully installed click-4.1
The best part of working with any open source technology is that you can inspect length and breadth of it. Checkout this link
find_by ~> Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns nil.
find ~> Finds the first record matching the specified conditions , but if no record is found, it raises an exception but that is done deliberately.
Do checkout the above link, it has all the explanation and use cases for the following two functions.
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
use this function it works for me
public byte[] toByteArray(int value) {
return new byte[] {
(byte)(value >> 24),
(byte)(value >> 16),
(byte)(value >> 8),
(byte)value};
}
it translates the int into a byte value
Try This one:: Libav in Linux
Installation: run command
sudo apt-get install libav-tools
Video conversion command::Go to folder contains the video and run in terminal
avconv -i oldvideo.flv -ar 22050 convertedvideo.mp4
This particular error is one annoying fact about v8. In most cases your JavaScript is broken in some way. For example missing a }
or something like that.
Example given, this will yield "Unexpected end of input" too:
eval('[{"test": 4}') // notice the missing ]
But the root cause of the problems seems to be that the requested JSON url has a Content-Type of text/html
which Chrome apparently tries to parse as HTML, which then results in the unexpected end of input due to the fact that the included image tags are being parsed.
Try setting the Content-Type to text/plain
I think it should fix the issues.
Nonetheless, V8 could do a better Job about telling one exactly where the input ended unexpectedly.
You can't resize the array, per se, but you can create a new array and efficiently copy the elements from the old array to the new array using some utility function like this:
public static int[] removeElement(int[] original, int element){
int[] n = new int[original.length - 1];
System.arraycopy(original, 0, n, 0, element );
System.arraycopy(original, element+1, n, element, original.length - element-1);
return n;
}
A better approach, however, would be to use an ArrayList (or similar List structure) to store your data and then use its methods to remove elements as needed.
The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.
There is a promising answer at Problem updating bokeh: [WinError 126] The specified module could not be found.
It hints at https://github.com/conda/conda/issues/9313.
There, you find:
It's a library load issue. More details at github.com/conda/conda/issues/8836 You probably have a broken conda right now. You can use a standalone conda from repo.anaconda.com/pkgs/misc/conda-execs to repair it: standalone-conda.exe update -p C:\ProgramData\Anaconda3 conda-package-handling You should get version 1.6.0, and the problems should go away.
Thus, it might simply be a conda issue. Reinstalling standalone conda might repair the error. Please comment whoever can confirm this.
My synopsis of rfc2397 is:
Once you've got your base64 encoded image data put it inside the <Image></Image> tags prefixed with "data:{mimetype};base64,
" this is similar to the prefixing done in the parenthesis of url()
definition in CSS or in the quoted value of the src
attribute of the img
tag in [X]HTML. You can test the data url in firefox by putting the data:image/...
line into the URL field and pressing enter, it should show your image.
For actually encoding I think we need to go over all your options, not just PHP, because there's so many ways to base64 encode something.
base64
command line tool. It's part of the GNU coreutils (v6+) and pretty much default in any Cygwin, Linux, GnuWin32 install, but not the BSDs I tried. Issue: $ base64 imagefile.ico > imagefile.base64.txt
A note on mime-types:
I would prefer you use one of image/png
image/jpeg
or image/gif
as I can't find the popular image/x-icon
. Should that be image/vnd.microsoft.icon
?
Also the other formats are much shorter.
compare 265 bytes vs 1150 bytes:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=
data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAD/////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv///////////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb///////////9mZmb/ZmZm//////////////////////////////////////////////////////9mZmb/ZmZm////////////ZmZm/2ZmZv//////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv//////ZmZm/2ZmZv///////////2ZmZv9mZmb//////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb//////2ZmZv9mZmb///////////9mZmb/ZmZm////////////////////////////8fX4/8nW5P+twtb/oLjP//////9mZmb/ZmZm////////////////////////////oLjP/3eZu/9pj7T/M2aZ/zNmmf8zZpn/M2aZ/zNmmf///////////////////////////////////////////zNmmf8zZpn/M2aZ/zNmmf8zZpn/d5m7/6C4z/+WwuH/wN/3//////////////////////////////////////+guM//rcLW/8nW5P/x9fj//////9/v+/+w1/X/QZ7m/1Cm6P//////////////////////////////////////////////////////7/f9/4C+7v8xluT/EYbg/zGW5P/A3/f/0933/9Pd9//////////////////////////////////f7/v/YK7q/xGG4P8RhuD/MZbk/7DX9f//////4uj6/zJh2/8yYdv/8PT8////////////////////////////UKbo/xGG4P8xluT/sNf1////////////4uj6/zJh2/8jVtj/e5ro/////////////////////////////////8Df9/+gz/P/////////////////8PT8/0944P8jVtj/bI7l/////////////////////////////////////////////////////////////////2yO5f8jVtj/T3jg//D0/P///////////////////////////////////////////////////////////3ua6P8jVtj/MmHb/+Lo+v////////////////////////////////////////////////////////////D0/P8yYdv/I1bY/9Pd9///////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
You need to use font-url
in your @font-face block, not url
@font-face {
font-family: 'Inconsolata';
src:font-url('Inconsolata-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
as well as this line in application.rb, as you mentioned (for fonts in app/assets/fonts
config.assets.paths << Rails.root.join("app", "assets", "fonts")
The best solution is to override the Django base.html template. Make another base.html template under admin directory. Make an admin directory first if it does not exist. app/admin/base.html.
Add {% block extrahead %}
to the overriding template.
{% extends 'admin/base.html' %}
{% load staticfiles %}
{% block javascripts %}
{{ block.super }}
<script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>
{% endblock %}
{% block extrahead %}
<link rel="shortcut icon" href="{% static 'app/img/favicon.ico' %}" />
{% endblock %}
{% block stylesheets %}
{{ block.super }}
{% endblock %}
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
Since you add ..
after cmake, it will jump up and up (just like cd ..
) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use .
instead of ..
.
You could try something like this (copied from the jQuery Ajax examples)
var request = $.ajax({
url: "script.php",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
console.log( msg );
});
request.fail(function(jqXHR, textStatus) {
console.log( "Request failed: " + textStatus );
});
The problem with your original code is that the error argument you pass into your on function isn't actually coming from anywhere. JQuery on doesn't return a second argument, and even if it did, it would relate to the click event not the Ajax call.
Also iftop:
display bandwidth usage on an interface
iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...
The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService
" as the service reference name, that will generate the type TestUploaderWebService.Service1
. That class will have a method named GetFileListOnWebServer
, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:
string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
proxy = new TestUploaderWebService.Service1();
files = proxy.GetFileListOnWebServer();
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.
Just got this problem on a development machine (production works just fine). I modify my config in IIS to allow anonymous access and put my name and password as credential.
Not the best way I am sure but it works for testing purposes.
Actually the navigation bar on tablets (at least Nexus 7) has different size in portrait and landscape so this function should look like this:
private int getNavigationBarHeight(Context context, int orientation) {
Resources resources = context.getResources();
int id = resources.getIdentifier(
orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape",
"dimen", "android");
if (id > 0) {
return resources.getDimensionPixelSize(id);
}
return 0;
}
It all depends really, if you're using the DataGrid from the WPF Toolkit then there is a built in sort, even a multi-column sort which is very useful. Check more out here:
Alternatively, if you're using a different control that doesn't support sorting, i'd recommend the following methods:
Followed by:
You have to use HorizontalContentAlignment="Center" and! Width="Auto".
On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
on myServerAddress
, write the name of your installed instance (by default it's .\SQLEXPRESS
for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.
edit
You will need to omit username and password for windows authentication and add Integrated Security=SSPI
.
Use ANSI syntax and it will be a lot more clear how you are joining the tables:
SELECT s.name as Student, c.name as Course
FROM student s
INNER JOIN bridge b ON s.id = b.sid
INNER JOIN course c ON b.cid = c.id
ORDER BY s.name
I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics
If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.
Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.
The way I worked about the same problem
IntervalTrees
or LineSweepAlgo
GrahamScanAlgo
to find a closed path with adjacent verticesDinicAlgo
to Dissolve themnote: my scenario was different given the polygons had a common vertice. But Hope this can help
On some systems (Windows with VC springs to mind, currently), RAND_MAX
is ridiculously small, i. e. only 15 bit. When dividing by RAND_MAX
you are only generating a mantissa of 15 bit instead of the 23 possible bits. This may or may not be a problem for you, but you're missing out some values in that case.
Oh, just noticed that there was already a comment for that problem. Anyway, here's some code that might solve this for you:
float r = (float)((rand() << 15 + rand()) & ((1 << 24) - 1)) / (1 << 24);
Untested, but might work :-)
Am I the only one who finds unwinding lists boring? ;-)
Let's try with objects. Real world example by the way.
Given: Object representing repetitive task. About important task fields: reminders are starting to ring at start
and repeat every repeatPeriod
repeatUnit
(e.g. 5 HOURS) and there will be repeatCount
reminders in total(including starting one).
Goal: achieve a list of task copies, one for each task reminder invocation.
List<Task> tasks =
Arrays.asList(
new Task(
false,//completed sign
"My important task",//task name (text)
LocalDateTime.now().plus(2, ChronoUnit.DAYS),//first reminder(start)
true,//is task repetitive?
1,//reminder interval
ChronoUnit.DAYS,//interval unit
5//total number of reminders
)
);
tasks.stream().flatMap(
x -> LongStream.iterate(
x.getStart().toEpochSecond(ZoneOffset.UTC),
p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds())
).limit(x.getRepeatCount()).boxed()
.map( y -> new Task(x,LocalDateTime.ofEpochSecond(y,0,ZoneOffset.UTC)))
).forEach(System.out::println);
Output:
Task{completed=false, text='My important task', start=2014-10-01T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-02T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-03T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-04T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-05T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
P.S.: I would appreciate if someone suggested a simpler solution, I'm not a pro after all.
UPDATE:
@RBz asked for detailed explanation so here it is.
Basically flatMap puts all elements from streams inside another stream into output stream. A lot of streams here :). So, for each Task in initial stream lambda expression x -> LongStream.iterate...
creates a stream of long values that represent task start moments. This stream is limited to x.getRepeatCount()
instances. It's values start from x.getStart().toEpochSecond(ZoneOffset.UTC)
and each next value is calculated using lambda p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds()
. boxed()
returns the stream with each long value as a Long wrapper instance. Then each Long in that stream is mapped to new Task instance that is not repetitive anymore and contains exact execution time. This sample contains only one Task in input list. But imagine that you have a thousand. You will have then a stream of 1000 streams of Task objects. And what flatMap
does here is putting all Tasks from all streams onto the same output stream. That's all as I understand it. Thank you for your question!
function trimNumber(num, len) {
const modulu_one = 1;
const start_numbers_float=2;
var int_part = Math.trunc(num);
var float_part = String(num % modulu_one);
float_part = float_part.slice(start_numbers_float, start_numbers_float+len);
return int_part+'.'+float_part;
}
To start recording your device’s screen, run the following command:
adb shell screenrecord /sdcard/example.mp4
This command will start recording your device’s screen using the default settings and save the resulting video to a file at /sdcard/example.mp4 file on your device.
When you’re done recording, press Ctrl+C in the Command Prompt window to stop the screen recording. You can then find the screen recording file at the location you specified. Note that the screen recording is saved to your device’s internal storage, not to your computer.
The default settings are to use your device’s standard screen resolution, encode the video at a bitrate of 4Mbps, and set the maximum screen recording time to 180 seconds. For more information about the command-line options you can use, run the following command:
adb shell screenrecord --help
This works without rooting the device. Hope this helps.
If you don't want to install Non-Microsoft tools, please download STRINGS.EXE from Microsoft Sysinternals and make a procedure like this one:
@echo off
if '%1' == '' goto NOPARAM
if '%2' == '' goto NOPARAM
if not exist %1 goto NOFOLDER
echo ------------------------------------------
echo - %1 : folder
echo - %2 : string to be searched in the folder
echo - PLEASE WAIT FOR THE RESULTS ...
strings -s %1\* | findstr /i %2 > grep.txt
notepad.exe grep.txt
goto END
:NOPARAM rem - input command not correct
echo ====================================
echo Usage of GREP.CMD:
echo Grep "SearchFolder" SearchString
echo Please specify all parameters
echo ====================================
goto END
:NOFOLDER
echo Folder %1 does not exist
goto END
:END rem - exit
Yes. It is also true for for
scope. But not functions of course.
In your example: if the condition in the if
statement is false, x
will not be defined though.
I tried all above, but none working
Finally tried this my own
getBaseActivity().getFragmentManager()
and is working .. :)
If you want to invoke the JavaScript function on the Parent from the iframe generated by another function ex shadowbox or lightbox.
You should try to make use of window
object and invoke parent function:
window.parent.targetFunction();
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
Or you can access root terminal by typing sudo -s
As xerq's excellent answer explains, this is a DNS timeout issue.
I wanted to contribute another possible answer for those of you using Windows Subsystem for Linux - there are some cases where something seems to be askew in the client OS after Windows resumes from sleep. Restarting the host OS will fix these issues (it's also likely restarting the WSL service will do the same).
The new way to do with c++20 is using format.
#include <format>
auto var = std::format("sometext {} sometext {}", somevar, somevar);
import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)
In this way all the messages of level=INFO from urllib3 won't be present in the logfile.
So you can continue to use the level=INFO for your log messages...just modify this for the library you are using.
Something like this?
public static T ConvertValue<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
You can then use it like this:
int val = ConvertValue<int>("42");
Edit:
You can even do this more generic and not rely on a string
parameter provided the type U
implements IConvertible
- this means you have to specify two type parameters though:
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
I considered catching the InvalidCastException
exception that might be raised by Convert.ChangeType()
- but what would you return in this case? default(T)
? It seems more appropriate having the caller deal with the exception.
This tutorial should help you:
Getting Started with Oracle SQL Developer
See the prerequisites:
Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:
alter user hr identified by hr account unlock;
Download and unzip the sqldev_mngdb.zip file that contains all the files you need to perform this tutorial.
Another version from May 2011: Getting Started with Oracle SQL Developer
For more info check this related question:
How to create a new database after initally installing oracle database 11g Express Edition?
mysqlclient is the best as others only provide support to specific versions of python
pip install mysqlclient
example code
import mysql.connector
import _mysql
db=_mysql.connect("127.0.0.1","root","umer","sys")
#db=_mysql.connect(host,user,password,db)
# Example of how to insert new values:
db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
db.store_result()
db.query("SELECT * FROM new1.table1 ;")
#new1 is scheme table1 is table mysql
res= db.store_result()
for i in range(res.num_rows()):
print(result.fetch_row())
With Moment.js simply use:
var jsDate = moment(netDateTime).toDate();
Where netDateTime
is your DateTime variable serialized, something like "/Date(1456956000000+0200)/"
.
Another one from Delphi, which I think is a little more rigorous than the other Delphi example submitted. This can easily turn into a golfing match, but I've tried to make mine readable.
Edit0: I was curious about the performance characteristics, so I did a little test. On my machine, I ran this function against a 60 character string 50 million times, and it took 5 seconds.
function TForm1.IsPalindrome(txt: string): boolean;
var
i, halfway, len : integer;
begin
Result := True;
len := Length(txt);
{
special cases:
an empty string is *never* a palindrome
a 1-character string is *always* a palindrome
}
case len of
0 : Result := False;
1 : Result := True;
else begin
halfway := Round((len/2) - (1/2)); //if odd, round down to get 1/2way pt
//scan half of our string, make sure it is mirrored on the other half
for i := 1 to halfway do begin
if txt[i] <> txt[len-(i-1)] then begin
Result := False;
Break;
end; //if we found a non-mirrored character
end; //for 1st half of string
end; //else not a special case
end; //case
end;
And here is the same thing, in C#, except that I've left it with multiple exit points, which I don't like.
private bool IsPalindrome(string txt) {
int len = txt.Length;
/*
Special cases:
An empty string is *never* a palindrome
A 1-character string is *always* a palindrome
*/
switch (len) {
case 0: return false;
case 1: return true;
} //switch
int halfway = (len / 2);
//scan half of our string, make sure it is mirrored on the other half
for (int i = 0; i < halfway; ++i) {
if (txt.Substring(i,1) != txt.Substring(len - i - 1,1)) {
return false;
} //if
} //for
return true;
}