I solved it by global searching the missing directory in the project. then delete any files containing that keyword. it can clean successfully after I remove all the build
and .externalNativeBuild
directories manually.
if you have :
/Users/james/Development/AndroidProjects/myapp/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.0/res/values-v23/values-v23.xml
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.
error , you must change your appcompat
, buildtools
, sdk
to 23
but , if you don't like to change it and must be in 22
do this :
Your compile SDK version must match the support library major version. This is the solution to your problem. You can check it easily in your Gradle Scripts in build.gradle
file.
Fx: if your compileSdkVersion
is 23 your compile library must start at 23.
compileSdkVersion 23
buildToolsVersion "23.0.0"
defaultConfig {
minSdkVersion 15
targetSdkVersion 23
versionCode 340
versionName "3.4.0"
}
dependencies {
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:recyclerview-v7:23.0.1'
}
And always check that your Android Studoi has the supported API Level. You can check it in your Android SDK, like this:
Open Android Studio -> Open Manifest File
add
<uses-sdk tools:overrideLibrary="android.support.v17.leanback"/>
don't forget to include xmlns:tools="http://schemas.android.com/tools"
too, before the <application>
tag
my solucion is compile with other version
build.gradle (app)
compileSdkVersion 21
Good Luck
I was up to date with everything and still got this error, not sure why but I think the image was corrupted in a strange way and after replacing the image I got rid of the error. Might be worth to try with a different image :)
In my case
I Followed This answer
Changed the location of project.
Tried another android device [Build and success install]
Tried on my android device [Build and success install * Uninstall any previous version of same app on device]
Edit- Again it happend
I had this error message and lot of others like
x-version is deprecated and use y-version instead and it'll be removed in 2019
and all of my project started giving same error messages suddenly.
Android studio was giving warnings about my antivirus program. I tried configuring it but didn't work.
Finally I uninstalled QuickHeal antivirus from my system and all is well now
I had similar issue Cannot resolve com.google.android.gms.common.
I followed setup guide http://developer.android.com/google/play-services/setup.html and it works!
Summary:
compile 'com.google.android.gms:play-services:4.0.30'
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
I had the same problem, and my solution is changing the support version '27.+'(27.1.0) to '27.0.1'
Cleaning the Project using Build in Menu Bar work for many error scenarios in Android Studio and so it does in this case.
grep
matches, grep -v
does the inverse. If you need to "match A but not B" you usually use pipes:
grep "${PATT}" file | grep -v "${NOTPATT}"
Sounds like your class loader is not loading the servlet classes once they are updated. This might be fixed if you change your web.xml file which should prompt the server/container to re-deploy and reload the servlet classes. I guess add an empty line at the end of your web.xml and save it and then see if that fixes it. As i said this might fix it or might not.
Good luck!
I use React and Rails. I did:
js
let params = {
filter_array: ['A', 'B', 'C']
}
...
//transform params in URI
Object.keys(params).map(key => {
if (Array.isArray(params[key])) {
return params[key].map((value) => `${key}[]=${value}`).join('&')
}
}
//filter_array[]=A&filter_array[]=B&filter_array[]=C
In any web application, there will be a web.xml
in the WEB-INF/
folder.
If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml
is under TOMCAT_HOME/conf/web.xml
Either way, the relevant lines of the web.xml are
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
so any file matching this pattern when found will be shown as the home page.
In Tomcat, a web.xml setting within your web app will override the default, if present.
Further Reading
I'm an oracle guy, but I believe MS SQL Server has support for the connect by clause:
select sysdate + level
from dual
connect by level <= 10 ;
The output is:
SYSDATE+LEVEL
05-SEP-09
06-SEP-09
07-SEP-09
08-SEP-09
09-SEP-09
10-SEP-09
11-SEP-09
12-SEP-09
13-SEP-09
14-SEP-09
Dual is just a 'dummy' table that comes with oracle (it contains 1 row and the word 'dummy' as the value of the single column).
I realize this is on older question but just wanted to add that
Environment.NewLine
also works if doing this through code.
Testing this in Chrome, you need to add
padding: 0px;
To the CSS.
Yes.
public class IncrementTest extends TestCase {
public void testPreIncrement() throws Exception {
int i = 0;
int j = i++;
assertEquals(0, j);
assertEquals(1, i);
}
public void testPostIncrement() throws Exception {
int i = 0;
int j = ++i;
assertEquals(1, j);
assertEquals(1, i);
}
}
Step 1:
select object_name, s.sid, s.serial#, p.spid
from v$locked_object l, dba_objects o, v$session s, v$process p
where l.object_id = o.object_id and l.session_id = s.sid and s.paddr = p.addr;
Step 2:
alter system kill session 'sid,serial#'; --`sid` and `serial#` get from step 1
More info: http://www.oracle-base.com/articles/misc/killing-oracle-sessions.php
Register an out parameter for the stored procedure, and set the value based on @@ROWCOUNT
if using SQL Server. Use SQL%ROWCOUNT
if you are using Oracle.
Mind that if you have multiple INSERT/UPDATE/DELETE
, you'll need a variable to store the result from @@ROWCOUNT
for each operation.
This line is causing problems:
(-b+math.sqrt(b**2-4*a*c))/2*a
x/2*a
is interpreted as (x/2)*a
. You need more parentheses:
(-b + math.sqrt(b**2 - 4*a*c)) / (2 * a)
Also, if you're already storing d
, why not use it?
x = (-b + math.sqrt(d)) / (2 * a)
How about
...
C() : arr{ {1,2,3} }
{}
...
?
Compiles fine on g++ 4.8
myList = [i.split('\t')[0] for i in myList]
If you are using Microsoft windows environment then you can set a variable named HTTP_PROXY
, FTP_PROXY
, or HTTPS_PROXY
depending on the requirement.
I have used following settings for allowing my commands at windows command prompt to use the browser proxy to access internet.
set HTTP_PROXY=http://proxy_userid:proxy_password@proxy_ip:proxy_port
The parameters on right must be replaced with actual values.
Once the variable HTTP_PROXY
is set, all our subsequent commands executed at windows command prompt will be able to access internet through the proxy along with the authentication provided.
Additionally if you want to use ftp and https as well to use the same proxy then you may like to the following environment variables as well.
set FTP_PROXY=%HTTP_PROXY%
set HTTPS_PROXY=%HTTP_PROXY%
By default Mysql store and return ‘date’ data type values in “YYYY/MM/DD” format. So if we want to display date in different format then we have to format date values as per our requirement in scripting language
And by the way what is the column data type and in which format you are storing the value.
This question is very interesting for me because I have problems, when I run container after execution finishes immediately exit and I fixed with -it:
docker run -it -p 3000:3000 -v /app/node_modules -v $(pwd):/app <your_container_id>
And when I must automate it with docker compose:
version: '3'
services:
frontend:
stdin_open: true
tty: true
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
volumes:
- /app/node_modules
- .:/app
This makes the trick: stdin_open: true, tty: true
This is a project generated with create-react-app
Dockerfile.dev it looks this that:
FROM node:alpine
WORKDIR '/app'
COPY package.json .
RUN npm install
COPY . .
CMD ["npm", "run", "start"]
Hope this example will help other to run a frontend(react in example) into docker container.
This will return true if String only contains ASCII characters and false when it does not
Charset.forName("US-ASCII").newEncoder().canEncode(str)
If You want to remove non ASCII , here is the snippet:
if(!Charset.forName("US-ASCII").newEncoder().canEncode(str)) {
str = str.replaceAll("[^\\p{ASCII}]", "");
}
Try this one
$('<div></div>').appendTo('body')
.html('<div><h6>Yes or No?</h6></div>')
.dialog({
modal: true, title: 'message', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
doFunctionForYes();
$(this).dialog("close");
},
No: function () {
doFunctionForNo();
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
SELECT table_name, owner FROM all_tables where owner='schema_name' order by table_name
I prefers using Guava :
import com.google.common.base.Charsets;
import com.google.common.io.Files;
File file = new File("/path/to/file", Charsets.UTF_8);
String content = Files.toString(file);
These are equivalent.
#pragma omp parallel
spawns a group of threads, while #pragma omp for
divides loop iterations between the spawned threads. You can do both things at once with the fused #pragma omp parallel for
directive.
I have been using Inno Setup for an installer. I'm using 64-bit Windows 7 only. I'm finding that registry entries are being written to
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
I haven't yet figured out how to get this list to be reported by WMI (although the program is listed as installed in Programs and Features). If I figure it out, I'll try to remember to report back here.
UPDATE:
Entries for 32-bit programs installed on a 64-bit machine go in that registry location. There's more written here:
http://mdb-blog.blogspot.com/2010/09/c-check-if-programapplication-is.html
See my comment that describes 32-bit vs 64-bit behavior in that same post here:
Unfortunately, there doesn't seem to be a way to get WMI to list all programs from the add/remove programs list (aka Programs and Features in Windows 7, not sure about Vista). My current code has dropped WMI in favor of using the registry. The code itself to interrogate the registry is even easier than using WMI. Sample code is in the above link.
You need to use background-image instead of backgroundImage. For example:
$(function() {
$('.home').click(function() {
$(this).css('background-image', 'url(images/tabs3.png)');
});
}):
We should have the projects which include (at least) all the filtered tags, or said in a different way, exclude the ones which doesn't include all those filtered tags.
So we can use Linq Except
to get those tags which are not included. Then we can use Count() == 0
to have only those which excluded no tags:
var res = projects.Where(p => filteredTags.Except(p.Tags).Count() == 0);
Or we can make it slightly faster with by replacing Count() == 0
with !Any()
:
var res = projects.Where(p => !filteredTags.Except(p.Tags).Any());
I know it's an old post, but you can use JSON5 for this purpose.
<script src="json5.js"></script>
<script>JSON.stringify(JSON5.parse('{a:1}'))</script>
You can use IDA Pro by Hex-Rays. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a lot of manual labor reversing the code.
If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rough though, at least when I used it a couple of years ago.
Try the Terminal Services PowerShell Module:
Get-TSSession -ComputerName comp1 -UserName user1 | Stop-TSSession -Force
Using return;
will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach
loop.
Try the following little program:
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
stringList.stream().forEach(str -> {
if (str.equals("b")) return; // only skips this iteration.
System.out.println(str);
});
}
Output:
a
c
Notice how the return;
is executed for the b
iteration, but c
prints on the following iteration just fine.
The reason the behavior seems unintuitive at first is because we are used to the return
statement interrupting the execution of the whole method. So in this case, we expect the main
method execution as a whole to be halted.
However, what needs to be understood is that a lambda expression, such as:
str -> {
if (str.equals("b")) return;
System.out.println(str);
}
... really needs to be considered as its own distinct "method", completely separate from the main
method, despite it being conveniently located within it. So really, the return
statement only halts the execution of the lambda expression.
The second thing that needs to be understood is that:
stringList.stream().forEach()
... is really just a normal loop under the covers that executes the lambda expression for every iteration.
With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):
public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");
for(String s : stringList) {
lambdaExpressionEquivalent(s);
}
}
private static void lambdaExpressionEquivalent(String str) {
if (str.equals("b")) {
return;
}
System.out.println(str);
}
With this "less magic" code equivalent, the scope of the return
statement becomes more apparent.
What operating system is this? The answer might depend on the OS involved. However, it looks like you need to find this BLAS library and install it. It doesn't seem to be in PIP (you'll have to do it by hand thus), but if you install it, it ought let you progress your SciPy install.
With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
class SampleController extends Controller
{
public function indexAction(Request $request) {
var_dump($request->request->all());
}
}
As others have noted, you can use SQL Profiler, but you can also leverage it's functionality through sp_trace_* system stored procedures. For example, this SQL snippet will (on 2000 at least; I think it's the same for SQL 2008 but you'll have to double-check) catch RPC:Completed
and SQL:BatchCompleted
events for all queries that take over 10 seconds to run, and save the output to a tracefile that you can open up in SQL profiler at a later date:
DECLARE @TraceID INT
DECLARE @ON BIT
DECLARE @RetVal INT
SET @ON = 1
exec @RetVal = sp_trace_create @TraceID OUTPUT, 2, N'Y:\TraceFile.trc'
print 'This trace is Trace ID = ' + CAST(@TraceID AS NVARCHAR)
print 'Return value = ' + CAST(@RetVal AS NVARCHAR)
-- 10 = RPC:Completed
exec sp_trace_setevent @TraceID, 10, 1, @ON -- Textdata
exec sp_trace_setevent @TraceID, 10, 3, @ON -- DatabaseID
exec sp_trace_setevent @TraceID, 10, 12, @ON -- SPID
exec sp_trace_setevent @TraceID, 10, 13, @ON -- Duration
exec sp_trace_setevent @TraceID, 10, 14, @ON -- StartTime
exec sp_trace_setevent @TraceID, 10, 15, @ON -- EndTime
-- 12 = SQL:BatchCompleted
exec sp_trace_setevent @TraceID, 12, 1, @ON -- Textdata
exec sp_trace_setevent @TraceID, 12, 3, @ON -- DatabaseID
exec sp_trace_setevent @TraceID, 12, 12, @ON -- SPID
exec sp_trace_setevent @TraceID, 12, 13, @ON -- Duration
exec sp_trace_setevent @TraceID, 12, 14, @ON -- StartTime
exec sp_trace_setevent @TraceID, 12, 15, @ON -- EndTime
-- Filter for duration [column 13] greater than [operation 2] 10 seconds (= 10,000ms)
declare @duration bigint
set @duration = 10000
exec sp_trace_setfilter @TraceID, 13, 0, 2, @duration
You can find the ID for each trace-event, columns, etc from Books Online; just search for the sp_trace_create, sp_trace_setevent and sp_trace_setfiler sprocs. You can then control the trace as follows:
exec sp_trace_setstatus 15, 0 -- Stop the trace
exec sp_trace_setstatus 15, 1 -- Start the trace
exec sp_trace_setstatus 15, 2 -- Close the trace file and delete the trace settings
...where '15' is the trace ID (as reported by sp_trace_create, which the first script kicks out, above).
You can check to see what traces are running with:
select * from ::fn_trace_getinfo(default)
The only thing I will say in caution -- I do not know how much load this will put on your system; it will add some, but how big that "some" is probably depends how busy your server is.
Try removing android:gradientRadius="90". Here is one that works for me:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<gradient
android:startColor="@color/purple"
android:endColor="@color/pink"
android:angle="270" />
</shape>
db2look -d <db_name> -e -z <schema_name> -t <table_name> -i <user_name> -w <password> > <file_name>.sql
For more information, please refer below:
db2look [-h]
-d: Database Name: This must be specified
-e: Extract DDL file needed to duplicate database
-xs: Export XSR objects and generate a script containing DDL statements
-xdir: Path name: the directory in which XSR objects will be placed
-u: Creator ID: If -u and -a are both not specified then $USER will be used
-z: Schema name: If -z and -a are both specified then -z will be ignored
-t: Generate statistics for the specified tables
-tw: Generate DDLs for tables whose names match the pattern criteria (wildcard characters) of the table name
-ap: Generate AUDIT USING Statements
-wlm: Generate WLM specific DDL Statements
-mod: Generate DDL statements for Module
-cor: Generate DDL with CREATE OR REPLACE clause
-wrap: Generates obfuscated versions of DDL statements
-h: More detailed help message
-o: Redirects the output to the given file name
-a: Generate statistics for all creators
-m: Run the db2look utility in mimic mode
-c: Do not generate COMMIT statements for mimic
-r: Do not generate RUNSTATS statements for mimic
-l: Generate Database Layout: Database partition groups, Bufferpools and Tablespaces
-x: Generate Authorization statements DDL excluding the original definer of the object
-xd: Generate Authorization statements DDL including the original definer of the object
-f: Extract configuration parameters and environment variables
-td: Specifies x to be statement delimiter (default is semicolon(;))
-i: User ID to log on to the server where the database resides
-w: Password to log on to the server where the database resides
private String getCurrentStackTraceString() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
return Arrays.stream(stackTrace).map(StackTraceElement::toString)
.collect(Collectors.joining("\n"));
}
Please refer to the official Advanced Content Filter guide and plugin integration tutorial.
You'll find much more than this about this powerful feature. Also see config.extraAllowedContent that seems suitable for your needs.
You can style it by the following way:
echo "<p style='color:red;'>" . $ip['cityName'] . "</p>";
echo "<p style='color:red;'>" . $ip['countryName'] . "</p>";
try this solution
date( 'W', strtotime( "2017-01-01 + 1 day" ) );
condition1 = False
condition2 = False
val = -1
#here is the function getstuff is not defined, i hope you define it before
#calling it into while loop code
while condition1 and condition2 is False and val == -1:
#as you can see above , we can write that in a simplified syntax.
val,something1,something2 = getstuff()
if something1 == 10:
condition1 = True
elif something2 == 20:
# here you don't have to use "if" over and over, if have to then write "elif" instead
condition2 = True
# ihope it can be helpfull
Make sure the value in the child's project/parent/version node matches its parent's project/version value
From the Java API specification:
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.
Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
In my case, I was getting value of <input type="text">
with JQuery and I did it like this:
var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
"firstName": inputFirstName[0] , "email": inputEmail[0].value}
And I was constantly getting this exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: java.io.PushbackInputStream@39cb6c98; line: 1, column: 54] (through reference chain: com.springboot.domain.User["firstName"]).
And I banged my head for like an hour until I realised that I forgot to write .value
after this"firstName": inputFirstName[0]
.
So, the correct solution was:
var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
"firstName": inputFirstName[0].value , "email": inputEmail[0].value}
I came here because I had this problem and I hope I save someone else hours of misery.
Cheers :)
I ran into this issue on my Ubuntu-64 system when attempting to import fst within python as such:
Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun 4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ogi/miniconda3/lib/python3.4/site-packages/pyfst-0.2.3.dev0-py3.4-linux-x86_64.egg/fst/__init__.py", line 1, in <module>
from fst._fst import EPSILON, EPSILON_ID, SymbolTable,\
ImportError: /home/ogi/miniconda3/lib/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/local/lib/libfst.so.1)
I then ran:
ogi@ubuntu:~/miniconda3/lib$ find ~/ -name "libstdc++.so.6"
/home/ogi/miniconda3/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-5-5.2.0-2/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-4.8.5-1/lib/libstdc++.so.6
find: `/home/ogi/.local/share/jupyter/runtime': Permission denied
ogi@ubuntu:~/miniconda3/lib$
mv /home/ogi/miniconda3/lib/libstdc++.so.6 /home/ogi/miniconda3/libstdc++.so.6.old
cp /home/ogi/miniconda3/libgcc-5-5.2.0-2/lib/libstdc++.so.6 /home/ogi/miniconda3/lib/
At which point I was then able to load the library
ogi@ubuntu:~/miniconda3/lib$ python
Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun 4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
>>> exit()
Another method would be to do it sooner. You can create a Boolean variable and set it to true once you load data to the array. so all you really need is a simple if statement of when you load data into the array.
I change the background_fill.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<size android:height="1dp" />
<gradient
android:angle="0"
android:centerColor="#616161"
android:endColor="#616161"
android:startColor="#616161" />
<corners android:radius="0dp" />
<stroke
android:width="1dp"
android:color="#616161" />
<stroke
android:width="1dp"
android:color="#616161" />
</shape>
and the progress_fill.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<size android:height="1dp" />
<gradient
android:angle="0"
android:centerColor="#fafafa"
android:endColor="#fafafa"
android:startColor="#fafafa" />
<corners android:radius="1dp" />
<stroke
android:width="1dp"
android:color="#cccccc" />
<stroke
android:width="1dp"
android:color="#cccccc" />
</shape>
to make the background & progress 1dp
height.
class
is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class
itself.
e.g.
class ANewType
{
// ... details
};
This defines a new type called ANewType
which is a class type.
You can then use this in function declarations:
void function(ANewType object);
You can then pass objects of type ANewType
into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.
If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.
void function(ANewType& object); // object passed by reference
This syntax means that any use of object
in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.
[* The class
keyword is also used in template definitions, but that's a different subject.]
You could use some third party open-source libraries to generated strong typed verified (X)HTML, such as CityLizard Framework or Sharp DOM.
Update For example
html
[head
[title["Title of the page"]]
[meta_(
content: "text/html;charset=UTF-8",
http_equiv: "Content-Type")
]
[link_(href: "css/style.css", rel: "stylesheet", type: "text/css")]
[script_(type: "text/javascript", src: "/JavaScript/jquery-1.4.2.min.js")]
]
[body
[div
[h1["Test Form to Test"]]
[form_(action: "post", id: "Form1")
[div
[label["Parameter"]]
[input_(type: "text", value: "Enter value")]
[input_(type: "submit", value: "Submit!")]
]
]
[div
[p["Textual description of the footer"]]
[a_(href: "http://google.com/")
[span["You can find us here"]]
]
[div["Another nested container"]]
]
]
];
The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[]
with an index read from stream. Try vector::at()
instead of vector::operator[]
. This won't solve your problem, but will show which assignment to the vector causes error.
Do one thing, get the commit's SHA no. such as 87c9808 and then,
error: failed to push some refs to 'https://github.com/YOURREPOSITORY/AndroidExperiments.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again.**
git push --force origin master
You can use "system.properties.os", for example:
public class GetOs {
public static void main (String[] args) {
String s =
"name: " + System.getProperty ("os.name");
s += ", version: " + System.getProperty ("os.version");
s += ", arch: " + System.getProperty ("os.arch");
System.out.println ("OS=" + s);
}
}
// EXAMPLE OUTPUT: OS=name: Windows 7, version: 6.1, arch: amd64
Here are more details:
what worked for on Ubuntu is granting all privileges to the user:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'yourpassword' WITH GRANT OPTION;
and setting the bind address in /etc/mysql/mysql.conf.d/mysqld.cnf
:
bind-address = 0.0.0.0
then restarting the mysql daemon:
service mysql restart
We can also define it using global
in setupTests
// setupTests.js
global.open = jest.fn()
And call it using global
in the actual test:
// yourtest.test.js
it('correct url is called', () => {
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
with UnionTable as
(
SELECT a.id, a.time FROM dbo.a
UNION
SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id
The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.
For example:
var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}
//that will not work.
delete myObj.test.keyToDelete
instead you would need to use:
delete myObj.test[keyToDelete];
Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.
If none of the above answers worked for you, just close your IntelliJ IDE and remove the IntelliJ IDE file and folder from the root of your project:
rm -rf .idea *.iml
Then open the project with IntelliJ. It must work now.
I faced the same issue. Tried adding the US_export_policy.jar
and local_policy.jar
in the java security folder first but the issue persisted. Then added the below in java_opts
inside tomcat setenv.sh
file and it worked.
-Djdk.tls.ephemeralDHKeySize=2048
Please check this link for further info
The problem is that .form-control
class renders like a DIV
element which according to the normal-flow-of-the-page
renders on a new line.
One way of fixing issues like this is to use display:inline
property. So, create a custom CSS
class with display:inline
and attach it to your component with a .form-control
class. You have to have a width
for your component as well.
There are other ways of handling this issue (like arranging your form-control
components inside any of the .col
classes), but the easiest way is to just make your .form-control
an inline
element (the way a span
would render)
UDP does have less overhead and is good for doing things like streaming real time data like audio or video, or in any case where it is ok if data is lost.
You could set your property in the model's constructor
public YourModel()
{
As = true;
}
There is no error in the code, but the error is thrown due to the following:
- Please check whether you have given Read-write permission to MS-Access database file.
- The Database file where it is stored (say in Folder1) is read-only..?
suppose you are stored the database (MS-Access file) in read only folder, while running your application the connection is not force-fully opened. Hence change the file permission / its containing folder permission like in C:\Program files
all most all c drive files been set read-only so changing this permission solves this Problem.
File sutest
#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"
run it: `./sutest' gives me
uid is 500
user is stephenp
username is stephenp
but using sudo: sudo ./sutest
gives
uid is 0
user is root
username is stephenp
So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:
#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.
Just sudo to invoke your script in the first place, it will prompt for the password once.
I originally wrote this answer on Linux, which does have some differences with OS X
OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER
when you're running sudo, which can be used in place of USERNAME
above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.
Changing the original script for OS X, it becomes...
#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.
A first stab at making it cross-platform could be...
#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
# else set it to USERNAME if THAT is set,
# else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}
sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.
If you use Oracle 10 or higher you can use regexp functions as codaddict suggested. In earlier versions translate
function will help you:
select * from tablename where translate(x, '.1234567890', '.') is null;
More info about Oracle translate function can be found here or in official documentation "SQL Reference"
UPD: If you have signs or spaces in your numbers you can add "+-
" characters to the second parameter of translate
function.
A double primitive in Java can never be null. It will be initialized to 0.0 if no value has been given for it (except when declaring a local double variable and not assigning a value, but this will produce a compile-time error).
More info on default primitive values here.
I can spot a few different problems with this. However, in the interest of time, try this chunk of code instead:
<?php require 'db.php'; ?> <?php if (isset($_POST['search'])) { $limit = $_POST['limit']; $country = $_POST['country']; $state = $_POST['state']; $city = $_POST['city']; $data = mysqli_query( $link, "SELECT * FROM proxies WHERE country = '{$country}' AND state = '{$state}' AND city = '{$city}' LIMIT {$limit}" ); while ($assoc = mysqli_fetch_assoc($data)) { $proxy = $assoc['proxy']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Sock5Proxies</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <link href="./style.css" rel="stylesheet" type="text/css" /> <link href="./buttons.css" rel="stylesheet" type="text/css" /> </head> <body> <center> <h1>Sock5Proxies</h1> </center> <div id="wrapper"> <div id="header"> <ul id="nav"> <li class="active"><a href="index.html"><span></span>Home</a></li> <li><a href="leads.html"><span></span>Leads</a></li> <li><a href="payout.php"><span></span>Pay out</a></li> <li><a href="contact.html"><span></span>Contact</a></li> <li><a href="logout.php"><span></span>Logout</a></li> </ul> </div> <div id="content"> <div id="center"> <table cellpadding="0" cellspacing="0" style="width:690px"> <thead> <tr> <th width="75" class="first">Proxy</th> <th width="50" class="last">Status</th> </tr> </thead> <tbody> <tr class="rowB"> <td class="first"> <?php echo $proxy ?> </td> <td class="last">Check</td> </tr> </tbody> </table> </div> </div> <div id="footer"></div> <span id="about">Version 1.0</span> </div> </body> </html> <?php } } ?> <html> <form action="" method="POST"> <input type="text" name="limit" placeholder="10" /><br> <input type="text" name="country" placeholder="Country" /><br> <input type="text" name="state" placeholder="State" /><br> <input type="text" name="city" placeholder="City" /><br> <input type="submit" name="search" value="Search" /><br> </form> </html>
Here is a working example (you'll have to trust me that there's a submit() method on the controller - it prints an Object, like {user: 'abc'} if 'abc' is entered in the input field):
<form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)">
<input type="text" name="user" ngModel required>
<button type="submit" [disabled]="loginForm.invalid">
Submit
</button>
</form>
As you can see:
Also, this is when you're NOT using the new FormBuilder, which I recommend. Things are very different when using FormBuilder.
Maybe too late :))) but there is another solution that you can find the key and value of structs and iterate over that
package main
import (
"fmt"
"reflect"
)
type person struct {
firsName string
lastName string
iceCream []string
}
func main() {
u := struct {
myMap map[int]int
mySlice []string
myPerson person
}{
myMap: map[int]int{1: 10, 2: 20},
mySlice: []string{"red", "green"},
myPerson: person{
firsName: "Esmaeil",
lastName: "Abedi",
iceCream: []string{"Vanilla", "chocolate"},
},
}
v := reflect.ValueOf(u)
for i := 0; i < v.NumField(); i++ {
fmt.Println(v.Type().Field(i).Name)
fmt.Println("\t", v.Field(i))
}
}
and there is no *panic* for v.Field(i)
It could just be because ACID is one set of properties that substances show( in Chemistry) and BASE is a complement set of them.So it could be just to show the contrast between the two that the acronym was made up and then 'Basically Available Soft State Eventual Consistency' was decided as it's full-form.
Don't.
That is, for most cases you are better off generating the whole string in one go rather then appending to an existing string.
For example, don't do: obj1.name + ":" + str(obj1.count)
Instead: use "%s:%d" % (obj1.name, obj1.count)
That will be easier to read and more efficient.
Here is an example contrasting how Python (dynamically typed) and Go (statically typed) handle a type error:
def silly(a):
if a > 0:
print 'Hi'
else:
print 5 + '3'
Python does type checking at run time, and therefore:
silly(2)
Runs perfectly fine, and produces the expected output Hi
. Error is only raised if the problematic line is hit:
silly(-1)
Produces
TypeError: unsupported operand type(s) for +: 'int' and 'str'
because the relevant line was actually executed.
Go on the other hand does type-checking at compile time:
package main
import ("fmt"
)
func silly(a int) {
if (a > 0) {
fmt.Println("Hi")
} else {
fmt.Println("3" + 5)
}
}
func main() {
silly(2)
}
The above will not compile, with the following error:
invalid operation: "3" + 5 (mismatched types string and int)
I had this problem also. The issue was because I was running an old version of PHP (5.6) and once I upgraded to PHP 7.4 the errors went away.
This was on Amazon Linux 2 for me and the command to upgrade was:
amazon-linux-extras install php7.4
Other flavors of *nix might have it in their repositories otherwise if you're on a flavor of Linux then Remi might have it for you here: https://rpms.remirepo.net/
If you want to add a flag to every link, e.g. -fsanitize=address
then I would not recommend using CMAKE_*_LINKER_FLAGS
. Even with them all set it still doesn't use the flag when linking a framework on OSX, and maybe in other situations. Instead use link_libraries()
:
add_compile_options("-fsanitize=address")
link_libraries("-fsanitize=address")
This works for everything.
First you need to separate your class from the further extensions ex you cannot extend AddAddressComponent.defaultProps
within the class
instead move it outside.
I will also recommend you to read about the Constructor and React's lifecycle: see Component Specs and Lifecycle
Here is what you want:
import PropTypes from 'prop-types';
class AddAddressComponent extends React.Component {
render() {
let { provinceList, cityList } = this.props;
if(cityList === undefined || provinceList === undefined){
console.log('undefined props');
}
}
}
AddAddressComponent.contextTypes = {
router: PropTypes.object.isRequired
};
AddAddressComponent.defaultProps = {
cityList: [],
provinceList: [],
};
AddAddressComponent.propTypes = {
userInfo: PropTypes.object,
cityList: PropTypes.array.isRequired,
provinceList: PropTypes.array.isRequired,
}
export default AddAddressComponent;
Yes there is such a built-in function: os.path.join
.
>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'
If you are developing to a modern browser. https://caniuse.com/#search=fit%20content
You can use:
width: fit-content;
You can use gcc, in Terminal, by doing gcc -c tat.c -o tst
however, it doesn't come installed by default. You have to install the XCode package from tour install disc or download from http://developer.apple.com
Here is where to download past developer tools from, which includes XCode 3.1, 3.0, 2.5 ...
http://connect.apple.com/cgi-bin/WebObjects/MemberSite.woa/wo/5.1.17.2.1.3.3.1.0.1.1.0.3.3.3.3.1
Perhaps you try this solution:
#define QUANTIDISCHI 6
#define QUDI(x) #x
#define QUdi(x) QUDI(x)
. . .
. . .
unsigned char TheNumber[] = "QUANTIDISCHI = " QUdi(QUANTIDISCHI) "\n";
This works great. Just paste this before plt.show()
:
plt.gca().axes.get_yaxis().set_visible(False)
Boom.
Since you are working in currency why not simply do this:
Console.Writeline("Earnings this week: {0:c}", answer);
This will format answer as currency, so on my machine (UK) it will come out as:
Earnings this week: £209.00
this code will return duplicate value in same array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
if(array_count_values($arr)[$item] > 1){
echo "Found Matched value : ".$item." <br />";
}
}
The system stored procedure sp_help
will give you the information. Execute the following statement:
execute sp_help table_name
Suppose a new build of an app is ready from the development phase.
We check if we are able to open the app without a crash. We login to the app. We check if the user is redirected to the proper URL and that the environment is stable. If the main aim of the app is to provide a "purchase" functionality to the user, check if the user's ID is redirected to the buying page.
After the smoke testing we confirm the build is in a testable form and is ready to go through sanity testing.
In this phase, we check the basic functionalities, like
jQuery.noConflict
will reset the $
variable so it's no longer an alias of jQuery
. Aside from just calling it once, there's not much else you really need to do. Though, you can create your own alias with the return value, if you'd like:
var jq = jQuery.noConflict();
And, generally, you want to do this right after including jQuery and any plugins:
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/jquery-plugin.js"></script>
<script type="text/javascript">
jQuery.noConflict();
// Code that uses other library's $ can follow here.
</script>
<script type="text/javascript" src="/path/to/prototype.js"></script>
You can also go one step further and free up jQuery
with noConflict(true)
. Though, if you take this route, you'll definitely want an alias as neither $
nor jQuery
will probably be what you want:
var jq = jQuery.noConflict(true);
I think this last option is mostly used for mixing versions of jQuery, particularly for out-dated plugins when you want to update jQuery itself:
<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script type="text/javascript" src="jquery-older-plugin.js"></script>
<script type="text/javascript">
var jq144 = jQuery.noConflict(true);
</script>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript" src="jquery-newer-plugin.js"></script>
Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need
now.MONTH now.HOUR
etc.
For Spring Tool Suite
I do:
File -> Open projects from File System
You're trying to change the value in the list, but all you're doing is changing the reference of x. Doing the following only changes x, not anything in the collection:
x = Integer.valueOf(9);
Additionally, Integer
is immutable, meaning you can't change the value inside the Integer object (which would require a different method to do anyway). This means you need to replace the whole object. There is no way to do this with an Iterator
(without adding your own layer of boxing). Do the following instead:
a.set(0, 9);
You can get the current year using DATEPART
function, from the current date obtained using getUTCDate()
SELECT
'01/01/' + CONVERT(VARCHAR(4), DATEPART(yy, getUTCDate())),
'31/12/' + CONVERT(VARCHAR(4), DATEPART(yy, getUTCDate()))
I had this problem, it is for foreign-key
Click on the Relation View
(like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB)
column, just put the select to nothing! Means no foreign-key
Hope that works!
you can swipe the key and the value. For example
String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
int[] v = {341, 273, 278, 329, 445};
TreeMap<Integer,String>a=new TreeMap();
for (int i = 0; i < k.length; i++)
a.put(v[i],k[i]);
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
a.remove(a.firstEntry().getKey());
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
Eclipse will by default try to launch with the default "java.exe
" (the first one referenced by your PATH
)
Three things to remember:
PATH
to update.June 2012, jmbertucci comments:
I'm running Windows 7 64-bit and I had the 32-bit JRE installed. I downloaded Eclipse 64-bit which looks for a 64-bit JRE. Because I didn't have the 64-bit JRE it threw the error, which makes sense.
I went to the Java manual install page (which was not as directly accessible as you'd like) and installed the 64-bit version. See "Java Downloads for All Operating Systems". That was all I needed.
April 2016: Steve Mayne adds in the comments:
I had to edit the
eclipse.ini
file to reference the correct Java path - Eclipse doesn't use the environmentPATH
at all when there is a value ineclipse.ini
.
My suggestion is to run
openssl enc -aes-256-cbc -in plain.txt -out encrypted.bin
under debugger and see what exactly what it is doing. openssl.c is the only real tutorial/getting started/reference guide OpenSSL has. All other documentation is just an API reference.
U1: My guess is that you are not setting some other required options, like mode of operation (padding).
U2: this is probably a duplicate of this question: AES CTR 256 Encryption Mode of operation on OpenSSL and answers there will likely help.
import pandas
df is the data frame you create.
Use the command:
df1=df[['Country','Place']][df.Value == df['Value'].max()]
This will display the country and place whose value is maximum.
Perhaps you're not disposing of the previous connection/ result classes from the previous run which means their still hanging around in memory.
In my case below code
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="10dp" android:bottom="-10dp"
>
<shape android:shape="rectangle">
<solid android:color="@color/maincolor" />
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomLeftRadius="0dp"
android:bottomRightRadius="0dp"
/>
</shape>
</item>
</layer-list>
Following code will enumerate all values for a certain Registry key, will sort them and will return value name : value pairs separated by colon (:):
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework';
Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
$command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_);
$value = Invoke-Expression -Command $command;
$_ + ' : ' + $value; };
Like this:
DbgJITDebugLaunchSetting : 16
DbgManagedDebugger : "C:\Windows\system32\vsjitdebugger.exe" PID %d APPDOM %d EXTEXT "%s" EVTHDL %d
InstallRoot : C:\Windows\Microsoft.NET\Framework\
With plt.scatter
, I can only think of one: to use a proxy artist:
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
x=ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
ccm=x.get_cmap()
circles=[Line2D(range(1), range(1), color='w', marker='o', markersize=10, markerfacecolor=item) for item in ccm((array([4,6,8])-4.0)/4)]
leg = plt.legend(circles, ['4','6','8'], loc = "center left", bbox_to_anchor = (1, 0.5), numpoints = 1)
And the result is:
You can use process.stdout.write()
:
process.stdout.write("hello: ");
See the docs for details.
You can't expect ObjectInputStream
to automagically convert text into objects. The hexadecimal 54657374
is "Test"
as text. You must be sending it directly as bytes.
You can control client cache with HTTP headers. This works in any web framework.
You can set the directives these headers to have fine grained control over how and when to enable|disable cache:
Cache-Control
Surrogate-Control
Expires
ETag
(very good one)Pragma
(if you want to support old browsers)Good caching is good, but very complex, in all computer systems. Take a look at https://helmetjs.github.io/docs/nocache/#the-headers for more information.
A more generalised example - if looking for parts of a word OR specific words in a string:
df = pd.DataFrame([('cat andhat', 1000.0), ('hat', 2000000.0), ('the small dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])
Specific parts of sentence or word:
searchfor = '.*cat.*hat.*|.*the.*dog.*'
Creat column showing the affected rows (can always filter out as necessary)
df["TrueFalse"]=df['col1'].str.contains(searchfor, regex=True)
col1 col2 TrueFalse
0 cat andhat 1000.0 True
1 hat 2000000.0 False
2 the small dog 1000.0 True
3 fog 330000.0 False
4 pet 3 30000.0 False
try to add #include "stdafx.h"
before #include "iostream"
I tried everything but I found a solution which really works. It creates independed solution with a new namespace name an so on.
In main form find namespace name -> right click -> Refactor -> Rename and select a new name. Check all boxes and click OK.
In the solution explorer rename solution name to a new name.
In the solution explorer rename project name to a new name.
Close VS and rename folder (in total commander for example) in the solution folder to a new name.
In .sln file rename old name to a new name.
Delete old .suo files (hidden)
Start VS and load project
Project -> properties -> change Assembly name and default namespace to a new name.
I had this same problem with this part of my code:
const newComment = {
dishId: dishId,
rating: rating,
author: author,
comment: comment
};
newComment.date = new Date().toISOString();
Same error, const is a reserved word.
The thing is, I made the .eslintrc.js from the link you gave in the update and still got the same error. Also, I get an parsing error in the .eslintrc.js
: Unexpected token ':'
.
Right in this part:
"env": {
"browser": true,
"node": true,
"es6": true
},
...
For others who ran into this issue in a project that is not using a sonar-runners.property file, you may find (as I did) that you need to tweak your pom.xml file, adding a sonar.host.url property.
For example, I needed to add the following line under the 'properties' element:
<sonar.host.url>https://sonar.my-internal-company-domain.net</sonar.host.url>
Where the url points to our internal sonar deployment.
This one works fine for me :
theme.applyStyle(R.style.AppTheme, true)
Usage:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//The call goes right after super.onCreate() and before setContentView()
theme.applyStyle(R.style.AppTheme, true)
setContentView(layoutId)
onViewCreated(savedInstanceState)
}
>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM
Try replacing %I
with %H
.
You have to access lists a little differently than arrays in Java. See the javadocs for the List
interface for more information.
playersList.get(0)
However if you want to find the smallest element in playersList
, you shouldn't sort it and then get the first element. This runs very slowly compared to just searching once through the list to find the smallest element.
For example:
int smallestIndex = 0;
for (int i = 1; i < playersList.size(); i++) {
if (playersList.get(i) < playersList.get(smallestIndex))
smallestIndex = i;
}
playersList.get(smallestIndex);
The above code will find the smallest element in O(n)
instead of O(n log n)
time.
Maybe hashset which do not store duplicate elements and silently ignore requests to add duplicates.
static void Main()
{
string textWithDuplicates = "aaabbcccggg";
Console.WriteLine(textWithDuplicates.Count());
var letters = new HashSet<char>(textWithDuplicates);
Console.WriteLine(letters.Count());
foreach (char c in letters) Console.Write(c);
Console.WriteLine("");
int[] array = new int[] { 12, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 };
Console.WriteLine(array.Count());
var distinctArray = new HashSet<int>(array);
Console.WriteLine(distinctArray.Count());
foreach (int i in distinctArray) Console.Write(i + ",");
}
Your first code will work by doing this
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss"); //Remove myDateTime.Date part
In Pro Angular-6 book is detailed as below;
invalid: This property returns true if the element’s contents are invalid and false otherwise.
pristine: This property returns true if the element’s contents have not been changed.
What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.
A simple representation written by 'Robert Sedgwick' and 'Kevin Wayne' is available at http://algs4.cs.princeton.edu/41graph/Graph.java.html
Explanation copied from the above page.
The Graph class represents an undirected graph of vertices named 0 through V - 1.
It supports the following two primary operations: add an edge to the graph, iterate over all of the vertices adjacent to a vertex. It also provides methods for returning the number of vertices V and the number of edges E. Parallel edges and self-loops are permitted. By convention, a self-loop v-v appears in the adjacency list of v twice and contributes two to the degree of v.
This implementation uses an adjacency-lists representation, which is a vertex-indexed array of Bag objects. All operations take constant time (in the worst case) except iterating over the vertices adjacent to a given vertex, which takes time proportional to the number of such vertices.
This Solution is of O(n^2) complexity. O(1) is the space complexity.
public class longestPalindromeInAString {
public static void main(String[] args) {
String a = "xyMADAMpRACECARwl";
String res = "";
//String longest = a.substring(0,1);
//System.out.println("longest => " +longest);
for (int i = 0; i < a.length(); i++) {
String temp = helper(a,i,i);//even palindrome
if(temp.length() > res.length()) {res = temp ;}
temp = helper(a,i,i+1);// odd length palindrome
if(temp.length() > res.length()) { res = temp ;}
}//for
System.out.println(res);
System.out.println("length of " + res + " is " + res.length());
}
private static String helper(String a, int left, int right) {
while(left>= 0 && right <= a.length() -1 && a.charAt(left) == a.charAt(right)) {
left-- ;right++ ;
}
String curr = a.substring(left + 1 , right);
System.out.println("curr =>" +curr);
return curr ;
}
}
You are declaring a local variable, not a class variable. To set an instance variable (attribute), use
class Example(object):
def the_example(self):
self.itsProblem = "problem" # <-- remember the 'self.'
theExample = Example()
theExample.the_example()
print(theExample.itsProblem)
To set a class variable (a.k.a. static member), use
class Example(object):
def the_example(self):
Example.itsProblem = "problem"
# or, type(self).itsProblem = "problem"
# depending what you want to do when the class is derived.
Use this in your my.ini
under
[mysqldump]
user=root
password=anything
How do you run a program all by itself without an operating system running?
You place your binary code to a place where processor looks for after rebooting (e.g. address 0 on ARM).
Can you create assembly programs that the computer can load and run at startup ( e.g. boot the computer from a flash drive and it runs the program that is on the drive)?
General answer to the question: it can be done. It's often referred to as "bare metal programming". To read from flash drive, you want to know what's USB, and you want to have some driver to work with this USB. The program on this drive would also have to be in some particular format, on some particular filesystem... This is something that boot loaders usually do, but your program could include its own bootloader so it's self-contained, if the firmware will only load a small block of code.
Many ARM boards let you do some of those things. Some have boot loaders to help you with basic setup.
Here you may find a great tutorial on how to do a basic operating system on a Raspberry Pi.
Edit: This article, and the whole wiki.osdev.org will anwer most of your questions http://wiki.osdev.org/Introduction
Also, if you don't want to experiment directly on hardware, you can run it as a virtual machine using hypervisors like qemu. See how to run "hello world" directly on virtualized ARM hardware here.
this is a sample of one of my app how i handle
//searching for the Edit Text in the view
final EditText myEditText =(EditText)view.findViewById(R.id.myEditText);
myEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
(keyCode == KeyEvent.KEYCODE_ENTER)) {
//do something
//true because you handle the event
return true;
}
return false;
}
});
I'm using GDB7.1.1, as --help
shows:
gdb [options] --args executable-file [inferior-arguments ...]
IMHO, the order is a bit unintuitive at first.
try with this code
String ids[] = {"182","160","183"};
StringBuilder builder = new StringBuilder();
for( int i = 0 ; i < ids.length; i++ ) {
builder.append("?,");
}
String sql = "delete from emp where id in ("+builder.deleteCharAt( builder.length() -1 ).toString()+")";
PreparedStatement pstmt = connection.prepareStatement(sql);
for (int i = 1; i <= ids.length; i++) {
pstmt.setInt(i, Integer.parseInt(ids[i-1]));
}
int count = pstmt.executeUpdate();
I too got the same problem. When i changed the Eclipse from EE to Eclipse Classic it worked fine. in Win professional 64Bit. Have a try it may work for you too..
Field[] fields = YourClassName.class.getFields();
returns an array of all public variables of the class.
getFields()
return the fields in the whole class-heirarcy. If you want to have the fields defined only in the class in question, and not its superclasses, use getDeclaredFields()
, and filter the public
ones with the following Modifier
approach:
Modifier.isPublic(field.getModifiers());
The YourClassName.class
literal actually represents an object of type java.lang.Class
. Check its docs for more interesting reflection methods.
The Field
class above is java.lang.reflect.Field
. You may take a look at the whole java.lang.reflect
package.
textAlign
property only works when there is a more space left for the Text
's content. Below are 2 examples which shows when textAlign has impact and when not.
For instance, in this example, it won't have any impact because there is no extra space for the content of the Text
.
Text(
"Hello",
textAlign: TextAlign.end, // no impact
),
If you wrap it in a Container
and provide extra width
such that it has more extra space.
Container(
width: 200,
color: Colors.orange,
child: Text(
"Hello",
textAlign: TextAlign.end, // has impact
),
)
Why don't you use a separate CSS file to maintain the height and the width of the image you want to display? In that way, you can provide the width and height necessarily.
eg:
image {
width: 64px;
height: 64px;
}
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
new Double(object.toString());
But it seems weird to me that you're going from an Object to a Double. You should have a better idea what class of object you're starting with before attempting a conversion. You might have a bit of a code quality problem there.
Note that this is a conversion, not casting.
Here is a complete, nicely wrapped solution based on Waterboy's answer and various other sources. It supports logging to both console and log file, allows for different log level settings, provides colorized output and is easily configurable (also available as Gist):
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# -
# Python dual-logging setup (console and log file), -
# supporting different log levels and colorized output -
# -
# Created by Fonic <https://github.com/fonic> -
# Date: 04/05/20 -
# -
# Based on: -
# https://stackoverflow.com/a/13733863/1976617 -
# https://uran198.github.io/en/python/2016/07/12/colorful-python-logging.html -
# https://en.wikipedia.org/wiki/ANSI_escape_code#Colors -
# -
# -------------------------------------------------------------------------------
# Imports
import os
import sys
import logging
# Logging formatter supporting colored output
class LogFormatter(logging.Formatter):
COLOR_CODES = {
logging.CRITICAL: "\033[1;35m", # bright/bold magenta
logging.ERROR: "\033[1;31m", # bright/bold red
logging.WARNING: "\033[1;33m", # bright/bold yellow
logging.INFO: "\033[0;37m", # white / light gray
logging.DEBUG: "\033[1;30m" # bright/bold black / dark gray
}
RESET_CODE = "\033[0m"
def __init__(self, color, *args, **kwargs):
super(LogFormatter, self).__init__(*args, **kwargs)
self.color = color
def format(self, record, *args, **kwargs):
if (self.color == True and record.levelno in self.COLOR_CODES):
record.color_on = self.COLOR_CODES[record.levelno]
record.color_off = self.RESET_CODE
else:
record.color_on = ""
record.color_off = ""
return super(LogFormatter, self).format(record, *args, **kwargs)
# Setup logging
def setup_logging(console_log_output, console_log_level, console_log_color, logfile_file, logfile_log_level, logfile_log_color, log_line_template):
# Create logger
# For simplicity, we use the root logger, i.e. call 'logging.getLogger()'
# without name argument. This way we can simply use module methods for
# for logging throughout the script. An alternative would be exporting
# the logger, i.e. 'global logger; logger = logging.getLogger("<name>")'
logger = logging.getLogger()
# Set global log level to 'debug' (required for handler levels to work)
logger.setLevel(logging.DEBUG)
# Create console handler
console_log_output = console_log_output.lower()
if (console_log_output == "stdout"):
console_log_output = sys.stdout
elif (console_log_output == "stderr"):
console_log_output = sys.stderr
else:
print("Failed to set console output: invalid output: '%s'" % console_log_output)
return False
console_handler = logging.StreamHandler(console_log_output)
# Set console log level
try:
console_handler.setLevel(console_log_level.upper()) # only accepts uppercase level names
except:
print("Failed to set console log level: invalid level: '%s'" % console_log_level)
return False
# Create and set formatter, add console handler to logger
console_formatter = LogFormatter(fmt=log_line_template, color=console_log_color)
console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)
# Create log file handler
try:
logfile_handler = logging.FileHandler(logfile_file)
except Exception as exception:
print("Failed to set up log file: %s" % str(exception))
return False
# Set log file log level
try:
logfile_handler.setLevel(logfile_log_level.upper()) # only accepts uppercase level names
except:
print("Failed to set log file log level: invalid level: '%s'" % logfile_log_level)
return False
# Create and set formatter, add log file handler to logger
logfile_formatter = LogFormatter(fmt=log_line_template, color=logfile_log_color)
logfile_handler.setFormatter(logfile_formatter)
logger.addHandler(logfile_handler)
# Success
return True
# Main function
def main():
# Setup logging
script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
if (not setup_logging(console_log_output="stdout", console_log_level="warning", console_log_color=True,
logfile_file=script_name + ".log", logfile_log_level="debug", logfile_log_color=False,
log_line_template="%(color_on)s[%(created)d] [%(threadName)s] [%(levelname)-8s] %(message)s%(color_off)s")):
print("Failed to setup logging, aborting.")
return 1
# Log some messages
logging.debug("Debug message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical message")
# Call main function
if (__name__ == "__main__"):
sys.exit(main())
NOTE regarding Microsoft Windows 10:
For colors to actually appear on Microsoft Windows 10, ANSI terminal mode has to be enabled first. Here is a function to do just that:
# Enable ANSI terminal on Microsoft Windows 10
# https://stackoverflow.com/a/36760881/1976617
# https://docs.microsoft.com/en-us/windows/console/setconsolemode
def windows_enable_ansi_terminal():
if (sys.platform != "win32"):
return None
try:
import ctypes
kernel32 = ctypes.windll.kernel32
result = kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
if (result == 0): raise Exception
return True
except:
return False
All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:
var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US"));
// (or 1,2345 with your local culture, for instance)
(obviously, you should replace the "en-US" with the culture of your number local culture)
the same way, if you want to do ToString()
d.ToString(new CultureInfo("en-US"));
Try this
DataSet ds = new DataSet("TimeRanges");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("Procedure1", conn);
sqlComm.Parameters.AddWithValue("@Start", StartTime);
sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
I was going through some details related to tuple
and list
, and what I understood is:
Heterogeneous
collection data typeSo for appending new item to a tuple, need to cast it to list
, and do append()
operation on it, then again cast it back to tuple.
But personally what I felt about the Question is, if Tuples are supposed to be finite, fixed length items and if we are using those data types in our application logics then there should not be a scenario to appending new items OR updating an item value in it. So instead of list of tuples it should be list of list itself, Am I right on this?
You can copy the HTML svg tag from the website, then paste the code on a new html file and rename the extension to svg. It worked for me. Hope it helps you.
There is also a smaller one yet called "input-mini".
Small addition to all of above:
Better use map
, when you need to get elements by range, as they are sorted and you can just iterate over them from one boundary to another.
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
Personally none of the above worked for me. What did:
new_str = [str(x) for x in old_obj][0]
You can use http://logging.apache.org/ library and use a database appender to collect all your log info together.
I had this issue with a package that was added to my app (FancyShowCaseView) and caused this problem on pre-lolipop. that package was written in kotlin and my main codes were written in java. so now I'm checking version in pre-lolipop and don't let its class to be executed. temporary solved the problem. check this out if you have similar problem like me
A very short & easy solution i'm using is this:
@ECHO OFF
SET /p NAME=- NAME ?
ECHO "%NAME%"
CALL :TRIM %NAME% NAME
ECHO "%NAME%"
PAUSE
:TRIM
SET %2=%1
GOTO :EOF
Results in:
- NAME ? my_name
" my_name "
"my_name"
Item[] newItemList = new Item[itemList.length+1];
//for loop to go thorough the list one by one
for(int i=0; i< itemList.length;i++){
//value is stored here in the new list from the old one
newItemList[i]=itemList[i];
}
//all the values of the itemLists are stored in a bigger array named newItemList
itemList=newItemList;
You can get the example of css implemented html to pdf conversion using jspdf on following link: JSFiddle Link
This is sample code for the jspdf html to pdf download.
$('#print-btn').click(() => {
var pdf = new jsPDF('p','pt','a4');
pdf.addHTML(document.body,function() {
pdf.save('web.pdf');
});
})
>>> L = range (11)
>>> [ x if x%2 == 1 else None for x in L ]
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
I have a patch that I've used in a Rails 4.1 app to let me continue using the legacy key generator (and hence backwards session compatibility with Rails 3), by allowing the secret_key_base to be blank.
Rails::Application.class_eval do
# the key_generator will then use ActiveSupport::LegacyKeyGenerator.new(config.secret_token)
fail "I'm sorry, Dave, there's no :validate_secret_key_config!" unless instance_method(:validate_secret_key_config!)
def validate_secret_key_config! #:nodoc:
config.secret_token = secrets.secret_token
if config.secret_token.blank?
raise "Missing `secret_token` for '#{Rails.env}' environment, set this value in `config/secrets.yml`"
end
end
end
I've since reformatted the patch are submitted it to Rails as a Pull Request
“--single-branch” switch is your answer, but it only works if you have git version 1.8.X onwards, first check
#git --version
If you already have git version 1.8.X installed then simply use "-b branch and --single branch" to clone a single branch
#git clone -b branch --single-branch git://github/repository.git
By default in Ubuntu 12.04/12.10/13.10 and Debian 7 the default git installation is for version 1.7.x only, where --single-branch is an unknown switch. In that case you need to install newer git first from a non-default ppa as below.
sudo add-apt-repository ppa:pdoes/ppa
sudo apt-get update
sudo apt-get install git
git --version
Once 1.8.X is installed now simply do:
git clone -b branch --single-branch git://github/repository.git
Git will now only download a single branch from the server.
Simply replace
print $image;
with
echo '<img src=".$image." >';
If this is the code you have, then you will get an error because, you are reassigning $row while in the loop, so you would never be able to iterate over the results. Replace
$rows = $rows['Name'];
with
$name = $rows['Name']'
So your code would look like
WHILE ($rows = mysql_fetch_array($query)):
$name = $rows['Name'];
$address = $rows['Address'];
$email = $rows['Email'];
$subject = $rows['Subject'];
$comment = $rows['Comment'];
Also I am assuming that the column names in the table users are Name, Address, Email etc. and not name,address, email. Remember that every variable name/field nameh is case sensitive.
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
The best solution that worked for me is:
public class DeactivatedViewPager extends ViewPager {
public DeactivatedViewPager (Context context) {
super(context);
}
public DeactivatedViewPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean canScrollHorizontally(int direction) {
return false;
}
}
After this the scroll will be disabled by touch and then you can still use setCurrentItem
method to change page.
gstreamer can handle webcam input. If I remeber well, there are python bindings for it!
You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode
before it can encode it back to UTF-8. That is what is failing here:
>>> data = u'\u00c3' # Unicode data
>>> data = data.encode('utf8') # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8') # Try to *re*-encode it
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Just write your data directly to the file, there is no need to encode already-encoded data.
If you instead build up unicode
values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open()
instead, which returns a file object that will encode unicode values to UTF-8 for you.
You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).
For your MySQL insert problem, you need to do two things:
Add charset='utf8'
to your MySQLdb.connect()
call.
Use unicode
objects, not str
objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:
artiste = artiste.decode('utf8') # it is already UTF8, decode to unicode
c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
# ...
c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
It may actually work better if you used codecs.open()
to decode the contents automatically instead:
import codecs
sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')
with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
for line in findex:
if u'#artiste' not in line:
continue
artiste=line.split(u'[:::]')[1].strip()
cursor = sql.cursor()
cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
if not cursor.fetchone()[0]:
cursor = sql.cursor()
cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
artists_inserted += 1
You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:
I resolve this error by below step :
1 : first of all write this code in terminal :
...$ which python3
/usr/bin/python3
2 : Then :
"python.pythonPath": "/users/bin/python",
done.
Actually you can use,
BigInteger sum= new BigInteger("12345");
for creating object for BigInteger class.But the problem here is,you cannot give a variable in the double quotes.So we have to use the valueOf() method and we have to store the answer in that sum again.So we will write,
sum= sum.add(BigInteger.valueOf(i));
To use Collections sort(List,Comparator) , you need to create a class that implements Comparator Interface, and code for the compare() in it, through Comparator Interface
You can do something like this:
class StudentComparator implements Comparator
{
public int compare (Student s1 Student s2)
{
// code to compare 2 students
}
}
To sort do this:
Collections.sort(List,new StudentComparator())
https://groups.google.com/group/golang-nuts/msg/71c307e4d73024ce?pli=1
The germane part:
Since integer types use two's complement arithmetic, you can infer the min/max constant values for
int
anduint
. For example,const MaxUint = ^uint(0) const MinUint = 0 const MaxInt = int(MaxUint >> 1) const MinInt = -MaxInt - 1
As per @CarelZA's comment:
uint8 : 0 to 255
uint16 : 0 to 65535
uint32 : 0 to 4294967295
uint64 : 0 to 18446744073709551615
int8 : -128 to 127
int16 : -32768 to 32767
int32 : -2147483648 to 2147483647
int64 : -9223372036854775808 to 9223372036854775807
On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755
you can find the second largest value of column by using the following query
SELECT *
FROM TableName a
WHERE
2 = (SELECT count(DISTINCT(b.ColumnName))
FROM TableName b WHERE
a.ColumnName <= b.ColumnName);
you can find more details on the following link
http://www.abhishekbpatel.com/2012/12/how-to-get-nth-maximum-and-minimun.html
One thing that I have observed is likely the email address you're providing is not a valid email address at the domain. like [email protected]. The email should be existing at Google Domain. I had alot of issues before figuring that out myself... Hope it helps.
As Brad Wilson states in his answer here:
ModelState.IsValid tells you if any model errors have been added to ModelState.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
Try using :-
if (!ModelState.IsValid)
{
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
// Breakpoint, Log or examine the list with Exceptions.
}
If it helps catching you the error. Courtesy this and this
In my case, it was just because there were no source file in the target. All of my library was template with source code in the header. Adding an empty file.cpp solved the problem.
The word “midnight” is tricky to define.
Some think of it as the moment before a new day starts. Trying to represent that in software as tricky as the last moment of the day can always be subdivided as a smaller fraction of a second.
I suggest a better way of thinking about this is to get “first moment of the day”.
This supports the commonly used approach of defining a span of time as ‘Half-Open’, where the beginning is inclusive while the ending is exclusive. So a full day starts with the first moment of the day and runs up to, but not including, the first moment of the following day. A full day would like this (notice the date going from the 3rd to the 4th):
2016-02-03T00:00:00.0-08:00[America/Los_Angeles]/2016-02-04T00:00:00.0-08:00[America/Los_Angeles]
If using the Joda-Time library, call withTimeAtStartOfDay
.
Note how we specify the time zone. If omitted, the JVM’s current default time zone is implicitly applied. Better to be explicit.
DateTime todayStart = DateTime.now( DateTimeZone.forID( "America/Montreal" ) ).withTimeAtStartOfDay() ;
If using Java 8 or later, better to use the java.time package built into Java. See sibling Answer by Jens Hoffman.
Unfortunately most of the other answers do not provide information specific to Windows 10.
Windows 10 has versions of its own: 1507, 1511, 1607, 1703, etc. This is what winver
shows.
Powershell:
(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId
Command prompt (CMD.EXE):
Reg Query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ReleaseId
See also related question on superuser.
As for other Windows versions use systeminfo
. Powershell wrapper:
PS C:\> systeminfo /fo csv | ConvertFrom-Csv | select OS*, System*, Hotfix* | Format-List
OS Name : Microsoft Windows 7 Enterprise
OS Version : 6.1.7601 Service Pack 1 Build 7601
OS Manufacturer : Microsoft Corporation
OS Configuration : Standalone Workstation
OS Build Type : Multiprocessor Free
System Type : x64-based PC
System Locale : ru;Russian
Hotfix(s) : 274 Hotfix(s) Installed.,[01]: KB2849697,[02]: KB2849697,[03]:...
Windows 10 output for the same command:
OS Name : Microsoft Windows 10 Enterprise N 2016 LTSB
OS Version : 10.0.14393 N/A Build 14393
OS Manufacturer : Microsoft Corporation
OS Configuration : Standalone Workstation
OS Build Type : Multiprocessor Free
System Type : x64-based PC
System Directory : C:\Windows\system32
System Locale : en-us;English (United States)
Hotfix(s) : N/A
Add this, I think it is what you're looking for:
<meta name = "format-detection" content = "telephone=no">
Return 0 on success and non-zero for error. This is the standard used by UNIX and DOS scripting to find out what happened with your program.
In order to add the file to the email as an attachment, it will need to be stored on the server briefly. It's trivial, though, to place it in a tmp location then delete it after you're done with it.
As for emailing, Zend Mail has a very easy to use interface for dealing with email attachments. We run with the whole Zend Framework installed, but I'm pretty sure you could just install the Zend_Mail library without needing any other modules for dependencies.
With Zend_Mail, sending an email with an attachment is as simple as:
$mail = new Zend_Mail();
$mail->setSubject("My Email with Attachment");
$mail->addTo("[email protected]");
$mail->setBodyText("Look at the attachment");
$attachment = $mail->createAttachment(file_get_contents('/path/to/file'));
$mail->send();
If you're looking for a one-file-package to do the whole form/email/attachment thing, I haven't seen one. But the individual components are certainly available and easy to assemble. Trickiest thing of the whole bunch is the email attachment, which the above recommendation makes very simple.
You could make those submit buttons and inside the servlet your are submitting the form to you could test the name of the button which was pressed and render the corresponding jsp page.
<input type="submit" value="Creazione Nuovo Corso" name="CreateCourse" />
<input type="submit" value="Gestione Autorizzazioni" name="AuthorizationManager" />
Inside the TrainerMenu
servlet if request.getParameter("CreateCourse")
is not empty then the first button was clicked and you could render the corresponding jsp.
First of all read in the data, then convert it to byte array:
byte b = Byte.parseByte(str, 16);
and then use String
constructor:
new String(byte[] bytes)
or if the charset is not system default then:
new String(byte[] bytes, String charsetName)
For float
have a look at sys.float_info
:
>>> import sys
>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2
250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsil
on=2.2204460492503131e-16, radix=2, rounds=1)
Specifically, sys.float_info.max
:
>>> sys.float_info.max
1.7976931348623157e+308
If that's not big enough, there's always positive infinity:
>>> infinity = float("inf")
>>> infinity
inf
>>> infinity / 10000
inf
The long
type has unlimited precision, so I think you're only limited by available memory.
I had a similar situation but the following worked best for me..
=Iif(Fields!Sales_Diff.Value)>1,Fields!Sales_Diff.Value),"")
I found a super simple explanation about class << self
, Eigenclass
and different type of methods.
In Ruby, there are three types of methods that can be applied to a class:
Instance methods and class methods are almost similar to their homonymous in other programming languages.
class Foo
def an_instance_method
puts "I am an instance method"
end
def self.a_class_method
puts "I am a class method"
end
end
foo = Foo.new
def foo.a_singleton_method
puts "I am a singletone method"
end
Another way of accessing an Eigenclass
(which includes singleton methods) is with the following syntax (class <<
):
foo = Foo.new
class << foo
def a_singleton_method
puts "I am a singleton method"
end
end
now you can define a singleton method for self
which is the class Foo
itself in this context:
class Foo
class << self
def a_singleton_and_class_method
puts "I am a singleton method for self and a class method for Foo"
end
end
end
There is an object serialization module, with the serialize function you can serialize any object.
To store the transformed string into a variable. Following worked for me -
$SOURCE_NAME
to $TARGET_NAME
TARGET_NAME="`echo $SOURCE_NAME | tr '[:upper:]' '[:lower:]'`"
Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).
This is a basic skeleton for a simple service:
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
Your code would go in the main()
method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop
method
In tensorflow you create graphs and pass values to that graph. Graph does all the hardwork and generate the output based on the configuration that you have made in the graph. Now When you pass values to the graph then first you need to create a tensorflow session.
tf.Session()
Once session is initialized then you are supposed to use that session because all the variables and settings are now part of the session. So, there are two ways to pass external values to the graph so that graph accepts them. One is to call the .run() while you are using the session being executed.
Other way which is basically a shortcut to this is to use .eval(). I said shortcut because the full form of .eval() is
tf.get_default_session().run(values)
You can check that yourself.
At the place of values.eval()
run tf.get_default_session().run(values)
. You must get the same behavior.
what eval is doing is using the default session and then executing run().
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
How about using pyjanitor
It has cool features.
After pip install pyjanitor
import janitor
df_filtered = df.filter_date(your_date_column_name, start_date, end_date)
select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;
Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.
There are 2 different things.
I'd also like to add that if using the three.js editor don't forget to set the background colour to clear as well in the index.html.
background-color:#00000000
You can do this by subsetting the data you pass into your merge:
merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)
Or you can simply delete the column after your current merge :)
try:
if val is None: # The variable
print('It is None')
except NameError:
print ("This variable is not defined")
else:
print ("It is defined and has a value")
A simple example of escaping quotes in the shell:
$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc
It's done by finishing an already-opened one ('
), placing the escaped one (\'
), and then opening another one ('
).
Alternatively:
$ echo 'abc'"'"'abc'
abc'abc
$ echo "abc"'"'"abc"
abc"abc
It's done by finishing already opened one ('
), placing a quote in another quote ("'"
), and then opening another one ('
).
More examples: Escaping single-quotes within single-quoted strings
Check your server's Java version. Happened to me because my Weblogic 10.3.6 was on JDK 1.7.0_75 which was on TLSv1. The rest endpoint I was trying to consume was shutting down anything below TLSv1.2.
By default Weblogic was trying to negotiate the strongest shared protocol. See details here: Issues with setting https.protocols System Property for HTTPS connections.
I added verbose SSL logging to identify the supported TLS. This indicated TLSv1 was being used for the handshake.
-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager -Djava.security.debug=access:stack
I resolved this by pushing the feature out to our JDK8-compatible product, JDK8 defaults to TLSv1.2. For those restricted to JDK7, I also successfully tested a workaround for Java 7 by upgrading to TLSv1.2. I used this answer: How to enable TLS 1.2 in Java 7
Just go to web.config file and add following
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="Path of your Page" />
</files>
</defaultDocument>
</system.webServer>
Correct, closing the shell will stop MongoDB. Try using the --fork
command line arg for the mongod process which makes it run as a daemon instead. I'm no Unix guru, but I'm sure there must be a way to then get it to auto start when the machine boots up.
e.g.
mongod --fork --logpath /var/log/mongodb.log --logappend
Check out the full documentation on Starting and Stopping Mongo.
echo '\x12\x02'
will not be interpreted, and will literally write the string \x12\x02
(and append a newline) to the specified serial port. Instead use
echo -n ^R^B
which you can construct on the command line by typing CtrlVCtrlR and CtrlVCtrlB. Or it is easier to use an editor to type into a script file.
The stty
command should work, unless another program is interfering. A common culprit is gpsd
which looks for GPS devices being plugged in.
Works for IE, Mozzila, Chrome
document.getElementById('YOUR IFRAME').contentDocument.location.reload(true);
If you have access to SRV Records, you can use them to get what you want :)
E.G
A Records
Name: mc1.domain.com
Value: <yourIP>
Name: mc2.domain.com
Value: <yourIP>
SRV Records
Name: _minecraft._tcp.mc1.domain.com
Priority: 5
Weight: 5
Port: 25565
Value: mc1.domain.com
Name: _minecraft._tcp.mc2.domain.com
Priority: 5
Weight: 5
Port: 25566
Value: mc2.domain.com
then in minecraft you can use
mc1.domain.com which will sign you into server 1 using port 25565
and
mc2.domain.com which will sign you into server 2 using port 25566
then on your router you can have it point 25565 and 25566 to the machine with both servers on and Voilà!
Source: This works for me running 2 minecraft servers on the same machine with ports 50500 and 50501
What I looked for is not exactly pointed out in here in SO, I'm writing for the benefit of others who might search for similar. I faced an issue with one file (present in old repo) getting removed in the repo. And when I apply the patch, it fails as it couldn't find the file to be applied. (so my case is git patch fails for file got removed) '#git apply --reject' definitely gave a view but didn't quite get me to the fix. I couldn't use wiggle as it is not available for us in our build servers. In my case, I got through this problem by removing the entry of the 'file which got removed in the repo' from patch file I've tried applying, so I got all other changes applied without an issue (using 3 way merge, avoiding white space errors), And then manually merging content of file removed into where its moved.
They are implemented in very different ways.
hash_map
(unordered_map
in TR1 and Boost; use those instead) use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.
map
is implemented as a balanced binary search tree (usually a red/black tree).
An unordered_map
should give slightly better performance for accessing known elements of the collection, but a map
will have additional useful characteristics (e.g. it is stored in sorted order, which allows traversal from start to finish). unordered_map
will be faster on insert and delete than a map
.
Err.. If you are a git noob are you sure you have git commit
before git push
? I made this mistake the first time!
Login into the database. then run the below query
select * from dba_role_privs where grantee = 'SCHEMA_NAME';
All the role granted to the schema will be listed.
Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.
I believe enum have a .name() in its API, pretty simple to use like this example:
private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }
private enum Security {
low,
high
}
With this you can simply call
yourObject.security()
and it returns high/low as String, in this example
I had a similar issue, I was sending a POST request (using RESTClient plugin for Firefox) with data in the request body and was receiving the same message.
In my case this happened because I was trying to use HTTPS protocol in a local tomcat instance where HTTPS was not configured.
In short, the answer is no. Once you show an alert
, confirm
, or prompt
the script no longer has control until the user returns control by clicking one of the buttons.
To do what you want, you will want to use DOM elements like a div
and show, then hide it after a specified time. If you need to be modal (takes over the page, allowing no further action) you will have to do additional work.
You could of course use one of the many "dialog" libraries out there. One that comes to mind right away is the jQuery UI Dialog widget
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
In my case this error occurred with dot net core and Microsoft.Data.SqlClient
.
The solution was to add ;TrustServerCertificate=true
to the end of the connection string.
Using Java 8 streams
char [] alphabets = Stream.iterate('a' , x -> (char)(x + 1))
.limit(26)
.map(c -> c.toString())
.reduce("", (u , v) -> u + v).toCharArray();
In Laravel 5.x, you can also do like this .
<img class="img-responsive" src="{{URL::to('/')}}/img/stuvi-logo.png" alt=""/>
Solved!
I have had this error for several days. It was driving me crazy because it didnt allow me to use firefox firebug's script debugger. Finally, my error was solved when I removed an empty url in a "background-image: url()" style property.
This has been so much a pain than I really hope somebody can use this advice.
In my case with using Mac, I deleted
/Applications/Python 3.7
.
because I already had Python3.7 by brew install python3
.
But it was a trigger of the message
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
What I did in my situation
/Applications/Python3.6/Install Certificates.command
and /Applications/Python3.6/Update Shell Profile.command
.pip.conf
. See pip install fails.If all login services use PAM, and all login services have session required pam_env.so
in their respective /etc/pam.d/*
configuration files, then all login sessions will have some environment variables set as specified in pam_env
's configuration file.
On most modern Linux distributions, this is all there by default -- just add your desired global environment variables to /etc/security/pam_env.conf
.
This works regardless of the user's shell, and works for graphical logins too (if xdm/kdm/gdm/entrance/… is set up like this).
I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).
I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.
I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.
Hope this helps!
<html>
<head>
<title>Names</title>
</head>
<body style="background-color:powderblue;">
<form method='post' action='alex.php'>
<input type='text' name='name'>
<input type='submit' value='name'>
</form>
Enter Name:
<?php
if($_POST)
{
$Name = $_POST['name'];
$count = 0;
$fh=fopen("alex.txt",'a+') or die("failed to create");
while(!feof($fh))
{
$line = chop(fgets($fh));
if($line==$Name && $line!="")
$count=1;
}
if($count==0 && $Name!="")
{
fwrite($fh, "\r\n$Name");
}
else if($count!=0 && $line!="")
{
echo '<font color="red">'.$Name.', the name you entered is already in the list.</font><br><br>';
}
$count=0;
fseek($fh, 0);
while(!feof($fh))
{
$a = chop(fgets($fh));
echo $a.'<br>';
$count++;
}
if($count<=1)
echo '<br>There are no names in the list<br>';
fclose($fh);
}
?>
</body>
</html>
Presumably this would work:
IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment
For me, only catching the mouseenter event was a bit buggy, and the tooltip was not showing/hiding properly. I had to write this, and it is now working perfectly:
$(document).on('mouseenter','[rel=tooltip]', function(){
$(this).tooltip('show');
});
$(document).on('mouseleave','[rel=tooltip]', function(){
$(this).tooltip('hide');
});
Add a border
to the regular item, the same color
as the background
, so that it cannot be seen. That way the item has a border: 1px
whether it is being hovered or not.
I had the same issue and I used this function to compress individual pages which results in the file size being compressed by upto 1/3 of the original size.
for (int i = 1; i <= theDoc.PageCount; i++)
{
theDoc.PageNumber = i;
theDoc.Flatten();
}