I think you misunderstand Unicode and its relationship to Perl. No matter which way you store data, Unicode, ISO-8859-1, or many other things, your program has to know how to interpret the bytes it gets as input (decoding) and how to represent the information it wants to output (encoding). Get that interpretation wrong and you garble the data. There isn't some magic default setup inside your program that's going to tell the stuff outside your program how to act.
You think it's hard, most likely, because you are used to everything being ASCII. Everything you should have been thinking about was simply ignored by the programming language and all of the things it had to interact with. If everything used nothing but UTF-8 and you had no choice, then UTF-8 would be just as easy. But not everything does use UTF-8. For instance, you don't want your input handle to think that it's getting UTF-8 octets unless it actually is, and you don't want your output handles to be UTF-8 if the thing reading from them can't handle UTF-8. Perl has no way to know those things. That's why you are the programmer.
I don't think Unicode in Perl 5 is too complicated. I think it's scary and people avoid it. There's a difference. To that end, I've put Unicode in Learning Perl, 6th Edition, and there's a lot of Unicode stuff in Effective Perl Programming. You have to spend the time to learn and understand Unicode and how it works. You're not going to be able to use it effectively otherwise.
No matter how I tried, the errorlevel always stays 0 even when msbuild failed. So I built my workaround:
Build Project and save log to Build.log
SET Build_Opt=/flp:summary;logfile=Build.log;append=true
msbuild "myproj.csproj" /t:rebuild /p:Configuration=release /fl %Build_Opt%
search for "0 Error" string in build log, set the result to var
FOR /F "tokens=* USEBACKQ" %%F IN (`find /c /i "0 Error" Build.log`) DO (
SET var=%%F
)
echo %var%
get the last character, which indicates how many lines contains the search string
set result=%var:~-1%
echo "%result%"
if string not found, then error > 0, build failed
if "%result%"=="0" ( echo "build failed" )
That solution was inspired by Mechaflash's post at How to set commands output as a variable in a batch file
Try like this format and use "width" attribute to manage the image size, it is simple. JavaScript can be implemented in element too.
<button><img src=""></button>
_x000D_
This should fix it...
Scanner in=new Scanner(System.in);
int rounds = 0;
while (rounds < 1 || rounds > 3) {
System.out.print("How many rounds? ");
if (in.hasNextInt()) {
rounds = in.nextInt();
} else {
System.out.println("Invalid input. Please try again.");
in.next(); // -->important
System.out.println();
}
// Clear buffer
}
System.out.print(rounds+" rounds.");
Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).
Anyways, if you're already planning on using MSYS2, there's no need for that installer.
Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).
After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit
or MSYS2 32-bit
in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu
, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).
Install a toolchain
a) for 32-bit:
pacman -S mingw-w64-i686-gcc
b) for 64-bit:
pacman -S mingw-w64-x86_64-gcc
install any libraries/tools you may need. You can search the repositories by doing
pacman -Ss name_of_something_i_want_to_install
e.g.
pacman -Ss gsl
and install using
pacman -S package_name_of_something_i_want_to_install
e.g.
pacman -S mingw-w64-x86_64-gsl
and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!
Open a MinGW-w64 shell:
a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"
b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"
Verify that the compiler is working by doing
gcc -v
If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin
or <MSYS2 root>/mingw64/bin
to your PATH
.
Overview of the services used by all sessions provides the distionary view v$session
(or gv$session
for RAC databases) in the column SERVICE_NAME
.
To limit the information to the connected session use the SID from the view V$MYSTAT
:
select SERVICE_NAME from gv$session where sid in (
select sid from V$MYSTAT)
If the name is SYS$USERS
the session is connected to a default service, i.e. in the connection string no explicit service_name was specified.
To see what services are available in the database use following queries:
select name from V$SERVICES;
select name from V$ACTIVE_SERVICES;
If I start with a 3x4 array, and concatenate a 3x1 array, with axis 1, I get a 3x5 array:
In [911]: x = np.arange(12).reshape(3,4)
In [912]: np.concatenate([x,x[:,-1:]], axis=1)
Out[912]:
array([[ 0, 1, 2, 3, 3],
[ 4, 5, 6, 7, 7],
[ 8, 9, 10, 11, 11]])
In [913]: x.shape,x[:,-1:].shape
Out[913]: ((3, 4), (3, 1))
Note that both inputs to concatenate have 2 dimensions.
Omit the :
, and x[:,-1]
is (3,) shape - it is 1d, and hence the error:
In [914]: np.concatenate([x,x[:,-1]], axis=1)
...
ValueError: all the input arrays must have same number of dimensions
The code for np.append
is (in this case where axis is specified)
return concatenate((arr, values), axis=axis)
So with a slight change of syntax append
works. Instead of a list it takes 2 arguments. It imitates the list append
is syntax, but should not be confused with that list method.
In [916]: np.append(x, x[:,-1:], axis=1)
Out[916]:
array([[ 0, 1, 2, 3, 3],
[ 4, 5, 6, 7, 7],
[ 8, 9, 10, 11, 11]])
np.hstack
first makes sure all inputs are atleast_1d
, and then does concatenate:
return np.concatenate([np.atleast_1d(a) for a in arrs], 1)
So it requires the same x[:,-1:]
input. Essentially the same action.
np.column_stack
also does a concatenate on axis 1. But first it passes 1d inputs through
array(arr, copy=False, subok=True, ndmin=2).T
This is a general way of turning that (3,) array into a (3,1) array.
In [922]: np.array(x[:,-1], copy=False, subok=True, ndmin=2).T
Out[922]:
array([[ 3],
[ 7],
[11]])
In [923]: np.column_stack([x,x[:,-1]])
Out[923]:
array([[ 0, 1, 2, 3, 3],
[ 4, 5, 6, 7, 7],
[ 8, 9, 10, 11, 11]])
All these 'stacks' can be convenient, but in the long run, it's important to understand dimensions and the base np.concatenate
. Also know how to look up the code for functions like this. I use the ipython
??
magic a lot.
And in time tests, the np.concatenate
is noticeably faster - with a small array like this the extra layers of function calls makes a big time difference.
Not sure if Access supports it, but in most engines (including SQL Server
) this is called a correlated subquery and works fine:
SELECT TypesAndBread.Type, TypesAndBread.TBName,
(
SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
FROM Sandwiches
WHERE (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
) As SandwichCount
FROM TypesAndBread
This can be made more efficient by indexing Type
and Bread
and distributing the subqueries over the UNION
:
SELECT [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
)
FROM [Sandwiches Types]
UNION ALL
SELECT [Breads].[Bread] As TBName, "Bread" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Bread = [Breads].[Bread]
)
FROM [Breads]
If you are looking for Uniformly distributed pseudorandom integers use:
randi([13, 20])
Swift 4
"string".count
;)
Swift 3
extension String {
var length: Int {
return self.characters.count
}
}
usage
"string".length
Shortest version without form
, min
or external JavaScript.
<input type="range" value="0" max="10" oninput="num.value = this.value">
<output id="num">0</output>
_x000D_
Explanation
If you wanna retrieve the value from the output
you commonly use an id
that can be linked from the oninput
instead of using this.nextElementSibling.value
(we take advantage of something that we are already using)
Compare the example above with this valid but a little more complex and long answer:
<input id="num" type="range" value="0" max="100" oninput="this.nextElementSibling.value = this.value">
<output>0</output>
With the shortest answer:
this
, something weird in JS for newcomersinput
placing the id
in the output
Notes
min
value when equal to
0
this
keyword makes it a better languageForce Stop the application in the device settings.
Send a ajax request to your server like this in your js and get your result in success function.
jQuery.ajax({
url: "/rest/abc",
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
//here is your json.
// process it
},
error : function(jqXHR, textStatus, errorThrown) {
},
timeout: 120000,
});
at server side send response as json type.
And you can use jQuery.getJSON for your application.
I use Eclipse under Fedora 20 with MinGW for cross compile. Use these settings and the program won't ask for libstdc++-6.dll any more.
Project type - Cross GCC
Cross Settings
Cross GCC Compiler
Command: gcc
All Options: -I/usr/x86_64-w64-mingw32/sys-root/mingw/include -O3 -Wall -c -fmessage-length=0
Includes: /usr/x86_64-w64-mingw32/sys-root/mingw/include
Cross G++ Compiler
Command: g++
All Options: -I/usr/x86_64-w64-mingw32/sys-root/mingw/include -O3 -Wall -c -fmessage-length=0
Includes: /usr/x86_64-w64-mingw32/sys-root/mingw/include
Cross G++ Linker
Command: g++ -static-libstdc++ -static-libgcc
All Options: -L/usr/x86_64-w64-mingw32/sys-root/mingw/lib -L/usr/x86_64-w64-mingw32/sys-root/mingw/bin
Library search path (-L):
/usr/x86_64-w64-mingw32/sys-root/mingw/lib
/usr/x86_64-w64-mingw32/sys-root/mingw/bin
For red lines an points
plt.plot(dates, values, '.r-')
or for x markers and blue lines
plt.plot(dates, values, 'xb-')
Some of the previous answers are not correct. They work for other widgets and views, but the documentation for the Spinner widget clearly states:
A spinner does not support item click events. Calling this method will raise an exception.
Better use OnItemSelectedListener() instead:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
This works for me.
Note that onItemSelected method is also invoked when the view is being build, so you can consider putting it inside onCreate()
method call.
You can't put a pseudo element in an input element, but can put in shadow element, like a placeholder!
input[type="text"] {
&::-webkit-input-placeholder {
&:before {
// your code
}
}
}
To make it work in other browsers, use :-moz-placeholder
, ::-moz-placeholder
and :-ms-input-placeholder
in different selectors. Can't group the selectors, because if a browser doesn't recognize the selector invalidates the entire statement.
UPDATE: The above code works only with CSS pre-processor (SASS, LESS...), without pre-processors use:
input[type="text"]::-webkit-input-placeholder:before { // your code }
There are multiple ways to do it. However, the quickest way I know is to use the Express.js library with body-parser.
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({extended : true}));
app.post("/pathpostdataissentto", function(request, response) {
console.log(request.body);
//Or
console.log(request.body.fieldName);
});
app.listen(8080);
That can work for strings, but I would change bodyParser.urlencoded to bodyParser.json instead if the POST data contains a JSON array.
More info: http://www.kompulsa.com/how-to-accept-and-parse-post-requests-in-node-js/
I'm not sure whether I understand your question correctly, but you can write your code in this way:
bool DoesEntityExist<T>(T instance, ....)
You can call the method in following fashion:
DoesEntityExist(myTypeInstance, ...)
This way you don't need to explicitly write the type, the framework will overtake the type automatically from the instance.
To add up to Louis answer:
Alternatively you can use the attribute ToolVersion="12.0"
if you are using Visual Studio 2013 instead of using the ToolPath
Attribute. Details visit http://msdn.microsoft.com/en-us/library/dd647548.aspx
So you are not forced to use absolute path.
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
you need to cast int to str before concatenating. for that use str(temperature)
. Or you can print the same output using ,
if you don't want to convert like this.
print("the furnace is now",temperature , "degrees!")
Been doing it for years. Never run into a problem.
I usually set up my DB's to have one table that contains all the keys and the modified dates and such. Haven't run into a problem of duplicate keys ever.
The only drawback that it has is when you are writing some queries to find some information quickly you are doing a lot of copying and pasting of the keys. You don't have the short easy to remember ids anymore.
Open the windows cmd. First list all the java processes,
jps -m
now get the name and run below command,
for /f "tokens=1" %i in ('jps -m ^| find "Name_of_the_process"') do ( taskkill /F /PID %i )
or simply kill the process ID
taskkill /F /PID <ProcessID>
sample :)
C:\Users\tk>jps -m
15176 MessagingMain
18072 SoapUI-5.4.0.exe
15164 Jps -m
3420 org.eclipse.equinox.launcher_1.3.201.v20161025-1711.jar -os win32 -ws win32 -arch x86_64 -showsplash -launcher C:\Users\tk\eclipse\jee-neon\eclipse\eclipse.exe -name Eclipse --launcher.library C:\Users\tk\.p2\pool\plugins\org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.401.v20161122-1740\eclipse_1617.dll -startup C:\Users\tk\eclipse\jee-neon\eclipse\\plugins/org.eclipse.equinox.launcher_1.3.201.v20161025-1711.jar --launcher.appendVmargs -exitdata 4b20_d0 -product org.eclipse.epp.package.jee.product -vm C:/Program Files/Java/jre1.8.0_131/bin/javaw.exe -vmargs -Dosgi.requiredJavaVersion=1.8 -XX:+UseG1GC -XX:+UseStringDeduplication -Dosgi.requiredJavaVersion=1.8 -Xms256m -Xmx1024m -Declipse.p2.max.threads=10 -Doomph.update.url=http://download.eclipse.org/oomph/updates/milestone/latest -Doomph.redirection.index.redirection=index:/->http://git.eclipse.org/c/oomph/org.eclipse.oomph.git/plain/setups/ -jar C:\Users\tk\
and
C:\Users\tk>for /f "tokens=1" %i in ('jps -m ^| find "MessagingMain"') do ( taskkill /F /PID %i )
C:\Users\tk>(taskkill /F /PID 15176 )
SUCCESS: The process with PID 15176 has been terminated.
or
C:\Users\tk>taskkill /F /PID 15176
SUCCESS: The process with PID 15176 has been terminated.
Some ideas in the following answer:
Steps in creating a web service using Axis2 - The client code
Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.
There are lots of web service frameworks out there...
Use numeric values instead of strings.
Finally to convert the constants JACK or QUEEN to a string, use the stringize (and/or tokenize) operators.
add an attribute to the EditText like android:imeOptions="actionSearch"
this is the best way to do the function
and the imeOptions also have some other values like "go" ?"next"?"done" etc.
i think android studio has a 64bit kernel version which is giving the problem. https://github.com/swcarpentry/windows-installer/issues/49
SELECT CONCAT (zipcode, ' - ', city, ', ', state) AS COMBINED FROM TABLE
color class taken from bootstrap color picker
// Color object
var Color = function(val) {
this.value = {
h: 1,
s: 1,
b: 1,
a: 1
};
this.setColor(val);
};
Color.prototype = {
constructor: Color,
//parse a string to HSB
setColor: function(val){
val = val.toLowerCase();
var that = this;
$.each( CPGlobal.stringParsers, function( i, parser ) {
var match = parser.re.exec( val ),
values = match && parser.parse( match ),
space = parser.space||'rgba';
if ( values ) {
if (space === 'hsla') {
that.value = CPGlobal.RGBtoHSB.apply(null, CPGlobal.HSLtoRGB.apply(null, values));
} else {
that.value = CPGlobal.RGBtoHSB.apply(null, values);
}
return false;
}
});
},
setHue: function(h) {
this.value.h = 1- h;
},
setSaturation: function(s) {
this.value.s = s;
},
setLightness: function(b) {
this.value.b = 1- b;
},
setAlpha: function(a) {
this.value.a = parseInt((1 - a)*100, 10)/100;
},
// HSBtoRGB from RaphaelJS
// https://github.com/DmitryBaranovskiy/raphael/
toRGB: function(h, s, b, a) {
if (!h) {
h = this.value.h;
s = this.value.s;
b = this.value.b;
}
h *= 360;
var R, G, B, X, C;
h = (h % 360) / 60;
C = b * s;
X = C * (1 - Math.abs(h % 2 - 1));
R = G = B = b - C;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return {
r: Math.round(R*255),
g: Math.round(G*255),
b: Math.round(B*255),
a: a||this.value.a
};
},
toHex: function(h, s, b, a){
var rgb = this.toRGB(h, s, b, a);
return '#'+((1 << 24) | (parseInt(rgb.r) << 16) | (parseInt(rgb.g) << 8) | parseInt(rgb.b)).toString(16).substr(1);
},
toHSL: function(h, s, b, a){
if (!h) {
h = this.value.h;
s = this.value.s;
b = this.value.b;
}
var H = h,
L = (2 - s) * b,
S = s * b;
if (L > 0 && L <= 1) {
S /= L;
} else {
S /= 2 - L;
}
L /= 2;
if (S > 1) {
S = 1;
}
return {
h: H,
s: S,
l: L,
a: a||this.value.a
};
}
};
how to use
var color = new Color("RGB(0,5,5)");
color.toHex()
If I understand the question, you want to change the value of the checkbox depending if it is checked or not.
Here is one solution:
$('#checkbox-value').text($('#checkbox1').val());_x000D_
_x000D_
$("#checkbox1").on('change', function() {_x000D_
if ($(this).is(':checked')) {_x000D_
$(this).attr('value', 'true');_x000D_
} else {_x000D_
$(this).attr('value', 'false');_x000D_
}_x000D_
_x000D_
$('#checkbox-value').text($('#checkbox1').val());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<input type="checkbox" name="acceptRules" class="inline checkbox" id="checkbox1" value="false">_x000D_
_x000D_
<div id="checkbox-value"></div>
_x000D_
To list the larger file in a folder
ls -sh /pathFolder | sort -rh | head -n 1
The output of ls -sh
is a sized s
and human h
understandable view of the file size number.
You could use ls -shS /pathFolder | head -n 1
. The bigger S
from ls
already order the list from the larger files to the smaller ones but the first result its the sum of all files in that folder. So if you want just to list the bigger file, one file, you need to head -n 2
and check at the "second line result" or use the first example with ls sort head
.
boto3 offers a resource model that makes tasks like iterating through objects easier. Unfortunately, StreamingBody doesn't provide readline
or readlines
.
s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
for obj in bucket.objects.all():
key = obj.key
body = obj.get()['Body'].read()
Perform multiple queries or use embedded documents or look at "database references".
Did you mean this?
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',tmppath);
});
I think you might see slightly better performance by doing it this way:
$("#Create, #Edit").find(".myClass").plugin(){
// Options
});
If you have previous apk file with you(backup) then use jarSigner to extract certificate from that that apk, then use that key or use keytool to clone that certificate, may be that will help... Helpful links are jarsigner docs and keytool docs.
Not an expert in regex, but you can do ^((part1|part2)|(part1, part2))$
. In words: "part 1 or part2 or both"
you could use the font style Like:
<font color="white"><h1>Header Content</h1></font>
Setting command timeout to 2 minutes.
scGetruntotals.CommandTimeout = 120;
but you can optimize your stored Procedures to decrease that time! like
If you want to use base_url()
, so we need to load url helper.
$autoload['helper'] = array('url');
$this->load->helper('url');
Then you can user base_url()
anywhere in controller or view.
Not directly, no. Android's C runtime library, bionic, is not binary compatible with the GNU libc, which most Linux distributions use.
You can always try to recompile your binaries for Android and pray.
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
>>> reduce(lambda s, x: s*256 + x, bytearray("y\xcc\xa6\xbb"))
2043455163
Test 1: inverse:
>>> hex(2043455163)
'0x79cca6bb'
Test 2: Number of bytes > 8:
>>> reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAAA"))
338822822454978555838225329091068225L
Test 3: Increment by one:
>>> reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAAB"))
338822822454978555838225329091068226L
Test 4: Append one byte, say 'A':
>>> reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAABA"))
86738642548474510294585684247313465921L
Test 5: Divide by 256:
>>> reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAABA"))/256
338822822454978555838225329091068226L
Result equals the result of Test 4, as expected.
I have the same problem, i read the url with an properties file:
String configFile = System.getenv("system.Environment");
if (configFile == null || "".equalsIgnoreCase(configFile.trim())) {
configFile = "dev.properties";
}
// Load properties
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/" + configFile));
//read url from file
apiUrl = properties.getProperty("url").trim();
URL url = new URL(apiUrl);
//throw exception here
URLConnection conn = url.openConnection();
dev.properties
url = "https://myDevServer.com/dev/api/gate"
it should be
dev.properties
url = https://myDevServer.com/dev/api/gate
without "" and my problem is solved.
According to oracle documentation
- Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
So it means it is not parsed inside the string.
The answer from @stuyam solved the "No such file or directory" issue for me
Short answer: Change "host" in the /app/config/database.php file from "localhost" to "127.0.0.1"
But then I had a "Connection refused" error. If anyone had the same issue, my solution for this was to update the app/config/local/database.php file so the port is 8889:
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => '8889',
'database' => 'databaseName',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
Alternately, use a filter.
Create an empty page in your WordPress blog, named appropriately to what you need it to be. Take note of the post_id. Then create a filter that alters its permalink.
add_filter('get_the_permalink','my_permalink_redirect');
function my_permalink_redirect($permalink) {
global $post;
if ($post->ID == your_post_id_here) {
$permalink = 'http://new-url.com/pagename';
}
return $permalink;
}
This way the url will show up correctly in the page no funny redirects are required.
If you need to do this a lot, then think about using the custom postmeta fields to define a postmeta value for "offsite_url" or something like that, then you can create pages as needed, enter the "offsite_url" value and then use a filter like the one above to instead of checking the post_id you check to see if it has the postmeta required and alter the permalink as needed.
If speed is critical, you might want to look for the Aho-Corasick algorithm for sets of patterns.
It's a trie with failure links, that is, complexity is O(n+m+k), where n is the length of the input text, m the cumulative length of the patterns and k the number of matches. You just have to modify the algorithm to terminate after the first match is found.
I would do this:
var date = new Date(2000, 0, 9);
var str = new Intl.DateTimeFormat('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' }).format(date);
console.log(str); // prints "01/09/2000"
_x000D_
You will have to use a class, but don't worry, it's pretty simple. First we'll assign your :hover
rules to not only apply to physically-hovered links, but also to links that have the classname hovered
.
a:hover, a.hovered { color: #ccff00; }
Next, when you click #btn
, we'll toggle the .hovered
class on the #link
.
$("#btn").click(function() {
$("#link").toggleClass("hovered");
});
If the link has the class already, it will be removed. If it doesn't have the class, it will be added.
I think the description of the error is misleading and has originally to do with wrong usage of the player object.
I had the same issue when switching to new Videos in a Slider.
When simply using the player.destroy()
function described here the problem is gone.
Why not use the Actions menu option to set this?
Do the following: If you have Acrobat Pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose 'Execute a menu item'. Click the Add button then select 'File > Print' then OK. Click OK again and save the PDF.
First of all, input
element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden
).
Second thing, you need the after()
, not append()
function.
In case of your jdk version less than 1.5, following option can be used.
int iTest = 2;
StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
sTest.append(String.valueOf(iTest));
System.out.println(sTest.substring(sTest.length()-6, sTest.length()));
There are much better ways to print variable's value in PHP. One of them is to use buildin var_dump() function. If you want to use var_dump(), I would also suggest to install Xdebug (from https://xdebug.org) since it generates much more readable printouts.
The idea of printing values to browser console is somewhat bizarre, but if you really want to use it, there is very useful Google Chrome extension, PHP Console, which should satisfy all your needs. You can find it at consle.com It works well also in Vivaldi and in Opera (though you will need "Download Chrome Extension" extension to install it). The extension is accompanied by PHP library you use in your code.
If you want to just shift everything down you can use:
Rows(1).Insert shift:=xlShiftDown
Similarly to shift everything over:
Columns(1).Insert shift:=xlShiftRight
From the docs
IF boolean-expression THEN
statements
ELSE
statements
END IF;
So in your above example the code should look as follows:
IF select count(*) from orders > 0
THEN
DELETE from orders
ELSE
INSERT INTO orders values (1,2,3);
END IF;
You were missing: END IF;
In case you're dealing with a Model, you can use the Attriutes API in Rails 5+ http://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute
just add a migration with a proper column name and then in the model set it with:
class StoreListing < ActiveRecord::Base
attribute :country, :string, default: 'PT'
end
Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.
1) Start of by setting your height as 100vh.
2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.
3) Just offset the extra padding-top with a negative margin-top
div
{
/*height: calc(100vh - 75vw);*/
height: 100vh;
margin-top: -75vw;
padding-top: 75vw;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: pink;
}
For those of you editing the ./.git/config
[remote "external"]
url = ssh://[email protected]:11720/aaa/bbb/ccc
fetch = +refs/heads/*:refs/remotes/external/*
check this condition
String string="//some string...//"
check this... if(string.equals((string.reverse()) { it is palindrome }
You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task
or Task<T>
, if you return nothing and you want your method will be run asyncronously you should define your method like this:
private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); }
And in Main method you can't await for DoDownloadAsync
, because you can't use await keyword in non-async function, and you can't make Main
async. So consider this:
var result = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); result.Wait();
For horizontal and vertical alignment of text in graphics,
you might want to use the following CSS styles.
In particular, note that dominant-baseline:middle
is probably wrong,
since this is (usually) half way between the top and the baseline,
rather than half way between the top and the bottom.
Also, some some sources (e.g. Mozilla) use dominant-baseline:hanging
instead of
dominant-baseline:text-before-edge
. This is also probably wrong, since
hanging
is designed for Indic scripts.
Of course, if you're using a mixture of Latin, Indic, ideographs
or whatever, you'll probably need to read the documentation.
/* Horizontal alignment */
text.goesleft{text-anchor:end}
text.equalleftright{text-anchor:middle}
text.goesright{text-anchor:start}
/* Vertical alignment */
text.goesup{dominant-baseline:text-after-edge}
text.equalupdown{dominant-baseline:central}
text.goesdown{dominant-baseline:text-before-edge}
text.ruledpaper{dominant-baseline:alphabetic}
Edit: I've just noticed that Mozilla also uses dominant-baseline:baseline
which is definitely wrong: it's not even a recognized value! I assume it's defaulting to the font default, which is alphabetic
, so they got lucky.
More edit: Safari (11.1.2) understands text-before-edge
but not text-after-edge
. It also fails on ideographic
. Great stuff, Apple. So you might be forced to use alphabetic
and allow for descenders after all. Sorry.
I saw this warning on many websites. Also, I saw that YUI 3 library also gives the same warning. It's a warning generated from the library (whether is it jQuery or YUI).
Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.
See the iOS Application Programming Guide.
To access the Documents directory of your applications sandbox, you can use the following:
+ (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
+ (NSString *) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = paths.firstObject;
return basePath;
}
This Documents directory allows you to store files and subdirectories your app creates or may need.
To access files in the Library directory of your apps sandbox use (in place of paths
above):
[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]
This is how I solved it on Windows. I have git installed separately, and Idea just picks git's options automatically (Default Idea config, as I would get from clean installer).
Open the project in the command line. Make some changes there. And commit and push files via git which is installed on my machine. During push it will open a windows asking me to enter username and password. After that, when I make a commit-push from idea, it will simply work.
You need to use getActivity() method from fragment for Intents.
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
In order for the client to be able to read cookies from cross-origin requests, you need to have:
All responses from the server need to have the following in their header:
Access-Control-Allow-Credentials: true
The client needs to send all requests with withCredentials: true
option
In my implementation with Angular 7 and Spring Boot, I achieved that with the following:
Server-side:
@CrossOrigin(origins = "http://my-cross-origin-url.com", allowCredentials = "true")
@Controller
@RequestMapping(path = "/something")
public class SomethingController {
...
}
The origins = "http://my-cross-origin-url.com"
part will add Access-Control-Allow-Origin: http://my-cross-origin-url.com
to every server's response header
The allowCredentials = "true"
part will add Access-Control-Allow-Credentials: true
to every server's response header, which is what we need in order for the client to read the cookies
Client-side:
import { HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// send request with credential options in order to be able to read cross-origin cookies
req = req.clone({ withCredentials: true });
// return XSRF-TOKEN in each request's header (anti-CSRF security)
const headerName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({ headers: req.headers.set(headerName, token) });
}
return next.handle(req);
}
}
With this class you actually inject additional stuff to all your request.
The first part req = req.clone({ withCredentials: true });
, is what you need in order to send each request with withCredentials: true
option. This practically means that an OPTION request will be send first, so that you get your cookies and the authorization token among them, before sending the actual POST/PUT/DELETE requests, which need this token attached to them (in the header), in order for the server to verify and execute the request.
The second part is the one that specifically handles an anti-CSRF token for all requests. Reads it from the cookie when needed and writes it in the header of every request.
The desired result is something like this:
You can find a few examples here:
// Fill the DataSet. DataSet ds = new DataSet(); ds.Locale = CultureInfo.InvariantCulture; FillDataSet(ds); DataTable contacts = ds.Tables["Contact"]; DataTable orders = ds.Tables["SalesOrderHeader"]; var query = contacts.AsEnumerable().Join(orders.AsEnumerable(), order => order.Field<Int32>("ContactID"), contact => contact.Field<Int32>("ContactID"), (contact, order) => new { ContactID = contact.Field<Int32>("ContactID"), SalesOrderID = order.Field<Int32>("SalesOrderID"), FirstName = contact.Field<string>("FirstName"), Lastname = contact.Field<string>("Lastname"), TotalDue = order.Field<decimal>("TotalDue") }); foreach (var contact_order in query) { Console.WriteLine("ContactID: {0} " + "SalesOrderID: {1} " + "FirstName: {2} " + "Lastname: {3} " + "TotalDue: {4}", contact_order.ContactID, contact_order.SalesOrderID, contact_order.FirstName, contact_order.Lastname, contact_order.TotalDue); }
Or just google for 'linq join method syntax'.
We can create multidimensional array dynamically as follows,
Create 2 variables to read x and y from standard input:
print("Enter the value of x: ")
x=int(input())
print("Enter the value of y: ")
y=int(input())
Create an array of list with initial values filled with 0 or anything using the following code
z=[[0 for row in range(0,x)] for col in range(0,y)]
creates number of rows and columns for your array data.
Read data from standard input:
for i in range(x):
for j in range(y):
z[i][j]=input()
Display the Result:
for i in range(x):
for j in range(y):
print(z[i][j],end=' ')
print("\n")
or use another way to display above dynamically created array is,
for row in z:
print(row)
To change the connect mode selection try Settings -> Wireless & Networks -> USB Connection. You can shoose to Charging, Mass Storage, Tethered, and ask on connection.
Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.
Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable
If you wish to use 2 subdomains to other ports, you can use Minecraft's proxy server (it means BungeeCord, Waterfall, Travertine...), and bind subdomain to specifiend in config.yml server. To do that you have to setup your servers in BungeeCord's config:
servers:
pvp:
motd: 'A Minecraft Server PVP'
address: localhost:25566
restricted: false
skyblock:
motd: 'A Minecraft Server SkyBlock'
address: localhost:25567
restricted: false
Remember! Ports must be diffrent than default Minecraft's port (it means 25565), because we will use this port to our proxy. sub1.domain.com and sub2.domain.com we have to bind to server where you have these servers. Now, we have to bind subdomains in your Bungee server:
listeners:
forced_hosts:
sub1.domain.com: pvp
sub2.domain.com: skyblock
domain.com: pvp // You can bind other domains to same servers.
Remember to change force_default_server to true, and change host to 0.0.0.0:25565 Example of BungeeCord's config.yml with some servers: https://pastebin.com/tA9ktZ6f Now you can connect to your pvp server on sub1.domain.com and connect to skyblock on sub2.domain.com. Don't worry, BungeeCord takes only 0,5GB of RAM for 500 players.
:w
- Write a file.
!sudo
- Call shell sudo command.
tee
- The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):
HTML5 adds a maxlength
attribute to the textarea
element, like so:
<!DOCTYPE html>
<html>
<body>
<form action="processForm.php" action="post">
<label for="story">Tell me your story:</label><br>
<textarea id="story" maxlength="100"></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is currently supported in Chrome 13, FF 5, and Safari 5. Not surprisingly, this is not supported in IE 9. (Tested on Win 7)
Just declare the enum outside the bounds of the class. Like this:
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
public class Card
{
...
}
Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)
fflush()
only flushes the buffering added by the stdio fopen()
layer, as managed by the FILE *
object. The underlying file itself, as seen by the kernel, is not buffered at this level. This means that writes that bypass the FILE *
layer, using fileno()
and a raw write()
, are also not buffered in a way that fflush()
would flush.
As others have pointed out, try not mixing the two. If you need to use "raw" I/O functions such as ioctl()
, then open()
the file yourself directly, without using fopen<()
and friends from stdio.
The trunk directory is the directory that you're probably most familiar with, because it is used to hold the most recent changes. Your main codebase should be in trunk.
The branches directory is for holding your branches, whatever they may be.
The tags directory is basically for tagging a certain set of files. You do this for things like releases, where you want "1.0" to be these files at these revisions and "1.1" to be these files at these revisions. You usually don't modify tags once they're made. For more information on tags, see Chapter 4. Branching and Merging (in Version Control with Subversion).
You can join to the same table on the fields that would be duplicated and then anti-join on the id field. Select the id field from the first table alias (tn1) and then use the array_agg function on the id field of the second table alias. Finally, for the array_agg function to work properly, you will group the results by the tn1.id field. This will produce a result set that contains the the id of a record and an array of all the id's that fit the join conditions.
select tn1.id,
array_agg(tn2.id) as duplicate_entries,
from table_name tn1 join table_name tn2 on
tn1.year = tn2.year
and tn1.sid = tn2.sid
and tn1.user_id = tn2.user_id
and tn1.cid = tn2.cid
and tn1.id <> tn2.id
group by tn1.id;
Obviously, id's that will be in the duplicate_entries array for one id, will also have their own entries in the result set. You will have to use this result set to decide which id you want to become the source of 'truth.' The one record that shouldn't get deleted. Maybe you could do something like this:
with dupe_set as (
select tn1.id,
array_agg(tn2.id) as duplicate_entries,
from table_name tn1 join table_name tn2 on
tn1.year = tn2.year
and tn1.sid = tn2.sid
and tn1.user_id = tn2.user_id
and tn1.cid = tn2.cid
and tn1.id <> tn2.id
group by tn1.id
order by tn1.id asc)
select ds.id from dupe_set ds where not exists
(select de from unnest(ds.duplicate_entries) as de where de < ds.id)
Selects the lowest number ID's that have duplicates (assuming the ID is increasing int PK). These would be the ID's that you would keep around.
Return ABDeadlineType
from repository:
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
List<ABDeadlineType> findAllSummarizedBy();
}
and then convert to DeadlineType. Manually or use mapstruct.
Or call constructor from @Query
annotation:
public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
@Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
List<DeadlineType> findAllSummarizedBy();
}
Or use @Projection
:
@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {
@Value("#{target.id}")
String getId();
@Value("#{target.code}")
String getText();
}
Update:
Spring can work without @Projection
annotation:
public interface DeadlineType {
String getId();
String getText();
}
Ok this this seems late and I was testing the app with internet connection off to test my app for some functionality. As I turned off the internet it gave me such error. After I turned on the internet I can install again. I know this is silly but this might be helpful to someone
You could also use lambda
. Useful if you're using django.utils.timezone.now
date = models.DateField(_("Date"), default=lambda: now().date())
I ran into this same problem pulling some data from a sqlite3 database with python. The above answers didn't work for me (not sure why), but this did: line = line.decode('ascii', 'ignore')
However, my goal was deleting the \xa0s, rather than replacing them with spaces.
I got this from this super-helpful unicode tutorial by Ned Batchelder.
Thanx schwiz for idea! Here is modified solution:
public class FileDialog {
private static final String PARENT_DIR = "..";
private final String TAG = getClass().getName();
private String[] fileList;
private File currentPath;
public interface FileSelectedListener {
void fileSelected(File file);
}
public interface DirectorySelectedListener {
void directorySelected(File directory);
}
private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
private final Activity activity;
private boolean selectDirectoryOption;
private String fileEndsWith;
/**
* @param activity
* @param initialPath
*/
public FileDialog(Activity activity, File initialPath) {
this(activity, initialPath, null);
}
public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
this.activity = activity;
setFileEndsWith(fileEndsWith);
if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
loadFileList(initialPath);
}
/**
* @return file dialog
*/
public Dialog createFileDialog() {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(currentPath.getPath());
if (selectDirectoryOption) {
builder.setPositiveButton("Select directory", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, currentPath.getPath());
fireDirectorySelectedEvent(currentPath);
}
});
}
builder.setItems(fileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String fileChosen = fileList[which];
File chosenFile = getChosenFile(fileChosen);
if (chosenFile.isDirectory()) {
loadFileList(chosenFile);
dialog.cancel();
dialog.dismiss();
showDialog();
} else fireFileSelectedEvent(chosenFile);
}
});
dialog = builder.show();
return dialog;
}
public void addFileListener(FileSelectedListener listener) {
fileListenerList.add(listener);
}
public void removeFileListener(FileSelectedListener listener) {
fileListenerList.remove(listener);
}
public void setSelectDirectoryOption(boolean selectDirectoryOption) {
this.selectDirectoryOption = selectDirectoryOption;
}
public void addDirectoryListener(DirectorySelectedListener listener) {
dirListenerList.add(listener);
}
public void removeDirectoryListener(DirectorySelectedListener listener) {
dirListenerList.remove(listener);
}
/**
* Show file dialog
*/
public void showDialog() {
createFileDialog().show();
}
private void fireFileSelectedEvent(final File file) {
fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
public void fireEvent(FileSelectedListener listener) {
listener.fileSelected(file);
}
});
}
private void fireDirectorySelectedEvent(final File directory) {
dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
public void fireEvent(DirectorySelectedListener listener) {
listener.directorySelected(directory);
}
});
}
private void loadFileList(File path) {
this.currentPath = path;
List<String> r = new ArrayList<String>();
if (path.exists()) {
if (path.getParentFile() != null) r.add(PARENT_DIR);
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
if (!sel.canRead()) return false;
if (selectDirectoryOption) return sel.isDirectory();
else {
boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
return endsWith || sel.isDirectory();
}
}
};
String[] fileList1 = path.list(filter);
for (String file : fileList1) {
r.add(file);
}
}
fileList = (String[]) r.toArray(new String[]{});
}
private File getChosenFile(String fileChosen) {
if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
else return new File(currentPath, fileChosen);
}
private void setFileEndsWith(String fileEndsWith) {
this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
}
}
class ListenerList<L> {
private List<L> listenerList = new ArrayList<L>();
public interface FireHandler<L> {
void fireEvent(L listener);
}
public void add(L listener) {
listenerList.add(listener);
}
public void fireEvent(FireHandler<L> fireHandler) {
List<L> copy = new ArrayList<L>(listenerList);
for (L l : copy) {
fireHandler.fireEvent(l);
}
}
public void remove(L listener) {
listenerList.remove(listener);
}
public List<L> getListenerList() {
return listenerList;
}
}
Use it on activity onCreate (directory selection option is commented):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
fileDialog = new FileDialog(this, mPath, ".txt");
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
}
});
//fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
// public void directorySelected(File directory) {
// Log.d(getClass().getName(), "selected dir " + directory.toString());
// }
//});
//fileDialog.setSelectDirectoryOption(false);
fileDialog.showDialog();
}
UPD
Apple requires to use arm64 architecture. Do not use x32 libraries in your project
So the answer below is not correct anymore!
Old answer
The new Xcode 5.1 sets the architecture armv7,armv7s,and arm64 as default.
And sometimes the error "build failure “Undefined symbols for architecture x86_64”" may be caused by this. Because, some libs (not Apple's) were compiled for x32 originally and doesn't support x64.
So what you need, is to change the "Architectures" for your project target like this
NB. If you're using Cocoapods - you should do the same for "Pods" target.
Small addition to Chris Kannon' accepted answer: only print if there actually is a second last column.
(
echo | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 3 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
)
For linux/unix OS, you can use the shell syntax
const shell = require('child_process').execSync ;
const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;
shell(`mv ${currentPath} ${newPath}`);
That's it!
Choosing a "different one" is actually a pretty easy solution.
I had been running Eclipse as an administrator (sudo eclipse
from the command line) because the "workspace" folder was throwing the Workspace in use or cannot be created…
error (and running as administrator seemed to be the only solution that fixed it).
A coworker (working on this same issue with me) wanted to run Eclipse by clicking on an icon. So when he ran Eclipse, and the dialogue box came up with the choose your workspace, he just added a "2" to the end of "workspace".
This created a new folder: "workspace2". Eclipse ran fine with that; and I haven’t had any of the locking problems since.
For Android Studio and IntelliJ:
First, commit everything and resolve any conflicts.
Then open the terminal from below of IDE and enter:
git pull origin master --allow-unrelated-histories
Now you can push.
Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:
public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(subUrl);
response.EnsureSuccessStatusCode();
var responseAsString = await response.Content.ReadAsStringAsync();
var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
return responseAsConcreteType;
}
}
The problem is that you are using SingleOrDefault
. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault
which will succeed no matter how many elements are in the collection.
Although similar in general cases ("run and get results for many tasks"), each function has some specific functionality for other cases:
asyncio.gather()
Returns a Future instance, allowing high level grouping of tasks:
import asyncio
from pprint import pprint
import random
async def coro(tag):
print(">", tag)
await asyncio.sleep(random.uniform(1, 3))
print("<", tag)
return tag
loop = asyncio.get_event_loop()
group1 = asyncio.gather(*[coro("group 1.{}".format(i)) for i in range(1, 6)])
group2 = asyncio.gather(*[coro("group 2.{}".format(i)) for i in range(1, 4)])
group3 = asyncio.gather(*[coro("group 3.{}".format(i)) for i in range(1, 10)])
all_groups = asyncio.gather(group1, group2, group3)
results = loop.run_until_complete(all_groups)
loop.close()
pprint(results)
All tasks in a group can be cancelled by calling group2.cancel()
or even all_groups.cancel()
. See also .gather(..., return_exceptions=True)
,
asyncio.wait()
Supports waiting to be stopped after the first task is done, or after a specified timeout, allowing lower level precision of operations:
import asyncio
import random
async def coro(tag):
print(">", tag)
await asyncio.sleep(random.uniform(0.5, 5))
print("<", tag)
return tag
loop = asyncio.get_event_loop()
tasks = [coro(i) for i in range(1, 11)]
print("Get first result:")
finished, unfinished = loop.run_until_complete(
asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED))
for task in finished:
print(task.result())
print("unfinished:", len(unfinished))
print("Get more results in 2 seconds:")
finished2, unfinished2 = loop.run_until_complete(
asyncio.wait(unfinished, timeout=2))
for task in finished2:
print(task.result())
print("unfinished2:", len(unfinished2))
print("Get all other results:")
finished3, unfinished3 = loop.run_until_complete(asyncio.wait(unfinished2))
for task in finished3:
print(task.result())
loop.close()
java -DLOG_DIR=${LOG_DIR} -jar myjar.jar "param1" "param2"
==> in cmd line if you have "value="${LOG_DIR}/log/clientProject/project-error.log" in xml
You can di this:
#axs[1].plot(clust_data[:,0],clust_data[:,1]) # Remove this if you don't need it
axs[1].axis("off") # This will leave the table alone in the window
int v2= Int32.Parse(v1.ToString());
In 2021 you should install wrapper:
ansible-galaxy collection install ansible.posix
And use
- name: Synchronize two directories on one remote host.
ansible.posix.synchronize:
src: /first/absolute/path
dest: /second/absolute/path
delegate_to: "{{ inventory_hostname }}"
Read more:
https://docs.ansible.com/ansible/latest/collections/ansible/posix/synchronize_module.html
Checked on:
ansible --version
ansible 2.10.5
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/daniel/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3.9/site-packages/ansible
executable location = /sbin/ansible
python version = 3.9.1 (default, Dec 13 2020, 11:55:53) [GCC 10.2.0]
You will have to read in all the data from the Stream object into a byte[]
buffer and then pass that into the MemoryStream
via its constructor. It may be better to be more specific about the type of stream object you are using. Stream
is very generic and may not implement the Length
attribute, which is rather useful when reading in data.
Here's some code for you:
public MyClass(Stream inputStream) {
byte[] inputBuffer = new byte[inputStream.Length];
inputStream.Read(inputBuffer, 0, inputBuffer.Length);
_ms = new MemoryStream(inputBuffer);
}
If the Stream
object doesn't implement the Length
attribute, you will have to implement something like this:
public MyClass(Stream inputStream) {
MemoryStream outputStream = new MemoryStream();
byte[] inputBuffer = new byte[65535];
int readAmount;
while((readAmount = inputStream.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
outputStream.Write(inputBuffer, 0, readAmount);
_ms = outputStream;
}
Also the $wshell = New-Object -ComObject wscript.shell;
helped a script that was running in the background, it worked fine with just but adding $wshell
. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")
In pom.xml file of the project,
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>X.X.X.RELEASE</version>
<relativePath> ../PROJECTNAME/pom.xml</relativePath>
</parent>
Pointing relativepath to the same MAVEN project POM file solved the issue for me.
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
For me, nobody explains it better than mindpro.com:
Gotchas
java.util.GregorianCalendar
has far fewer bugs and gotchas than theold java.util.Date
class but it is still no picnic.Had there been programmers when Daylight Saving Time was first proposed, they would have vetoed it as insane and intractable. With daylight saving, there is a fundamental ambiguity. In the fall when you set your clocks back one hour at 2 AM there are two different instants in time both called 1:30 AM local time. You can tell them apart only if you record whether you intended daylight saving or standard time with the reading.
Unfortunately, there is no way to tell
GregorianCalendar
which you intended. You must resort to telling it the local time with the dummy UTC TimeZone to avoid the ambiguity. Programmers usually close their eyes to this problem and just hope nobody does anything during this hour.Millennium bug. The bugs are still not out of the Calendar classes. Even in JDK (Java Development Kit) 1.3 there is a 2001 bug. Consider the following code:
GregorianCalendar gc = new GregorianCalendar(); gc.setLenient( false ); /* Bug only manifests if lenient set false */ gc.set( 2001, 1, 1, 1, 0, 0 ); int year = gc.get ( Calendar.YEAR ); /* throws exception */
The bug disappears at 7AM on 2001/01/01 for MST.
GregorianCalendar
is controlled by a giant of pile of untyped int magic constants. This technique totally destroys any hope of compile-time error checking. For example to get the month you useGregorianCalendar. get(Calendar.MONTH));
GregorianCalendar
has the rawGregorianCalendar.get(Calendar.ZONE_OFFSET)
and the daylight savingsGregorianCalendar. get( Calendar. DST_OFFSET)
, but no way to get the actual time zone offset being used. You must get these two separately and add them together.
GregorianCalendar.set( year, month, day, hour, minute)
does not set the seconds to 0.
DateFormat
andGregorianCalendar
do not mesh properly. You must specify the Calendar twice, once indirectly as a Date.If the user has not configured his time zone correctly it will default quietly to either PST or GMT.
In GregorianCalendar, Months are numbered starting at January=0, rather than 1 as everyone else on the planet does. Yet days start at 1 as do days of the week with Sunday=1, Monday=2,… Saturday=7. Yet DateFormat. parse behaves in the traditional way with January=1.
I note you suggested this formula
=IF(ISNUMBER(FIND("RuhrP";F9));LOOKUP(A9;Ruhrpumpen!A$5:A$100;Ruhrpumpen!I$5:I$100);"")
.....but LOOKUP
isn't appropriate here because I assume you want an exact match (LOOKUP won't guarantee that and also data in lookup range has to be sorted), so VLOOKUP
or INDEX/MATCH
would be better....and you can also use IFERROR to avoid the IF function, i.e
=IFERROR(VLOOKUP(A9;Ruhrpumpen!A$5:Z$100;9;0);"")
Note: VLOOKUP always looks up the lookup value (A9) in the first column of the "table array" and returns a value from the nth column of the "table array" where n is defined by col_index_num, in this case 9
INDEX/MATCH is sometimes more flexible because you can explicitly define the lookup column and the return column (and return column can be to the left of the lookup column which can't be the case in VLOOKUP), so that would look like this:
=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH(A9;Ruhrpumpen!A$5:A$100;0));"")
INDEX/MATCH also allows you to more easily return multiple values from different columns, e.g. by using $ signs in front of A9 and the lookup range Ruhrpumpen!A$5:A$100, i.e.
=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH($A9;Ruhrpumpen!$A$5:$A$100;0));"")
this version can be dragged across to get successive values from column I, column J, column K etc.....
The question didn't defined if the background is a color or an image but since @Blowski have already answered for coloured backgrounds, there's a hack for images below:
background: linear-gradient(rgba(0,0,0,.6), rgba(0,0,0,.6)), url('image.jpg');
This way you can manipulate the color of your opacity and even add nice gradient effects.
.wrapper {_x000D_
width: 630px;_x000D_
height: 420px;_x000D_
display: table;_x000D_
background: linear-gradient(_x000D_
rgba(0,0,0,.8), _x000D_
rgba(0,0,0,.8)), _x000D_
url('http://cdn.moviestillsdb.com/sm/35bc3c6a2b791425de6caf8b9391026e/rambo-iii.jpg');_x000D_
}_x000D_
_x000D_
h1 {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
color: #fff;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<h1>Question 5770341</h1>_x000D_
</div>
_x000D_
You are able to do that using Traits in PHP which announced as of PHP 5.4
Here is a quick tutorial for you, http://culttt.com/2014/06/25/php-traits/
>
is the child combinator, sometimes mistakenly called the direct descendant combinator.1
That means the selector div > p.some_class
only selects paragraphs of .some_class
that are nested directly inside a div
, and not any paragraphs that are nested further within.
An illustration:
div > p.some_class {
background: yellow;
}
_x000D_
<div>
<p class="some_class">Some text here</p> <!-- Selected [1] -->
<blockquote>
<p class="some_class">More text here</p> <!-- Not selected [2] -->
</blockquote>
</div>
_x000D_
What's selected and what's not:
Selected
This p.some_class
is located directly inside the div
, hence a parent-child relationship is established between both elements.
Not selected
This p.some_class
is contained by a blockquote
within the div
, rather than the div
itself. Although this p.some_class
is a descendant of the div
, it's not a child; it's a grandchild.
Consequently, while div > p.some_class
won't match this element, div p.some_class
will, using the descendant combinator instead.
1 Many people go further to call it "direct child" or "immediate child", but that's completely unnecessary (and incredibly annoying to me), because a child element is immediate by definition anyway, so they mean the exact same thing. There's no such thing as an "indirect child".
The VS equivalent of a makefile is a "Solution" (over-simplified, I know).
In the config file, change the "host" variable to point to the external server. The config file is called config.inc.php
and it will be in the main phpMyAdmin folder. There should be a line like this:
$cfg['Servers'][$i]['host'] = 'localhost';
Just change localhost
to your server's IP address.
Note: you may have to configure the external server to allow remote connections, but I've done this several times on shared hosting so it should be fine.
Same question : how-to-update-the-gui-from-another-thread-in-c
Two Ways:
Return value in e.result and use it to set yout textbox value in backgroundWorker_RunWorkerCompleted event
Declare some variable to hold these kind of values in a separate class (which will work as data holder) . Create static instance of this class adn you can access it over any thread.
Example:
public class data_holder_for_controls
{
//it will hold value for your label
public string status = string.Empty;
}
class Demo
{
public static data_holder_for_controls d1 = new data_holder_for_controls();
static void Main(string[] args)
{
ThreadStart ts = new ThreadStart(perform_logic);
Thread t1 = new Thread(ts);
t1.Start();
t1.Join();
//your_label.Text=d1.status; --- can access it from any thread
}
public static void perform_logic()
{
//put some code here in this function
for (int i = 0; i < 10; i++)
{
//statements here
}
//set result in status variable
d1.status = "Task done";
}
}
Initializing a vector having struct, class or Union can be done this way
std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);
If you are going for a console command it would be:
chmod -R 777 /www/store
. The -R
(or --recursive
) options make it recursive.
Or if you want to make all the files in the current directory have all permissions type:
chmod -R 777 ./
If you need more info about chmod
command see: File permission
package com.tulu.ds;
public class EmailSecurity {
public static void main(String[] args) {
System.out.println(returnSecuredEmailID("[email protected]"));
}
private static String returnSecuredEmailID(String email){
String str=email.substring(1, email.lastIndexOf("@")-1);
return email.replaceAll(email.substring(1, email.lastIndexOf("@")-1),replacewith(str.length(),"*"));
}
private static String replacewith(int length,String replace) {
String finalStr="";
for(int i=0;i<length;i++){
finalStr+=replace;
}
return finalStr;
}
}
a = 10
for i in sorted(range(a), reverse=True):
print i
why you looking for this problem into your code? Even, if it's copypasted.
If you can see, what exactly happening after save file in synced folder - you will see something like *****
at the end of file. It's not related to your code at all.
Solution.
If you are using nginx
in vagrant box - add to server config:
sendfile off;
If you are using apache
in vagrant box - add to server config:
EnableSendfile Off;
Source of problem: VirtualBox Bug
To get a pure hex value this might be useful. It's based on Joe's answer:
def gethex(decimal):
return hex(decimal)[2:]
Simply do:
db.getCollection('test').find('4ecbe7f9e8c1c9092c000027');
If you use chldNode
as XmlElement
instead of XmlNode
, you can use
var attributeValue = chldNode.GetAttribute("Name");
The return value will just be an empty string, in case the attribute name does not exist.
So your loop could look like this:
XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");
foreach (XmlElement node in nodes)
{
var attributeValue = node.GetAttribute("Name");
}
This will select all nodes <node>
surrounded by <Node><N0de></N0de><Node>
tags and subsequently loop through them and read the attribute "Name".
public class ReverseLinkedList {
public static void main(String args[]){
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("a");
linkedList.add("b");
linkedList.add("c");
linkedList.add("d");
linkedList.add("e");
linkedList.add("f");
System.out.println("Original linkedList:");
for(int i = 0; i <=linkedList.size()-1; i++){
System.out.println(" - "+ linkedList.get(i));
}
LinkedList<String> reversedlinkedList = reverse(linkedList);
System.out.println("Reversed linkedList:");
for(int i = 0; i <=reversedlinkedList.size()-1; i++){
System.out.println(" - "+ reversedlinkedList.get(i));
}
}
public static LinkedList<String> reverse(LinkedList<String> linkedList){
for(int i = 0; i < linkedList.size()/2; i++){
String temp = linkedList.get(i);
linkedList.set(i, linkedList.get(linkedList.size()-1-i));
linkedList.set((linkedList.size()-1-i), temp);
}
return linkedList;
}
}
Use this in your code:
String.valueOf(x);
lsof -P | grep ':3000' | awk '{print $2}'
This will give you just the pid, tested on MacOS.
From here
You should be referencing a copy of the library that you copied to your development workspace—you should not reference the library directly from the Android SDK directory.
I faced this error because I referenced the original copy from SDK directory. Make sure that you first copy the library to android workspace and only reference it. In eclipse you can do it by checking "Copy projects into workspace" while importing the project.
Although <input>
ignores the rows
attribute, you can take advantage of the fact that <textarea>
doesn't have to be inside <form>
tags, but can still be a part of a form by referencing the form's id:
<form method="get" id="testformid">
<input type="submit" />
</form>
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>
Of course, <textarea>
now appears below "submit" button, but maybe you'll find a way to reposition it.
You can set a reference to the Scripting.Runtime library and then use the FileSystemObject. It has a DeleteFile method and a FileExists method.
See the MSDN article here.
Here is a snippet code through a chain of environments properties files are being loaded for different environments.
Properties file under your application resources ( src/main/resources ):-
1. application.properties
2. application-dev.properties
3. application-uat.properties
4. application-prod.properties
Ideally, application.properties contains all common properties which are accessible for all environments and environment related properties only works on specifies environment. therefore the order of loading these properties files will be in such way -
application.properties -> application.{spring.profiles.active}.properties.
Code snippet here :-
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class PropertiesUtils {
public static final String SPRING_PROFILES_ACTIVE = "spring.profiles.active";
public static void initProperties() {
String activeProfile = System.getProperty(SPRING_PROFILES_ACTIVE);
if (activeProfile == null) {
activeProfile = "dev";
}
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer
= new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[]
{new ClassPathResource("application.properties"),
new ClassPathResource("application-" + activeProfile + ".properties")};
propertySourcesPlaceholderConfigurer.setLocations(resources);
}
}
You need to add a COM reference in your project to the "Microsoft Excel 11.0 Object Library
" - or whatever version is appropriate.
This code works for me:
private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
Microsoft.Office.Interop.Excel.Application xlApp = null;
Workbook xlWorkbook = null;
Sheets xlSheets = null;
Worksheet xlNewSheet = null;
try {
xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
return;
// Uncomment the line below if you want to see what's happening in Excel
// xlApp.Visible = true;
xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
xlSheets = xlWorkbook.Sheets as Sheets;
// The first argument below inserts the new worksheet as the first one
xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = worksheetName;
xlWorkbook.Save();
xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
xlApp.Quit();
}
finally {
Marshal.ReleaseComObject(xlNewSheet);
Marshal.ReleaseComObject(xlSheets);
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
}
Note that you want to be very careful about properly cleaning up and releasing your COM object references. Included in that StackOverflow question is a useful rule of thumb: "Never use 2 dots with COM objects". In your code; you're going to have real trouble with that. My demo code above does NOT properly clean up the Excel app, but it's a start!
Some other links that I found useful when looking into this question:
According to MSDN
To use COM interop, you must have administrator or Power User security permissions.
Hope that helps.
all you need to know is in Jackson Documentation https://www.baeldung.com/jackson-serialize-dates
Ad.9 quick solved the problem for me.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Try the jQuery starts-with
selector, '^=', eg
[id^="jander"]
I have to ask though, why don't you want to do this using classes?
Code check:
This is offtopic here but the people over at CodeReview are more than happy to help you.
I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.
Lists:
As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List
.
Lists are very straightforward to use but take a look at the related documentation anyway.
A very simple example to keep multiple bikes in a list:
List<Motorbike> bikes = new List<Motorbike>();
bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });
And to iterate over the list you can use the foreach
statement:
foreach(var bike in bikes) {
Console.WriteLine(bike.make);
}
I just want to echo sam9046's modest comment as an alternative and potentially much easier solution that worked in my case: uninstall and install homebrew again from scratch. No sudo commands required.
You can also browse/modify the uninstall script from that link above if you need to ensure it won't affect your previously installed packages. In my case this was just my home machine so I just started over.
Keep it simple!
var classes = $(this).parent('div').attr('class');
If the variant is empty then an error will be thrown. The bullet-proof code is the following:
Public Function GetLength(a As Variant) As Integer
If IsEmpty(a) Then
GetLength = 0
Else
GetLength = UBound(a) - LBound(a) + 1
End If
End Function
You shouldn't raise
the warning, you should be using warnings
module. By raising it you're generating error, rather than warning.
myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [i/myInt for i in myList]
!important
is a part of CSS1.
Browsers supporting it: IE5.5+, Firefox 1+, Safari 3+, Chrome 1+.
It means, something like:
Use me, if there is nothing important else around!
Cant say it better.
For check it with ngModel, make a merge between "ngModel" and "value", Example:
<mat-checkbox [(ngModel)]="myVariable" value="1" >Subscribe</mat-checkbox>
Where, myVariable = 1
Greeting
If you are using “import android.app.Fragment;” Then use either:
1)
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.specific_function_name();
Where R.id.example_fragment is most likely the FrameLayout id inside your xml layout. OR
2)
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentByTag(“FragTagName”);
fragment.specific_function_name();
Where FragTagName is the name u specified when u did:
TabHost mTabHost.newTabSpec(“FragTagName”)
If you are using “import android.support.v4.app.Fragment;” Then use either:
1)
ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.example_fragment);
fragment.specific_function_name();
OR
2)
ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentByTag(“FragTagName”);
fragment.specific_function_name();
Swift 3 version
import UIKit
protocol PhoneCalling {
func call(phoneNumber: String)
}
extension PhoneCalling {
func call(phoneNumber: String) {
let cleanNumber = phoneNumber.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "-", with: "")
guard let number = URL(string: "telprompt://" + cleanNumber) else { return }
UIApplication.shared.open(number, options: [:], completionHandler: nil)
}
}
Here are the instructions from github:
touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/tqisjim/google-oauth.git
git push -u origin master
Here's what actually worked:
touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/tqisjim/google-oauth.git
git clone origin master
After cloning, then the push command succeeds by prompting for a username and password
Google now has a feature stating that it won't allow insecure devices to send emails. When I ran my program it came up with the error in the first post. I had to go into my account and allow insecure apps to send emails, which I did by clicking on my account, going into the security tab, and allowing insecure apps to use my gmail.
The openssh project lists several Java alternatives, Trilead SSH for Java seems to fit what you're asking for.
JavaScript setTimeout
is a very good solution:
function funcx()
{
// your code here
// break out here if needed
setTimeout(funcx, 3000);
}
funcx();
The delay
function in jQuery is mostly used for delaying animations in a jQuery animation queue.
Just insert the line into RatingBar:
android:isIndicator="true"
In XML the ratingbar look like this.
<RatingBar
android:id="@+id/ratingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:isIndicator="true"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false" />
Another issue here is that you likely need to turn off "connect as media device" to be able to connect with adb.
$('div[id ^= "player_"]');
This worked for me..select all Div starts with "players_" keyword and display it.
UPDATE on the Android studio AVD:
No microwaves or elevators :)
You are so close!
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
cursor = cnxn.cursor()
cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")
for row in cursor.fetchall():
print row
(the "columns()" function collects meta-data about the columns in the named table, as opposed to the actual data).
You can do this more simply using plot()
instead of plot_date()
.
First, convert your strings to instances of Python datetime.date
:
import datetime as dt
dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here
Then plot:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()
Result:
Check whether your template in theme
folder contains search.php
and searchform.php
or not.
workbench.action.quickOpen
.You can use this to search the Keyboard Shortcuts
menu located in Preferences
.
On MacOS the default keybinding is cmd ? + P.
(Coming from Sublime Text, I always change this to cmd ? + T)
The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.
As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:
/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml
The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.
BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is
@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
public void bussinesMethod(){
}
}
No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.
Now in your client code you need to lookup "MyComponentName".
You can also use extremely small numbers for your radius'.
<corners
android:bottomRightRadius="0.1dp" android:bottomLeftRadius="2dp"
android:topLeftRadius="2dp" android:topRightRadius="0.1dp" />
Just because you use a buffer doesn't mean the stream has to fill that buffer. In other words, this should be okay:
public static void copyStream(InputStream input, OutputStream output)
throws IOException
{
byte[] buffer = new byte[1024]; // Adjust if you want
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1)
{
output.write(buffer, 0, bytesRead);
}
}
That should work fine - basically the read
call will block until there's some data available, but it won't wait until it's all available to fill the buffer. (I suppose it could, and I believe FileInputStream
usually will fill the buffer, but a stream attached to a socket is more likely to give you the data immediately.)
I think it's worth at least trying this simple solution first.
From how it looks, I think grouping by multiple columns/fields wont hurt your result. Why don't you try adding to the group by like this:
GROUP BY `proof_type`, `id`
This will group by proof_type
first then id
. I hope this does not alter the results. In some/most cases group by multiple columns gives wrong results.
[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}
According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.
So to create a empty file do:
var f = new File([""], "filename");
The third argument looks like:
var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.
touchstart or touchend are not good, because if you scroll the page, the device do stuff. So, if I want close a window with tap or click outside the element, and scroll the window, I've done:
$(document).on('touchstart', function() {
documentClick = true;
});
$(document).on('touchmove', function() {
documentClick = false;
});
$(document).on('click touchend', function(event) {
if (event.type == "click") documentClick = true;
if (documentClick){
doStuff();
}
});
Here's a (probably very bash-specific) little function involving bash variable indirection and unset
; it's a general solution that does not involve text substitution or discarding empty elements and has no problems with quoting/whitespace etc.
delete_ary_elmt() {
local word=$1 # the element to search for & delete
local aryref="$2[@]" # a necessary step since '${!$2[@]}' is a syntax error
local arycopy=("${!aryref}") # create a copy of the input array
local status=1
for (( i = ${#arycopy[@]} - 1; i >= 0; i-- )); do # iterate over indices backwards
elmt=${arycopy[$i]}
[[ $elmt == $word ]] && unset "$2[$i]" && status=0 # unset matching elmts in orig. ary
done
return $status # return 0 if something was deleted; 1 if not
}
array=(a 0 0 b 0 0 0 c 0 d e 0 0 0)
delete_ary_elmt 0 array
for e in "${array[@]}"; do
echo "$e"
done
# prints "a" "b" "c" "d" in lines
Use it like delete_ary_elmt ELEMENT ARRAYNAME
without any $
sigil. Switch the == $word
for == $word*
for prefix matches; use ${elmt,,} == ${word,,}
for case-insensitive matches; etc., whatever bash [[
supports.
It works by determining the indices of the input array and iterating over them backwards (so deleting elements doesn't screw up iteration order). To get the indices you need to access the input array by name, which can be done via bash variable indirection x=1; varname=x; echo ${!varname} # prints "1"
.
You can't access arrays by name like aryname=a; echo "${$aryname[@]}
, this gives you an error. You can't do aryname=a; echo "${!aryname[@]}"
, this gives you the indices of the variable aryname
(although it is not an array). What DOES work is aryref="a[@]"; echo "${!aryref}"
, which will print the elements of the array a
, preserving shell-word quoting and whitespace exactly like echo "${a[@]}"
. But this only works for printing the elements of an array, not for printing its length or indices (aryref="!a[@]"
or aryref="#a[@]"
or "${!!aryref}"
or "${#!aryref}"
, they all fail).
So I copy the original array by its name via bash indirection and get the indices from the copy. To iterate over the indices in reverse I use a C-style for loop. I could also do it by accessing the indices via ${!arycopy[@]}
and reversing them with tac
, which is a cat
that turns around the input line order.
A function solution without variable indirection would probably have to involve eval
, which may or may not be safe to use in that situation (I can't tell).
//javascript
//teams.Table does not exist
function OnSuccessJSON(data, status) {
var teams = eval('(' + data.d + ')');
var listItems = "";
for (var i = 0; i < teams.length; i++) {
listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
}
$("#<%=ddlTeams.ClientID%>").html(listItems);
}
Set the background color of the src to none and allow transparencey.
[WITHIN SCR PAGE STYLE]
<style type="text/css">
body
{
background:none transparent;
}
</style>
[IFRAME]
<iframe src="#" allowtransparency="true">Error, iFrame failed to load.</iframe>
NOTE: I code my CSS a little different to how everyone else does.
Since you asked for a C++ solution...
#include <algorithm>
#include <iterator>
const int arr_size = 10;
some_type src[arr_size];
// ...
some_type dest[arr_size];
std::copy(std::begin(src), std::end(src), std::begin(dest));
AFAIU java.lang.Process is the process created by java itself (like Runtime.exec('firefox'))
You can use system-dependant commands like
Runtime rt = Runtime.getRuntime();
if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1)
rt.exec("taskkill " +....);
else
rt.exec("kill -9 " +....);
{
height:100vh;
width:100vw;
}
You should bind the tap event, the click does not exist on mobile safari or in the UIWbview. You can also use this polyfill ,to avoid the 300ms delay when a link is touched.
Since java.sql.Date
extends java.util.Date
, you should be able to do
java.util.Date newDate = result.getDate("VALUEDATE");
I did a little research and was able to write this code:
strbody = "<BODY style=font-size:11pt;font-family:Calibri>Good Morning;<p>We have completed our main aliasing process for today. All assigned firms are complete. Please feel free to respond with any questions.<p>Thank you.</BODY>"
apparently by setting the "font-size=11pt"
instead of setting the font size <font size=5>
,
It allows you to select a specific font size like you normally would in a text editor, as opposed to selecting a value from 1-7 like my code was originally.
This link from simpLE MAn gave me some good info.
You can accomplish this via method overloading.
public int doSomething(int arg1, int arg2)
{
return 0;
}
public int doSomething()
{
return doSomething(defaultValue0, defaultValue1);
}
By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.
You can try this one
img{
max-height:500px;
max-width:500px;
height:auto;
width:auto;
}
This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px
You can check this post
I used this:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
If it's one script it's fine with the above solution.
I would set up Ansible to do the Job. It works in the same way (Ansible uses ssh to execute the scripts on the remote machine for both Unix or Windows).
It will be more structured and maintainable.
WebClient client = new WebClient();
using (Stream data = client.OpenRead(Text))
{
using (StreamReader reader = new StreamReader(data))
{
string content = reader.ReadToEnd();
string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
MatchCollection matches = Regex.Matches(content,pattern);
List<string> urls = new List<string>();
foreach (Match match in matches)
{
urls.Add(match.Value);
}
}
My solution, it seems it can be in O(n) time as Hash map access is O(1), and filter is O(n). It also uses by closure to select property by which to make the distinction of elements in sequence.
extension Sequence {
func distinct<T: Hashable>(by: (Element) -> T) -> [Element] {
var seen: [T: Bool] = [:]
return self.filter { seen.updateValue(true, forKey: by($0)) == nil }
}
}
I'm not a JS pro, but I figured out a couple ways you could do this.
The HTML:
<p id="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi elementum consequat tortor et euismod. Nam commodo consequat libero vel lobortis. Morbi ac nisi at leo vehicula consectetur.</p>
Then with jQuery you truncate it down to a specific character count but leave the last word like this:
// Truncate but leave last word
var myTag = $('#truncate').text();
if (myTag.length > 100) {
var truncated = myTag.trim().substring(0, 100).split(" ").slice(0, -1).join(" ") + "…";
$('#truncate').text(truncated);
}
The result looks like this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
elementum consequat tortor et…
Or, you can simply truncate it down to a specific character count like this:
// Truncate to specific character
var myTag = $('#truncate').text();
if (myTag.length > 15) {
var truncated = myTag.trim().substring(0, 100) + "…";
$('#truncate').text(truncated);
}
The result looks like this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
elementum consequat tortor et euismod…
Hope that helps a bit.
Here is the jsFiddle.
Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.
<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>
<script>
document.getElementById('click').addEventListener('click', function(){
doStuff();
});
function doStuff() {
for(var i=1; i<=2; i++){
var el = document.getElementById("hello" + i);
el.style.display = 'none';
}
}
</script>
Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.
May be you are missing Third party library
to like actionBarSherlock, slidingMenu, achartengine
Add it into lib
folder and Add to Build Path
..
Its work for me.
From the answer of @DevWL, I got "Undefined offset ..." at
if ($j<($num_fields-1)) { $data.= ','; }
I made some changes to:
class DBbackup {
public $suffix;
public $dirs;
protected $dbInstance;
public function __construct() {
try{
$this->dbInstance = new PDO("mysql:host=".$dbhost.";dbname=".$dbname,
$username, $password);
} catch(Exception $e) {
die("Error ".$e->getMessage());
}
$this->suffix = date('Ymd_His');
}
public function backup($tables = '*'){
$output = "-- database backup - ".date('Y-m-d H:i:s').PHP_EOL;
$output .= "SET NAMES utf8;".PHP_EOL;
$output .= "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';".PHP_EOL;
$output .= "SET foreign_key_checks = 0;".PHP_EOL;
$output .= "SET AUTOCOMMIT = 0;".PHP_EOL;
$output .= "START TRANSACTION;".PHP_EOL;
//get all table names
if($tables == '*') {
$tables = [];
$query = $this->dbInstance->prepare('SHOW TABLES');
$query->execute();
while($row = $query->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
$query->closeCursor();
}
else {
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
foreach($tables as $table) {
$query = $this->dbInstance->prepare("SELECT * FROM `$table`");
$query->execute();
$output .= "DROP TABLE IF EXISTS `$table`;".PHP_EOL;
$query2 = $this->dbInstance->prepare("SHOW CREATE TABLE `$table`");
$query2->execute();
$row2 = $query2->fetch(PDO::FETCH_NUM);
$query2->closeCursor();
$output .= PHP_EOL.$row2[1].";".PHP_EOL;
while($row = $query->fetch(PDO::FETCH_NUM)) {
$output .= "INSERT INTO `$table` VALUES(";
for($j=0; $j<count($row); $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
if (isset($row[$j]))
$output .= "'".$row[$j]."'";
else $output .= "''";
if ($j<(count($row)-1))
$output .= ',';
}
$output .= ");".PHP_EOL;
}
}
$output .= PHP_EOL.PHP_EOL;
$output .= "COMMIT;";
//save filename
$filename = 'db_backup_'.$this->suffix.'.sql';
$this->writeUTF8filename($filename,$output);
}
private function writeUTF8filename($fn,$c){ /* save as utf8 encoding */
$f=fopen($fn,"w+");
# Now UTF-8 - Add byte order mark
fwrite($f, pack("CCC",0xef,0xbb,0xbf));
fwrite($f,$c);
fclose($f);
}
}
And usage example:
$Backup = new DBbackup();
$Backup->backup();
This works great on MySQL 10.1.34-MariaDB , PHP : 7.2.7
A other users suggested,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
If you wish to keep data, like event handlers for example, you should use
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
I often use this to remember the two:
My use case: I am going to the city.
includes -> drive the car
extends -> fill the petrol
"Fill the petrol" may not be required at all times, but may optionally be required based on the amount of petrol left in the car. "Drive the car" is a prerequisite hence I am including.
Using ES6 the javascript becomes a little cleaner
handleFiles(input) {
const file = input.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const file = event.target.result;
const allLines = file.split(/\r\n|\n/);
// Reading line by line
allLines.forEach((line) => {
console.log(line);
});
};
reader.onerror = (event) => {
alert(event.target.error.name);
};
reader.readAsText(file);
}
This answer builds on Zach Smith's answer by resetting the identity column as well:
Here is the query:
-- Disable all constraints in the database
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
declare @catalog nvarchar(250);
declare @schema nvarchar(250);
declare @tbl nvarchar(250);
DECLARE i CURSOR LOCAL FAST_FORWARD FOR select
TABLE_CATALOG,
TABLE_SCHEMA,
TABLE_NAME
from INFORMATION_SCHEMA.TABLES
where
TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME != 'sysdiagrams'
AND TABLE_NAME != '__RefactorLog'
-- Optional
-- AND (TABLE_SCHEMA = 'dbo')
OPEN i;
FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @sql NVARCHAR(MAX) = N'DELETE FROM [' + @catalog + '].[' + @schema + '].[' + @tbl + '];'
/* Make sure these are the commands you want to execute before executing */
PRINT 'Executing statement: ' + @sql
--EXECUTE sp_executesql @sql
-- Reset identity counter if one exists
IF ((SELECT OBJECTPROPERTY( OBJECT_ID(@catalog + '.' + @schema + '.' + @tbl), 'TableHasIdentity')) = 1)
BEGIN
SET @sql = N'DBCC CHECKIDENT ([' + @catalog + '.' + @schema + '.' + @tbl + '], RESEED, 0)'
PRINT 'Executing statement: ' + @sql
--EXECUTE sp_executesql @sql
END
FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
END
CLOSE i;
DEALLOCATE i;
-- Re-enable all constraints again
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes
https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task
I made it work with this:
.element {
transition: height 3s ease-out, width 5s ease-in;
}
I solved the issue by configuring environment.rb as
YourApp::Application.default_url_options = YourApp::Application.config.action_mailer.default_url_options
You need to set default_url_options for action mailer against each environment like development, testing, staging and production etc.
Reference: Missing host to link to! Please provide :host parameter or set default_url_options[:host]
It might work if you rewrite this
function myfun(){ ... return 0; else return 1; fi;}
as this function myfun(){ ... return; else false; fi;}
. That is if false
is the last instruction in the function you get false result for whole function but return
interrupts function with true result anyway. I believe it's true for my bash interpreter at least.
The following format should work:
$.ajax({
type: "POST",
url: "@Url.Action("refresh", "group")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
myDate: '2011-04-02 17:15:45'
}),
success: function (result) {
//do something
},
error: function (req, status, error) {
//error
}
});
Very simple to fix, you just need to turn the parameter to writerow into a list.
for item in RESULTS:
wr.writerow([item,])
String str = "Good";
str = str + " Morning";
In the above code you create 3 String
Objects.
Note: Strings are always immutable. There is no, such thing as a mutable String. str
is just a reference which eventually points to "Good Morning". You are actually, not working on 1
object. you have 3
distinct String
Objects.
StringBuffer str = new StringBuffer("Good");
str.append(" Morning");
StringBuffer
contains an array of characters. It is not same as a String
.
The above code adds characters to the existing array. Effectively, StringBuffer
is mutable, its String
representation isn't.
A version without error-handling:
Function sheetExists(sheetToFind As String) As Boolean
sheetExists = False
For Each sheet In Worksheets
If sheetToFind = sheet.name Then
sheetExists = True
Exit Function
End If
Next sheet
End Function
I had this problem too. I found setting the appearance to none helped.
.class {
appearance:none;
-moz-appearance:none;
-webkit-appearance:none;
background-color: red;
}
To say lack of tools suggest lack of need is just begging the question. The same could be applied to support for X or Y in Linux (Why bother developing quality drivers and/or games for such a minority OS? And why pay attention to an OS that big game and hardware companies don't develop for?). Probably the people who would need to use XSLT and JSON end up using a somewhat trivial workaround: Transforming JSON into XML. But that's not the optimal solution, is it?
When you have a native JSON format and you want to edit it "wysywyg" in the browser, XSLT would be a more than adequate solution for the problem. Doing that with traditional javascript programming can become a pain in the arse.
In fact, I have implemented a "stone-age" approach to XSLT, using substring parsing to interpret some basic commands for javascript, like calling a template, process children, etc. Certainly implementing a transformation engine with a JSON object is much easier than implementing a full-fledged XML parser to parse the XSLT. Problem is, that to use XML templates to transform a JSON object you need to parse the XML of the templates.
To tranform a JSON object with XML (or HTML, or text or whatever) you need to think carefully about the syntax and what special characters you need to use to identify the transformation commands. Otherwise you'll end up having to design a parser for your own custom templating language. Having walked through that path, I can tell you that it's not pretty.
Update (Nov 12, 2010): After a couple of weeks working on my parser, I've been able to optimize it. Templates are parsed beforehand and commands are stored as JSON objects. Transformation rules are also JSON objects, while the template code is a mix of HTML and a homebrew syntax similar to shell code. I've been able to transform a complex JSON document into HTML to make a document editor. The code is around 1K lines for the editor (it's for a private project so I can't share it) and around 990 lines for the JSON transformation code (includes iteration commands, simple comparisons, template calling, variable saving and evaluation). I plan to release it under a MIT license. Drop me a mail if you want to get involved.
I got the same error, when I was trying to import matplotlib.pyplot
In [1]: import matplotlib.pyplot as plt
...
...
ImportError: No module named PyQt4.QtCore
But in my case the problem was due to a missing linux library libGL.so.1
OS : Cent OS 64 bit
Python version : 3.5.2
$> locate libGL.so.1
If this command returns a value, your problem could be different, so please ignore my answer. If it does not return any value and your environment is same as mine, below steps would fix your problem.
$> yum install mesa-libGL.x86_64
This installs the necessary OpenGL libraries for 64 bit Cent OS.
$> locate libGL.so.1
/usr/lib/libGL.so.1
Now go back to iPython and try to import
In [1]: import matplotlib.pyplot as plt
This time it imported successfully.
Here is how you can add an icon while creating an exe file from a Python file
open command prompt at the place where Python file exist
type:
pyinstaller --onefile -i"path of icon" path of python file
Example-
pyinstaller --onefile -i"C:\icon\Robot.ico" C:\Users\Jarvis.py
This is the easiest way to add an icon.
replace the password fields from the input:
{"_csrf":["9d90c85f-ac73-4b15-ad08-ebaa3fa4a005"],"originPassword":["uaas"],"newPassword":["uaas"],"confirmPassword":["uaas"]}
private static final Pattern PATTERN = Pattern.compile(".*?password.*?\":\\[\"(.*?)\"\\](,\"|}$)", Pattern.CASE_INSENSITIVE);
private static String replacePassword(String input, String replacement) {
Matcher m = PATTERN.matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find()) {
Matcher m2 = PATTERN.matcher(m.group(0));
if (m2.find()) {
StringBuilder stringBuilder = new StringBuilder(m2.group(0));
String result = stringBuilder.replace(m2.start(1), m2.end(1), replacement).toString();
m.appendReplacement(sb, result);
}
}
m.appendTail(sb);
return sb.toString();
}
@Test
public void test1() {
String input = "{\"_csrf\":[\"9d90c85f-ac73-4b15-ad08-ebaa3fa4a005\"],\"originPassword\":[\"123\"],\"newPassword\":[\"456\"],\"confirmPassword\":[\"456\"]}";
String expected = "{\"_csrf\":[\"9d90c85f-ac73-4b15-ad08-ebaa3fa4a005\"],\"originPassword\":[\"**\"],\"newPassword\":[\"**\"],\"confirmPassword\":[\"**\"]}";
Assert.assertEquals(expected, replacePassword(input, "**"));
}
code {_x000D_
background: black;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
Tested and works in Safari 5 and IE6+.
I had to run
php-config --configure-options --enable-soap
as root and restart apache.
That worked! Now my phpinfo() call shows the SOAP section.
There is no 'array' type in batch files, which is both an upside and a downside at times, but there are workarounds.
Here's a link that offers a few suggestions for creating a system for yourself similar to an array in a batch: http://hypftier.de/en/batch-tricks-arrays.
echo variable >> filepath
works for echoing the contents of a variable to a file,echo.
(the period is not a typo) works for echoing a newline character.I think that these two together should work to accomplish what you need.