RiggsFolly answered this for me elsewhere, simply:
in your apache conf folder edit file: httpd-vhost.conf:
Add this little line inside the Directory nest:
Require ip 192.168.1
Restart the server, apache or Wamp or whatever you have.
That's it, now all your HOME deivces (in ip range 192.168.1.xxx) can see your PC server. Note you only add the first 3 parts of ip number).
Any problems, exit your firewall to test.
To see your network devices ip numbers, download an "IP Scanner" software (quite a few free ones around) for PC or for android get Fing from play store.
Here is a link which is useful to learn about select a siblings element in Jquery.
How do I select a sibling element using jQuery
$("selector").nextAll();
$("selector").prev();
you can also find an element using Jquery selector
$("h2").siblings('table').find('tr');
For more information, refer this link next(), nextAll(), prev(), prevAll(), find() and siblings in JQuery
I had similar problem, then I tried writing this from JavaScript and it works! : referenceToYourInputFile.value = "" ;
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
Since the checked value is Boolean
it's preferred to use it directly for less coding and at all it did same ==true
It is now out of preview, and available to everyone: https://developer.android.com/studio/projects/add-native-code.html
ndk-build
if you have a jni
directory in your project sources.This is working on Android studio 0.5.9 (canary build).
Either add ANDROID_NDK_HOME
to your environment variables or add ndk.dir=/path/to/ndk
to your local.properties
in your Android Studio project. This allows Android studio to run the ndk automatically.
Download the latest gradle sample projects to see an example of an ndk project. (They're at the bottom of the page). A good sample project is ndkJniLib
.
Copy the gradle.build
from the NDK sample projects. It'll look something like this. This gradle.build
creates a different apk for each architecture. You must select which architecture you want using the build variants
pane.
apply plugin: 'android'
dependencies {
compile project(':lib')
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.2"
// This actual the app version code. Giving ourselves 100,000 values [0, 99999]
defaultConfig.versionCode = 123
flavorDimensions "api", "abi"
productFlavors {
gingerbread {
flavorDimension "api"
minSdkVersion 10
versionCode = 1
}
icecreamSandwich {
flavorDimension "api"
minSdkVersion 14
versionCode = 2
}
x86 {
flavorDimension "abi"
ndk {
abiFilter "x86"
}
// this is the flavor part of the version code.
// It must be higher than the arm one for devices supporting
// both, as x86 is preferred.
versionCode = 3
}
arm {
flavorDimension "abi"
ndk {
abiFilter "armeabi-v7a"
}
versionCode = 2
}
mips {
flavorDimension "abi"
ndk {
abiFilter "mips"
}
versionCode = 1
}
fat {
flavorDimension "abi"
// fat binary, lowest version code to be
// the last option
versionCode = 0
}
}
// make per-variant version code
applicationVariants.all { variant ->
// get the version code of each flavor
def apiVersion = variant.productFlavors.get(0).versionCode
def abiVersion = variant.productFlavors.get(1).versionCode
// set the composite code
variant.mergedFlavor.versionCode = apiVersion * 1000000 + abiVersion * 100000 + defaultConfig.versionCode
}
}
Note that this will ignore your Android.mk and Application.mk files. As a workaround, you can tell gradle to disable atuomatic ndk-build call, then specify the directory for ndk sources manually.
sourceSets.main {
jniLibs.srcDir 'src/main/libs' // use the jni .so compiled from the manual ndk-build command
jni.srcDirs = [] //disable automatic ndk-build call
}
In addition, you'll probably want to call ndk-build in your gradle build script explicitly, because you just disabled the automatic call.
task ndkBuild(type: Exec) {
commandLine 'ndk-build', '-C', file('src/main/jni').absolutePath
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.
plt.subplots()
is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots()
you unpack this tuple into the variables fig
and ax
. Having fig
is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('yourfilename.png')
). You certainly don't have to use the returned figure object but many people do use it later so it's common to see. Also, all axes objects (the objects that have plotting methods), have a parent figure object anyway, thus:
fig, ax = plt.subplots()
is more concise than this:
fig = plt.figure()
ax = fig.add_subplot(111)
I have used the following method in a project and it's working successfully.
private string identifier(string wmiClass, string wmiProperty)
//Return a hardware identifier
{
string result = "";
System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
return result;
}
you can call the above method as mentioned below,
string modelNo = identifier("Win32_DiskDrive", "Model");
string manufatureID = identifier("Win32_DiskDrive", "Manufacturer");
string signature = identifier("Win32_DiskDrive", "Signature");
string totalHeads = identifier("Win32_DiskDrive", "TotalHeads");
If you need a unique identifier, use a combination of these IDs.
Assert.Throws
returns the exception that's thrown which lets you assert on the exception.
var ex = Assert.Throws<Exception>(() => user.MakeUserActive());
Assert.That(ex.Message, Is.EqualTo("Actual exception message"));
So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert.Throws
assertion will fail. However if an exception of the correct type is thrown then you can now assert on the actual exception that you've saved in the variable.
By using this pattern you can assert on other things than the exception message, e.g. in the case of ArgumentException
and derivatives, you can assert that the parameter name is correct:
var ex = Assert.Throws<ArgumentNullException>(() => foo.Bar(null));
Assert.That(ex.ParamName, Is.EqualTo("bar"));
You can also use the fluent API for doing these asserts:
Assert.That(() => foo.Bar(null),
Throws.Exception
.TypeOf<ArgumentNullException>()
.With.Property("ParamName")
.EqualTo("bar"));
or alternatively
Assert.That(
Assert.Throws<ArgumentNullException>(() =>
foo.Bar(null)
.ParamName,
Is.EqualTo("bar"));
A little tip when asserting on exception messages is to decorate the test method with the SetCultureAttribute
to make sure that the thrown message is using the expected culture. This comes into play if you store your exception messages as resources to allow for localization.
The code runs much faster without using modulo:
public boolean isEven(int a){
return ( (a & 1) == 0 );
}
public boolean isOdd(int a){
return ( (a & 1) == 1 );
}
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
In case when you load all <options ....></options>
by Ajax call
Follow these step to do this.
1). Create a separate method for set value of drop-down
For Ex:
function set_ip_base_country(countryCode)
$('#country').val(countryCode)
}
2). Call this method when ajax call success all html append task complete
For Ex:
success: function (doc) {
.....
.....
$("#country").append('<option style="color:black;" value="' + key + '">' + value + '</option>')
set_ip_base_country(ip_base_country)
}
did you try this ?
$("#yourdiv").load(url, function(){
your functions goes here !!!
});
You can have more than one statement when still return:
[]() -> your_type {return (
your_statement,
even_more_statement = just_add_comma,
return_value);}
you have various ways to distinct values on one column or multi columns.
using the GROUP BY
SELECT DISTINCT MIN(o.tblFruit_ID) AS tblFruit_ID,
o.tblFruit_FruitType,
MAX(o.tblFruit_FruitName)
FROM tblFruit AS o
GROUP BY
tblFruit_FruitType
using the subquery
SELECT b.tblFruit_ID,
b.tblFruit_FruitType,
b.tblFruit_FruitName
FROM (
SELECT DISTINCT(tblFruit_FruitType),
MIN(tblFruit_ID) tblFruit_ID
FROM tblFruit
GROUP BY
tblFruit_FruitType
) AS a
INNER JOIN tblFruit b
ON a.tblFruit_ID = b.tblFruit_I
using the join with subquery
SELECT t1.tblFruit_ID,
t1.tblFruit_FruitType,
t1.tblFruit_FruitName
FROM tblFruit AS t1
INNER JOIN (
SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
tblFruit_FruitType
FROM tblFruit
GROUP BY
tblFruit_FruitType
) AS t2
ON t1.tblFruit_ID = t2.tblFruit_ID
using the window functions only one column distinct
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName
FROM (
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName,
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID)
rn
FROM tblFruit
) t
WHERE rn = 1
using the window functions multi column distinct
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName
FROM (
SELECT tblFruit_ID,
tblFruit_FruitType,
tblFruit_FruitName,
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType, tblFruit_FruitName
ORDER BY tblFruit_ID) rn
FROM tblFruit
) t
WHERE rn = 1
check this fiddle,
i just edited the above fiddle, its working
http://jsfiddle.net/narensrinivasans/FpNxn/1/
.selectDefault, .selectDiv option
{
font-family:arial;
font-size:12px;
}
select @EmpID = ID from dbo.Employee
Or
set @EmpID =(select id from dbo.Employee)
Note that the select query might return more than one value or rows. so you can write a select query that must return one row.
If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable
DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..
As table type variable do not exist in Oracle and others, you would have to define it:
DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;
-- Then to declare a TABLE variable of this type: variable_name type_name;
-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text'
;
-- Where 'n' is the index value
Also, SimpleDateFormat is not available with some of the client-side technologies, like GWT.
It's a good idea to go for Calendar.getInstance(), and your requirement is to compare two dates; go for long date.
This error is cause by security clutches between the web application and your java. To resolve it, look into your java setting under control panel. Move the security level to a medium.
Try to use it this way:
let current_time = moment().format("HH:mm")
Repository are nothing but well-designed DAO.
ORM are table centric but not DAO.
There's no need to use several DAO in repository since DAO itself can do exactly the same with ORM repositories/entities or any DAL provider, no matter where and how a car is persisted 1 table, 2 tables, n tables, half a table, a web service, a table and a web service etc. Services uses several DAO/repositories.
My own DAO, let's say CarDao only deal with Car DTO,I mean, only take Car DTO in input and only return car DTO or car DTO collections in output.
So just like Repository, DAO actually is an IoC, for the business logic, allowing persitence interfaces not be be intimidated by persitence strategies or legacies. DAO both encapsulates the persistence strategy and does provide the domaine-related persitence interface. Repository is just an another word for those who had not understood what a well-defined DAO actualy was.
You can use Extend to add new objects to an existing one.
If you are constructing the connection string within the app then you would use your command of connString. If you are using a connection string in the web config. Then you use the "name" of that string.
The $ sign is an identifier for variables and functions.
That has a clear explanation of what the dollar sign is for.
Here's an alternative explanation: http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html
VBA uses a garbage collector which is implemented by reference counting.
There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook
creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.
Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)
<FilesMatch "\.(js|css)$">
ExpiresActive On
ExpiresDefault A1
Header append Cache-Control must-revalidate
</FilesMatch>
I cloned a repo from Github and went through every one of the suggestions here. After a lot of frustration, I realized that npm install
did not install any of the modules and my node_modules
folder was empty the whole time.
QUICK FIX:
1) delete your node_modules
folder
2) delete your package-lock.json
3) run npm install
You can get all keys / values and preserve the hierarchy with this
// get keys of an object or array
function getkeys(z){
var out=[];
for(var i in z){out.push(i)};
return out;
}
// print all inside an object
function allInternalObjs(data, name) {
name = name || 'data';
return getkeys(data).reduce(function(olist, k){
var v = data[k];
if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
else { olist.push(name + '.' + k + ' = ' + v); }
return olist;
}, []);
}
// run with this
allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')
This is a modification on (https://stackoverflow.com/a/25063574/1484447)
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
Here's a LESS mixin to generate the stroke: http://codepen.io/anon/pen/BNYGBy?editors=110
/// Stroke font-character
/// @param {Integer} $stroke - Stroke width
/// @param {Color} $color - Stroke color
/// @return {List} - text-shadow list
.stroke(@stroke, @color) {
@maxi: @stroke + 1;
.i-loop (@i) when (@i > 0) {
@maxj: @stroke + 1;
.j-loop (@j) when (@j > 0) {
text-shadow+: (@i - 1)*(1px) (@j - 1)*(1px) 0 @color;
text-shadow+: (@i - 1)*(1px) (@j - 1)*(-1px) 0 @color;
text-shadow+: (@i - 1)*(-1px) (@j - 1)*(-1px) 0 @color;
text-shadow+: (@i - 1)*(-1px) (@j - 1)*(1px) 0 @color;
.j-loop(@j - 1);
}
.j-loop (0) {}
.j-loop(@maxj);
.i-loop(@i - 1);
}
.i-loop (0) {}
.i-loop(@maxi);
text-shadow+: 0 0 0 @color;
}
(it's based on pixelass answer that instead uses SCSS)
If you're using a standard POSIX OS, you use cron.
If you're using Windows, you use at.
Write a Django management command to
Figure out what platform they're on.
Either execute the appropriate "AT" command for your users, or update the crontab for your users.
That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.
The HTML in your example will be:
<tr>
<td>TEST</td>
</tr>
Read the PHP documentation that explains it.
if(success == true)
{
//For wait 5 seconds
setTimeout(function()
{
location.reload(); //Refresh page
}, 5000);
}
I changed the memory limit from .htaccess and this problem got resolved.
I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:
php_value memory_limit 512M
After scan was over, I removed this line to make the size as it was before.
Since API 16 you can supply an activity options bundle when calling Context.startActivity(Intent, Bundle) or related methods. It is created via the ActivityOptions builder:
Intent myIntent = new Intent(context, MyActivity.class);
ActivityOptions options =
ActivityOptions.makeCustomAnimation(context, R.anim.fade_in, R.anim.fade_out);
context.startActivity(myIntent, options.toBundle());
Don't forget to check out the other methods of the ActivityOptions builder and the ActivityOptionsCompat if you are using the Support Library.
API 5+:
For apps targeting API level 5+ there is the Activities overridePendingTransition
method. It takes two resource IDs for the incoming and outgoing animations. An id of 0
will disable the animations. Call this immediately after the startActivity
call.
i.e.:
startActivity(new Intent(this, MyActivity.class));
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
API 3+:
You can prevent the default animation (Slide in from the right) with the Intent.FLAG_ACTIVITY_NO_ANIMATION
flag in your intent.
i.e.:
Intent myIntent = new Intent(context, MyActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(myIntent);
then in your Activity you simply have to specify your own animation.
This also works for the 1.5 API (Level 3).
It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.
http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html
Data Type Date Type Storage Required
(CLOB) (BLOB)
TINYTEXT TINYBLOB L + 1 bytes, where L < 2**8 (255)
TEXT BLOB L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT MEDIUMBLOB L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT LONGBLOB L + 4 bytes, where L < 2**32 (4 GB)
where L stands for the byte length of a string
How to do this in 2017:
spl_autoload_register( function ($class_name) {
$CLASSES_DIR = __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR; // or whatever your directory is
$file = $CLASSES_DIR . $class_name . '.php';
if( file_exists( $file ) ) include $file; // only include if file exists, otherwise we might enter some conflicts with other pieces of code which are also using the spl_autoload_register function
} );
Recommended by PHP documentation here: Autoloading classes
The information provided in this answer can lead to insecure programming practices.
The information provided here depends highly on MySQL configuration, including (but not limited to) the program version, the database client and character-encoding used.
See http://dev.mysql.com/doc/refman/5.0/en/string-literals.html
MySQL recognizes the following escape sequences. \0 An ASCII NUL (0x00) character. \' A single quote (“'”) character. \" A double quote (“"”) character. \b A backspace character. \n A newline (linefeed) character. \r A carriage return character. \t A tab character. \Z ASCII 26 (Control-Z). See note following the table. \\ A backslash (“\”) character. \% A “%” character. See note following the table. \_ A “_” character. See note following the table.
So you need
select * from tablename where fields like "%string \"hi\" %";
Although as Bill Karwin notes below, using double quotes for string delimiters isn't standard SQL, so it's good practice to use single quotes. This simplifies things:
select * from tablename where fields like '%string "hi" %';
I had the same error and running mvn install -U
and then running mvn install
worked for me.
use it
ApplicationContext context = new FileSystemXmlApplicationContext("Beans.xml");
Take a look at the Cursor.Position
Property. It should get you started.
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
I believe you are looking for this:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());
Based on other answers, here goes one more example where I removed all special chars in a given string:
#include <iostream>
#include <string>
#include <algorithm>
std::string chars(".,?!.:;_,!'\"-");
int main(int argc, char const *argv){
std::string input("oi?");
std::string output = eraseSpecialChars(input);
return 0;
}
std::string eraseSpecialChars(std::string str){
std::string newStr;
newStr.assign(str);
for(int i = 0; i < str.length(); i++){
for(int j = 0; j < chars.length(); j++ ){
if(str.at(i) == chars.at(j)){
char c = str.at(i);
newStr.erase(std::remove(newStr.begin(), newStr.end(), c), newStr.end());
}
}
}
return newStr;
}
Input vs Output:
Input:ra,..pha
Output:rapha
Input:ovo,
Output:ovo
Input:a.vo
Output:avo
Input:oi?
Output:oi
.document {
align-items: center;
background-color: hsl(229, 57%, 11%);
border-radius: 5px;
display: flex;
height: 40px;
width: 40px;
}
.document img {
display: block;
margin: auto;
}
_x000D_
<div class="document">
<img src="./images/icon-document.svg" alt="icon-document" />
</div>
_x000D_
I tried many formats, but only that worked:
select /*+INDEX(e,dept_idx)*/ * from emp e;
Interestingly, this solution can break, but a workaround:
Looking for my database called KeyWorks.accdb
which must exist:
Run this:
Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry
If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.
If my database is named KeyWorksBB.accdb
, the If
statement will find this acceptable and exit the If
statement because it did indeed find KeyWorks
and accdb
.
If I surround the If
statement qualifier with single quotes like 'KeyWorks.accdb'
, it now looks for all the consecutive characters in order and would enter the If
block because it did not match.
You have to set all parent containers to a 100% width if you want to cover the whole page with it. You have to set an absolute value at width and height for the #content div at the very least.
body, html {
height: 100%;
width: 100%;
}
div#content {
width: 100%; height: 100%;
}
groupId and Mojo name change Since version 2.0-beta-1 tomcat mojos has been renamed to tomcat6 and tomcat7 with the same goals.
You must configure your pom to use this new groupId:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat6-maven-plugin</artifactId>
<version>2.3-SNAPSHOT</version>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.3-SNAPSHOT</version>
</plugin>
</plugins>
</pluginManagement>
Or add the groupId in your settings.xml
.... org.apache.tomcat.maven ....
Set path=%path%;C:\Users\\AppData\Roaming\npm
In your mysql command line: SET explicit_defaults_for_timestamp=1
in this scenario:
DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
aren't you missing the column you want to compare to? example:
DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.
If you're already in conflicted state, and you want to just accept all of theirs:
git checkout --theirs .
git add .
If you want to do the opposite:
git checkout --ours .
git add .
This is pretty drastic, so make sure you really want to wipe everything out like this before doing it.
If you know a variable is empty, you could use it as a comment. Of course if it is not empty it will mess up your command.
ls -l ${1# -F is turned off} -a /etc
Simply type
MODE [width],[height]
Example:
MODE 14,1
That is the smallest size possible.
MODE 1000,1000
is the largest possible, although it probably won't even fit your screen. If you want to minimize it, type
start /min [yourbatchfile/cmd]
and of course, to maximaze,
start /max [yourbatchfile/cmd]
I am currently working on doing this from the same batch files so that you don't have to have two or start it with cmd. of course, there are shortcuts, but I'm gonna try to figure it out.
What is happening here is that database route does not accept any url methods.
I would try putting the url methods in the app route just like you have in the entry_page function:
@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
if request.method == 'POST':
date = request.form['date']
title = request.form['blog_title']
post = request.form['blog_main']
post_entry = models.BlogPost(date = date, title = title, post = post)
db.session.add(post_entry)
db.session.commit()
return redirect(url_for('database'))
else:
return render_template('entry.html')
@app.route('/database', methods=['GET', 'POST'])
def database():
query = []
for i in session.query(models.BlogPost):
query.append((i.title, i.post, i.date))
return render_template('database.html', query = query)
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
@crobar, you are right that there is a dearth of multi-file examples, so I decided to share the following in the hopes that it helps others:
::::::::::::::
main.cpp
::::::::::::::
#include <iostream>
#include "UseSomething.h"
#include "Something.h"
int main()
{
UseSomething y;
std::cout << y.getValue() << '\n';
}
::::::::::::::
Something.h
::::::::::::::
#ifndef SOMETHING_H_
#define SOMETHING_H_
class Something
{
private:
static int s_value;
public:
static int getValue() { return s_value; } // static member function
};
#endif
::::::::::::::
Something.cpp
::::::::::::::
#include "Something.h"
int Something::s_value = 1; // initializer
::::::::::::::
UseSomething.h
::::::::::::::
#ifndef USESOMETHING_H_
#define USESOMETHING_H_
class UseSomething
{
public:
int getValue();
};
#endif
::::::::::::::
UseSomething.cpp
::::::::::::::
#include "UseSomething.h"
#include "Something.h"
int UseSomething::getValue()
{
return(Something::getValue());
}
The first argument to a shell script is available as the variable $1
, so the simplest implementation would be
if [ "$1" == "-h" ]; then
echo "Usage: `basename $0` [somestuff]"
exit 0
fi
But what anubhava said.
Your condition is wrong. myChar != 'n' || myChar != 'N'
will always be true.
Use myChar != 'n' && myChar != 'N'
instead
The correct function to use is flush()
.
<html>
<body>
<p>
Hello! I am waiting for the next message...<br />
<?php flush(); sleep(5); ?>
I am the next message!<br />
<?php flush(); sleep(5); ?>
And I am the last message. Good bye.
</p>
</body>
</html>
Please note that there is a "problem" with IE, which only outputs the flushed content when it is at least 256 byte, so your first part of the page needs to be at least 256 byte.
Right answer can be found in this (duplicate) question.
I reproduced the answer here (and it works!):
Just delete the .lock file in the .metadata directory in your eclipse workspace directory
Given an activated Python 3.6 virtualenv in somepath/venv, the following aliases resolved the various issues on a macOS Sierra where pip insisted on pointing to Apple's 2.7 Python.
alias pip='python somepath/venv/lib/python3.6/site-packages/pip/__main__.py'
This didn't work so well when I had to do sudo pip
as the root user doesn't know anything about my alias or the virtualenv, so I had to add an extra alias to handle this as well. It's a hack, but it works, and I know what it does:
alias sudopip='sudo somepath/venv/bin/python somepath/venv/lib/python3.6/site-packages/pip/__main__.py'
pip3 did not exist to start (command not found) with and which pip
would return /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/pip, the Apple Python.
Python 3.6 was installed via macports.
After activation of the 3.6 virtualenv I wanted to work with, which python
would return somepath/venv/bin/python
Somehow pip install
would do the right thing and hit my virtualenv, but pip list
would rattle off Python 2.7 packages.
For Python, this is batting way beneath my expectations in terms of beginner-friendliness.
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
If anyone is seeing this,
This fix worked for me as nothing from the above worked:
This worked for me
int indexOf(Object o)
This method returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element.
I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:
myLabel.ForeColor = System.Drawing.Color.Red;
Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:
myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)
Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".
An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.
A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.
You'll need to save as a blob, LONGBLOB datatype in mysql will work.
Ex:
CREATE TABLE 'test'.'pic' (
'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
'caption' VARCHAR(45) NOT NULL,
'img' LONGBLOB NOT NULL,
PRIMARY KEY ('idpic')
)
As others have said, its a bad practice but it can be done. Not sure if this code would scale well, though.
In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.
From the connecting schema:
CREATE SYNONYM pi_int FOR pct.pi_int;
Then you can query pi_int
as:
SELECT * FROM pi_int;
Use anchor links and the scroll-behavior
property (MDN reference) for the scrolling container:
scroll-behavior: smooth;
Browser support: Firefox 36+, Chrome 61+ (therefore also Edge 79+) and Opera 48+.
Intenet Explorer, non-Chromium Edge and (so far) Safari do not support scroll-behavior
and simply "jump" to the link target.
Example usage:
<head>
<style type="text/css">
html {
scroll-behavior: smooth;
}
</style>
</head>
<body id="body">
<a href="#foo">Go to foo!</a>
<!-- Some content -->
<div id="foo">That's foo.</div>
<a href="#body">Back to top</a>
</body>
Here's a Fiddle.
And here's also a Fiddle with both horizontal and vertical scrolling.
I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default
declaration for a class, and instead append the export
tag to the class declaration. The imported class should be instead listed in the import
command of the module.
That is: instead of
class Foo {
// ...
}
export default Foo;
and the simple import Foo from './foo';
in the module that will import, one should use
export class Foo {
// ...
}
and import {Foo} from './foo'
in the importer.
The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default
can lead to problems
while(something.hasnext())
do something...
if(contains something to process){
do something...
break;
}
}
Just use the break statement;
For eg:this just prints "Breaking..."
while (true) {
if (true) {
System.out.println("Breaking...");
break;
}
System.out.println("Did this print?");
}
In file wp-config.php you can find constant WP_DEBUG. Make sure it is set to false.
define('WP_DEBUG', false);
This is for WordPress 3.x.
Lately I created a chrome extension "eXtract Snippet" for copying the inspected element, html and only the relevant css and media queries from a page. Note that this would give you the actual relevant CSS
https://chrome.google.com/webstore/detail/extract-snippet/bfcjfegkgdoomgmofhcidoiampnpbdao?hl=en
If it is for binding, then you can reference indexers from XAML
Text="{Binding [FullName]}"
Here it is referencing the class indexer with the key "FullName"
SO what i have decided to do finally is here and its working fine on all mobile browsers including iPhones and Androids.
$(document).ready(function(){_x000D_
_x000D_
$('input[type="date"]').each(function(e) {_x000D_
var $el = $(this), _x000D_
$this_placeholder = $(this).closest('label').find('.custom-placeholder');_x000D_
$el.on('change',function(){_x000D_
if($el.val()){_x000D_
$this_placeholder.text('');_x000D_
}else {_x000D_
$this_placeholder.text($el.attr('placeholder'));_x000D_
}_x000D_
});_x000D_
});_x000D_
_x000D_
});
_x000D_
label {_x000D_
position: relative; _x000D_
}_x000D_
.custom-placeholder {_x000D_
#font > .proxima-nova-light(26px,40px);_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: 10;_x000D_
color: #999;_x000D_
}
_x000D_
<label>_x000D_
<input type="date" placeholder="Date">_x000D_
<span class="custom-placeholder">Date</span>_x000D_
</label>
_x000D_
Date
This answer similar to others, but using preferred stringr::str_detect
and dplyr rownames_to_column
.
library(tidyverse)
mtcars %>%
rownames_to_column("type") %>%
filter(stringr::str_detect(type, 'Toyota|Mazda') )
#> type mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 2 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 3 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
#> 4 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
Created on 2018-06-26 by the reprex package (v0.2.0).
I know this is an old question, but I just searched for the same thing and probably there are many others searching for a quick, mobile solution. Here is what I finally come up with:
# We set production environment by default
SetEnv PROD_ENV 1
<IfDefine DEV_ENV>
# If 'DEV_ENV' has been defined, then unset the PROD_ENV
UnsetEnv PROD_ENV
AuthType Basic
AuthName "Protected Area"
AuthUserFile /var/www/foo.local/.htpasswd
Require valid-user
</IfDefine>
<IfDefine PROD_ENV>
AuthType Basic
AuthName "Protected Area"
AuthUserFile /home/foo/public_html/.htpasswd
Require valid-user
</IfDefine>
Bootstrap 4
Use the data-parent=""
attribute on the collapse element (instead of the trigger element)
<div id="accordion">
<div class="card">
<div class="card-header">
<h5>
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
Collapsible #1 trigger
</button>
</h5>
</div>
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="card-body">
Collapsible #1 element
</div>
</div>
</div>
... (more cards/collapsibles inside #accordion parent)
</div>
Bootstrap 3
See this issue on GitHub: https://github.com/twbs/bootstrap/issues/10966
There is a "bug" that makes the accordion dependent on the .panel
class when using the data-parent
attribute. To workaround it, you can wrap each accordion group in a 'panel' div..
<div class="accordion" id="myAccordion">
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
<div id="collapsible-1" class="collapse">
..
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
<div id="collapsible-2" class="collapse">
..
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
<div id="collapsible-3" class="collapse">
...
</div>
</div>
</div>
Edit
As mentioned in the comments, each section doesn't have to be a .panel
. However...
.panel
must be a direct child of the element used as data-parent=
data-toggle=
) must be a direct child of the .panel
(http://www.bootply.com/AbiRW7BdD6#)It depends on usage. If the case is lookup objects is very faster.
Here is a Plunker example to test performance of array and object lookups.
https://plnkr.co/edit/n2expPWVmsdR3zmXvX4C?p=preview
You will see that;
Looking up for 5.000 items in 5.000 length array collection, take over 3000
milisecons
However Looking up for 5.000 items in object has 5.000 properties, take only 2
or 3
milisecons
Also making object tree don't make huge difference
This will work:
let item = tableView.cellForRowAtIndexPath(indexPath)!.textLabel!.text!
You don't need a generate bock if you want all the bits of temp
assigned in the same always block.
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
for (integer c=0; c<ROWBITS; c=c+1) begin: test
temp[c] <= 1'b0;
end
end
Alternatively, if your simulator supports IEEE 1800 (SytemVerilog), then
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
temp <= '0; // fill with 0
end
end
Because you can't print a character with string formating. You can also think of adding a format with something like this
#define PRINTC(c,f,s) printf ("\033[%dm" f "\033[0m", 30 + c, s)
f
is format as in printf
PRINTC (4, "%s\n", "bar")
will print blue bar
PRINTC (1, "%d", 'a')
will print red 97
this.setState(
{
originId: input.originId,
destinationId: input.destinationId,
radius: input.radius,
search: input.search
},
function() { console.log("setState completed", this.state) }
)
this might be helpful
in asp.net:
color_black = (Color)new ColorConverter().ConvertFromString("#FF76B3");
Go for whatever is most readable and easily maintainable. Just because you can write it out in a single line doesn't mean that you should. Your existing solution is close to what I would use other than I would user iteritems to skip the value lookup, and I hate nested ifs if I can avoid them:
for key, val in d.iteritems():
if filter_string not in key:
continue
# do something
However if you realllly want something to let you iterate through a filtered dict then I would not do the two step process of building the filtered dict and then iterating through it, but instead use a generator, because what is more pythonic (and awesome) than a generator?
First we create our generator, and good design dictates that we make it abstract enough to be reusable:
# The implementation of my generator may look vaguely familiar, no?
def filter_dict(d, filter_string):
for key, val in d.iteritems():
if filter_string not in key:
continue
yield key, val
And then we can use the generator to solve your problem nice and cleanly with simple, understandable code:
for key, val in filter_dict(d, some_string):
# do something
In short: generators are awesome.
By using JavaScript: document.getElementById("myBtn").click();
Well..according to this php bug report , you can even get 0wned.
<?php
$pass = isset($_GET['pass']) ? $_GET['pass'] : '';
// Query /?pass[]= will authorize user
//strcmp and strcasecmp both are prone to this hack
if ( strcasecmp( $pass, '123456' ) == 0 ){
echo 'You successfully logged in.';
}
?>
It gives you a warning , but still bypass the comparison.
You should be doing ===
as @postfuturist suggested.
in code there should be coma"," not colon ":"
the code must be $(this).css({'background-color' , '#FFFFEE'});
i hope it helps.
regards Saleha
Using Stopwatch class we can achieve it from System.Diagnostics
.
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
stopwatch.Stop();
Debug.WriteLine(stopwatch.ElapsedMilliseconds);
In C++, a constructor with only one required parameter is considered an implicit conversion function. It converts the parameter type to the class type. Whether this is a good thing or not depends on the semantics of the constructor.
For example, if you have a string class with constructor String(const char* s)
, that's probably exactly what you want. You can pass a const char*
to a function expecting a String
, and the compiler will automatically construct a temporary String
object for you.
On the other hand, if you have a buffer class whose constructor Buffer(int size)
takes the size of the buffer in bytes, you probably don't want the compiler to quietly turn int
s into Buffer
s. To prevent that, you declare the constructor with the explicit
keyword:
class Buffer { explicit Buffer(int size); ... }
That way,
void useBuffer(Buffer& buf);
useBuffer(4);
becomes a compile-time error. If you want to pass a temporary Buffer
object, you have to do so explicitly:
useBuffer(Buffer(4));
In summary, if your single-parameter constructor converts the parameter into an object of your class, you probably don't want to use the explicit
keyword. But if you have a constructor that simply happens to take a single parameter, you should declare it as explicit
to prevent the compiler from surprising you with unexpected conversions.
Posed question
Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.
Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.
Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:
Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.
Application-specific question
However, returning to your task, I'd research 2 topics:
Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:
Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."
(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.
Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.
(link)
Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).
(link) - they explore both accuracy and MSE, considering the latter to be better
Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.
(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.
Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.
About approaches, not metrics
Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.
The best and most effective solution is just adding theme in your main class and add input decoration like these.
theme: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.pink)
)
),
)
With no parameters, the .hide() method is the simplest way to hide an element:
$('.target').hide(); The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.
Same about show
See the Scripting Guy! Blog:
How Can I Tell Whether a Value Exists in the Registry?
They discuss doing the check on a remote computer and show that if you read a string value from the key, and if the value is Null (as opposed to Empty), the key does not exist.
With respect to using the RegRead method, if the term "key" refers to the path (or folder) where registry values are kept, and if the leaf items in that key are called "values", using WshShell.RegRead(strKey) to detect key existence (as opposed to value existance) consider the following (as observed on Windows XP):
If strKey name is not the name of an existing registry path, Err.Description reads "Invalid root in registry key"... with an Err.Number of 0x80070002.
If strKey names a registry path that exists but does not include a trailing "\" the RegRead method appears to interpret strKey as a path\value reference rather than as a simple path reference, and returns the same Err.Number but with an Err.Description of "Unable to open registry key". The term "key" in the error message appears to mean "value". This is the same result obtained when strKey references a path\value where the path exists, but the value does not exist.
With the newer versions of angularjs the correct answer to this question is to use ng-if
:
<ul>
<li ng-if="list.length === 0">( No items in this list yet! )</li>
<li ng-repeat="item in list">{{ item }}</li>
</ul>
This solution will not flicker when the list is about to download either because the list has to be defined and with a length of 0 for the message to display.
Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview
Tip: You can also show a loading text or spinner:
<li ng-if="!list">( Loading... )</li>
Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.
If you define the field as VARCHAR2(11 BYTE)
, Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.
By defining the field as VARCHAR2(11 CHAR)
you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
$scope.$emit: This method dispatches the event in the upwards direction (from child to parent)
$scope.$broadcast: Method dispatches the event in the downwards direction (from parent to child) to all the child controllers.
$scope.$on: Method registers to listen to some event. All the controllers which are listening to that event get notification of the broadcast or emit based on the where those fit in the child-parent hierarchy.
The $emit event can be cancelled by any one of the $scope who is listening to the event.
The $on provides the "stopPropagation" method. By calling this method the event can be stopped from propagating further.
Plunker :https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/
In case of sibling scopes (the scopes which are not in the direct parent-child hierarchy) then $emit and $broadcast will not communicate to the sibling scopes.
For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html
Adding to @zzzzzzz answer, I ran the command:python3 -c "import sys; print(sys.path)"
and it provided me with different paths comparing to the same command with python
. The paths that were displayed with python3
were "python3 oriented".
See the output of the two different commands:
python -c "import sys; print(sys.path)"
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/local/lib/python2.7/dist-packages/setuptools-39.1.0-py2.7.egg', '/usr/lib/python2.7/dist-packages']
python3 -c "import sys; print(sys.path)"
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
Both commands were executed on my Ubuntu 18.04 machine.
To avoid the race condition @GregPettit mentions, one can use:
($("element").data('bs.modal') || {})._isShown // Bootstrap 4
($("element").data('bs.modal') || {}).isShown // Bootstrap <= 3
as discussed in Twitter Bootstrap Modal - IsShown.
When the modal is not yet opened, .data('bs.modal')
returns undefined
, hence the || {}
- which will make isShown
the (falsy) value undefined
. If you're into strictness one could do ($("element").data('bs.modal') || {isShown: false}).isShown
here is my solution
string var = "Hello345wor705Ld";
string alpha = string.Empty;
string numer = string.Empty;
foreach (char str in var)
{
if (char.IsDigit(str))
numer += str.ToString();
else
alpha += str.ToString();
}
Console.WriteLine("String is: " + alpha);
Console.WriteLine("Numeric character is: " + numer);
Console.Read();
If the file is text, and you want to get the text line by line, the easiest way is to use fgets().
char buffer[100];
FILE *fp = fopen("filename", "r"); // do not use "rb"
while (fgets(buffer, sizeof(buffer), fp)) {
... do something
}
fclose(fp);
With ObsoleteAttribute
you can to show the deprecated method.
Obsolete attribute has three constructor:
[Obsolete]:
is a no parameter constructor and is a default using this attribute.[Obsolete(string message)]:
in this format you can getmessage
of why this method is deprecated.[Obsolete(string message, bool error)]:
in this format message is very explicit buterror
means, in compilation time, compiler must be showing error and cause to fail compiling or not.
It is possible with PowerShell 4.
Get-Service *spool* | select name,starttype | ft -AutoSize
Tensorflow isn't available for python 3.8
(as of Dec 4th 2019) according to their documentation page. You will have to downgrade to python 3.7
.
Let's dissect it. There are three parts:
cd
-- This is change directory command./d
-- This switch makes cd
change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0
. (%~d0
Changs active drive, cd %~p0
change the directory).%~dp0
-- This can be dissected further into three parts:
%0
-- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.%~0
-- The ~
there strips double quotes ("
) around the expanded argument.%dp0
-- The d
and p
there are modifiers of the expansion. The d
forces addition of a drive letter and the p
adds full path.As of Git v2.23.0 (August 2019), git switch
is preferred over git checkout
when you’re simply switching branches/tags. I’m guessing they did this since git checkout
had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch
, and git restore
, to separate those concerns. I would predict at some point in the future, git checkout
will be deprecated.
To switch to a normal branch, use git switch <branch-name>
. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>
, where <commitish>
is the tag name or commit number.
The --detach
option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>
.
dplyr since 0.4 implemented all those joins including outer_join
, but it was worth noting that for the first few releases prior to 0.4 it used not to offer outer_join
, and as a result there was a lot of really bad hacky workaround user code floating around for quite a while afterwards (you can still find such code in SO, Kaggle answers, github from that period. Hence this answer still serves a useful purpose.)
Join-related release highlights:
v0.1.3 (4/2014)
Workarounds per hadley's comments in that issue:
install this https://www.microsoft.com/en-us/download/details.aspx?id=13255
install the 32 bit version no matter whether you are 64 bit and enable the 32 bit apps in the application pool
Check out this article and this simple example. Quick translation of same to your classes ...
var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
Per your edit: For that case, you can do this ...
var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
To see where I came up with backtick1 for the name of the generic class, see this article.
Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:
Type type = typeof(IReadOnlyDictionary<,>);
I guess you won't be able to really find all possible exploits by parsing your source files.
also if there are really great lists provided in here, you can miss a function which can be exploitet
there still could be "hidden" evil code like this
$myEvilRegex = base64_decode('Ly4qL2U=');
preg_replace($myEvilRegex, $_POST['code']);
you could now say, i simply extend my script to also match this
but then you will have that mayn "possibly evil code" which additionally is out of it's context
so to be (pseudo-)secure, you should really write good code and read all existing code yourself
Check the thread status by calling Thread.isAlive
.
isset
is not appropriate.According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists
is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
Below code worked for me for getting a pdf file from an API service and response it out to the browser - hope it helps;
public async Task<FileResult> PrintPdfStatements(string fileName)
{
var fileContent = await GetFileStreamAsync(fileName);
var fileContentBytes = ((MemoryStream)fileContent).ToArray();
return File(fileContentBytes, System.Net.Mime.MediaTypeNames.Application.Pdf);
}
Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =
In my opinion, it is a good practice to run Jupyter in a dedicated workbook folder.
$ mkdir jupyter_folder
$ jupyter-notebook --notebook-dir jupyter_folder
where 'jupyter_folder' is a folder in my home.
This method work without permission issue.
i have a data access library which works with both .net core and .net framework.
the trick was in .net core projects to keep the connection strings in a xml file named "app.config" (also for web projects), and mark it as 'copy to output directory',
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="conn1" connectionString="...." providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
ConfigurationManager.ConnectionStrings - will read the connection string.
var conn1 = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;
I write out a rule in web.config after $locationProvider.html5Mode(true)
is set in app.js
.
Hope, helps someone out.
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
In my index.html I added this to <head>
<base href="/">
Don't forget to install IIS URL Rewrite on server.
Also if you use Web API and IIS, this will work if your API is at www.yourdomain.com/api
because of the third input (third line of condition).
Here's the actual code based on Colin's Ramsay answer:
<View style={{flex: 1}}>
<ScrollView>main</ScrollView>
<View><Text>footer</Text></View>
</View>
Use block level buttons, those that span the full width of a parent
You can achieve this by adding btn-block
class your button element.
Documentation here
I think you can use substring method to get name of the file from the path string.
String path=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";
// it contains your image path...I'm using a temp string...
String filename=path.substring(path.lastIndexOf("/")+1);
Note: Ruby >= 1.9.2 has an order-preserving hash: the order keys are inserted will be the order they are enumerated. The below applies to older versions or to backward-compatible code.
There is no concept of a sorted hash. So no, what you're doing isn't right.
If you want it sorted for display, return a string:
"{" + h.sort.map{|k,v| "#{k.inspect}=>#{v.inspect}"}.join(", ") + "}"
or, if you want the keys in order:
h.keys.sort
or, if you want to access the elements in order:
h.sort.map do |key,value|
# keys will arrive in order to this block, with their associated value.
end
but in summary, it makes no sense to talk about a sorted hash. From the docs, "The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order." So inserting keys in a specific order into the hash won't help.
One another way is to use the same thing what firebase uses.
For example when user logs in, firebase stores below details in local storage. When user comes back to the page, firebase uses the same method to identify if user should be logged in automatically.
ATTN: As this is neither listed or recommended by firebase. You can call this method un-official way of doing this. Which means later if firebase changes their inner working, this method may not work. Or in short. Use at your own risk! :)
Lots of answers already to do it the way that the OP asked. But it worth noting that doing it the opposite way around is far simpler:
git clone repo-url tmp/
cp -R working/ tmp/
You now have the desired target state - fresh clone + local-changes.
Keep a look out for SQL Server to support the 'INSERT ALL' Statement. Oracle has it already, it looks like this (SQL Cookbook):
insert all
when loc in ('NEW YORK', 'BOSTON') THEN
into dept_east(deptno, dname, loc) values(deptno, dname, loc)
when loc in ('CHICAGO') THEN
into dept_mid(deptno, dname, loc) values(deptno, dname, loc)
else
into dept_west(deptno, dname, loc) values(deptno, dname, loc)
select deptno, dname, loc
from dept
If there's only some few components of your webview that is slow or laggy, try adding this to the elements css:
transform: translate3d(0,0,0);
-webkit-transform: translate3d(0,0,0);
This has been the only speedhack that really had a effect on my webview. But be careful not to overuse it! (you can read more about the hack in this article.)
Consider the following example to solve your problem:
#!/usr/bin/python
# -*- coding: latin-1 -*-
import os, sys, time, signal
def termination_handler (signum,frame):
global running
global pidfile
print 'You have requested to terminate the application...'
sys.stdout.flush()
running = 0
os.unlink(pidfile)
running = 1
signal.signal(signal.SIGINT,termination_handler)
pid = str(os.getpid())
pidfile = '/tmp/'+os.path.basename(__file__).split('.')[0]+'.pid'
if os.path.isfile(pidfile):
print "%s already exists, exiting" % pidfile
sys.exit()
else:
file(pidfile, 'w').write(pid)
# Do some actual work here
while running:
time.sleep(10)
I suggest this script because it can be executed one time only.
if you don't even want to initialize ng-model to a static value and each value is DB driven, it can be done in the following way. Angular compares the evaluated value and populates the drop down.
Here below modelData.unitId is retrieved from DB and is compared to the list of unit id which is a separate list from db-
<select id="uomList" ng-init="modelData.unitId"_x000D_
ng-model="modelData.unitId" ng-options="unitOfMeasurement.id as unitOfMeasurement.unitName for unitOfMeasurement in unitOfMeasurements">
_x000D_
I think this represents a good answer.
APK Signature Scheme v2 verification
APK Signing Block
and verify that:
APK Signing Block
contain the same value.ZIP Central Directory
is immediately followed by ZIP End of Central Directory
record.ZIP End of Central Directory
is not followed by more data.APK Signature Scheme v2 Block
inside the APK Signing Block
. If the v2 Block if present, proceed to step 3. Otherwise, fall back to verifying the APK using v1 scheme.APK Signature Scheme v2 Block
:
SubjectPublicKeyInfo
of the first certificate of certificates is identical to public key.Note: APK must not be verified using the v1 scheme if a failure occurs in step 3 or 4.
JAR-signed APK verification (v1 scheme)
The JAR-signed APK is a standard signed JAR, which must contain exactly the entries listed in META-INF/MANIFEST.MF
and where all entries must be signed by the same set of signers. Its integrity is verified as follows:
META-INF/<signer>.SF
and META-INF/<signer>.(RSA|DSA|EC)
JAR entry.<signer>.(RSA|DSA|EC)
is a PKCS #7 CMS ContentInfo
with SignedData structure whose signature is verified over the <signer>.SF
file.<signer>.SF
file contains a whole-file digest of the META-INF/MANIFEST.MF
and digests of each section of META-INF/MANIFEST.MF
. The whole-file digest of the MANIFEST.MF
is verified. If that fails, the digest of each MANIFEST.MF
section is verified instead.META-INF/MANIFEST.MF
contains, for each integrity-protected JAR entry, a correspondingly named section containing the digest of the entry’s uncompressed contents. All these digests are verified.MANIFEST.MF
and are not part of JAR signature.
The protection chain is thus <signer>.(RSA|DSA|EC)
? <signer>.SF
? MANIFEST.MF
? contents of each integrity-protected JAR entry.In 3 words: inline-block
is better.
Inline Block
The only drawback to the display: inline-block
approach is that in IE7 and below an element can only be displayed inline-block
if it was already inline
by default. What this means is that instead of using a <div>
element you have to use a <span>
element. It's not really a huge drawback at all because semantically a <div>
is for dividing the page while a <span>
is just for covering a span of a page, so there's not a huge semantic difference. A huge benefit of display:inline-block
is that when other developers are maintaining your code at a later point, it is much more obvious what display:inline-block
and text-align:right
is trying to accomplish than a float:left
or float:right
statement. My favorite benefit of the inline-block
approach is that it's easy to use vertical-align: middle
, line-height
and text-align: center
to perfectly center the elements, in a way that is intuitive. I found a great blog post on how to implement cross-browser inline-block, on the Mozilla blog. Here is the browser compatibility.
Float
The reason that using the float
method is not suited for layout of your page is because the float
CSS property was originally intended only to have text wrap around an image (magazine style) and is, by design, not best suited for general page layout purposes. When changing floated elements later, sometimes you will have positioning issues because they are not in the page flow. Another disadvantage is that it generally requires a clearfix otherwise it may break aspects of the page. The clearfix requires adding an element after the floated elements to stop their parent from collapsing around them which crosses the semantic line between separating style from content and is thus an anti-pattern in web development.
Any white space problems mentioned in the link above could easily be fixed with the white-space
CSS property.
SitePoint is a very credible source for web design advice and they seem to have the same opinion that I do:
If you’re new to CSS layouts, you’d be forgiven for thinking that using CSS floats in imaginative ways is the height of skill. If you have consumed as many CSS layout tutorials as you can find, you might suppose that mastering floats is a rite of passage. You’ll be dazzled by the ingenuity, astounded by the complexity, and you’ll gain a sense of achievement when you finally understand how floats work.
Don’t be fooled. You’re being brainwashed.
http://www.sitepoint.com/give-floats-the-flick-in-css-layouts/
2015 Update - Flexbox is a good alternative for modern browsers:
.container {
display: flex; /* or inline-flex */
}
.item {
flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
}
Dec 21, 2016 Update
Bootstrap 4 is removing support for IE9, and thus is getting rid of floats from rows and going full Flexbox.
Normally, the exe can be found in the debug folder, as suggested previously, but not in the release folder, that is disabled by default in my configuration. If you want to activate the release folder, you can do this: BUILD->Batch Build And activate the "build" checkbox in the release configuration. When you click the build button, the exe with some dependencies will be generated. Now you can copy and use it.
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
An elegant scripted solution for Linux can be found at: http://www.damnsmalllinux.org/f/topic-3-23-17031-0.html
My favorite way to do is by using behavior subject or event emitter (almost the same) in my service to control all my subcomponent.
Using angular cli, run ng g s to create a new service then use a BehaviorSubject or EventEmitter
export Class myService {
#all the stuff that must exist
myString: string[] = [];
contactChange : BehaviorSubject<string[]> = new BehaviorSubject(this.myString);
getContacts(newContacts) {
// get your data from a webservices & when you done simply next the value
this.contactChange.next(newContacts);
}
}
When you do that every component using your service as a provider will be aware of the change. Simply subscribe to the result like you do with eventEmitter ;)
export Class myComp {
#all the stuff that exists like @Component + constructor using (private myService: myService)
this.myService.contactChange.subscribe((contacts) => {
this.contactList += contacts; //run everytime next is called
}
}
There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.
The compiler will convert the code you have to something like this:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//snip
MyButton.Click += new EventHandler(delegate (Object o, EventArgs a)
{
//snip
});
}
}
use this attribute in style
font-size: 11px !important;//your font size
by !important it override your css
You can use the < !-- [if IE] >
hack to set a global js variable that then gets tested in your normal js code. A bit ugly but has worked well for me.
Here a little program in Python that uses the angle between vectors to determine if a point is inside or outside a certain polygon
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from shapely.geometry import Point, Polygon
from pprint import pprint
# Plot variables
x_min, x_max = -6, 12
y_min, y_max = -3, 8
tick_interval = 1
FIG_SIZE = (10, 10)
DELTA_ERROR = 0.00001
IN_BOX_COLOR = 'yellow'
OUT_BOX_COLOR = 'black'
def angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'
The sign of the angle is dependent on the order of v1 and v2
so acos(norm(dot(v1, v2))) does not work and atan2 has to be used, see:
https://stackoverflow.com/questions/21483999/using-atan2-to-find-angle-between-two-vectors
"""
arg1 = np.cross(v1, v2)
arg2 = np.dot(v1, v2)
angle = np.arctan2(arg1, arg2)
return angle
def point_inside(point, border):
""" Returns True if point is inside border polygon and False if not
Arguments:
:point: x, y in shapely.geometry.Point type
:border: [x1 y1, x2 y2, ... , xn yn] in shapely.geomettry.Polygon type
"""
assert len(border.exterior.coords) > 2,\
'number of points in the polygon must be > 2'
point = np.array(point)
side1 = np.array(border.exterior.coords[0]) - point
sum_angles = 0
for border_point in border.exterior.coords[1:]:
side2 = np.array(border_point) - point
angle = angle_between(side1, side2)
sum_angles += angle
side1 = side2
# if wn is 1 then the point is inside
wn = sum_angles / 2 / np.pi
if abs(wn - 1) < DELTA_ERROR:
return True
else:
return False
class MainMap():
@classmethod
def settings(cls, fig_size):
# set the plot outline, including axes going through the origin
cls.fig, cls.ax = plt.subplots(figsize=fig_size)
cls.ax.set_xlim(-x_min, x_max)
cls.ax.set_ylim(-y_min, y_max)
cls.ax.set_aspect(1)
tick_range_x = np.arange(round(x_min + (10*(x_max - x_min) % tick_interval)/10, 1),
x_max + 0.1, step=tick_interval)
tick_range_y = np.arange(round(y_min + (10*(y_max - y_min) % tick_interval)/10, 1),
y_max + 0.1, step=tick_interval)
cls.ax.set_xticks(tick_range_x)
cls.ax.set_yticks(tick_range_y)
cls.ax.tick_params(axis='both', which='major', labelsize=6)
cls.ax.spines['left'].set_position('zero')
cls.ax.spines['right'].set_color('none')
cls.ax.spines['bottom'].set_position('zero')
cls.ax.spines['top'].set_color('none')
@classmethod
def get_ax(cls):
return cls.ax
@staticmethod
def plot():
plt.tight_layout()
plt.show()
class PlotPointandRectangle(MainMap):
def __init__(self, start_point, rectangle_polygon, tolerance=0):
self.current_object = None
self.currently_dragging = False
self.fig.canvas.mpl_connect('key_press_event', self.on_key)
self.plot_types = ['o', 'o-']
self.plot_type = 1
self.rectangle = rectangle_polygon
# define a point that can be moved around
self.point = patches.Circle((start_point.x, start_point.y), 0.10,
alpha=1)
if point_inside(start_point, self.rectangle):
_color = IN_BOX_COLOR
else:
_color = OUT_BOX_COLOR
self.point.set_color(_color)
self.ax.add_patch(self.point)
self.point.set_picker(tolerance)
cv_point = self.point.figure.canvas
cv_point.mpl_connect('button_release_event', self.on_release)
cv_point.mpl_connect('pick_event', self.on_pick)
cv_point.mpl_connect('motion_notify_event', self.on_motion)
self.plot_rectangle()
def plot_rectangle(self):
x = [point[0] for point in self.rectangle.exterior.coords]
y = [point[1] for point in self.rectangle.exterior.coords]
# y = self.rectangle.y
self.rectangle_plot, = self.ax.plot(x, y,
self.plot_types[self.plot_type], color='r', lw=0.4, markersize=2)
def on_release(self, event):
self.current_object = None
self.currently_dragging = False
def on_pick(self, event):
self.currently_dragging = True
self.current_object = event.artist
def on_motion(self, event):
if not self.currently_dragging:
return
if self.current_object == None:
return
point = Point(event.xdata, event.ydata)
self.current_object.center = point.x, point.y
if point_inside(point, self.rectangle):
_color = IN_BOX_COLOR
else:
_color = OUT_BOX_COLOR
self.current_object.set_color(_color)
self.point.figure.canvas.draw()
def remove_rectangle_from_plot(self):
try:
self.rectangle_plot.remove()
except ValueError:
pass
def on_key(self, event):
# with 'space' toggle between just points or points connected with
# lines
if event.key == ' ':
self.plot_type = (self.plot_type + 1) % 2
self.remove_rectangle_from_plot()
self.plot_rectangle()
self.point.figure.canvas.draw()
def main(start_point, rectangle):
MainMap.settings(FIG_SIZE)
plt_me = PlotPointandRectangle(start_point, rectangle) #pylint: disable=unused-variable
MainMap.plot()
if __name__ == "__main__":
try:
start_point = Point([float(val) for val in sys.argv[1].split()])
except IndexError:
start_point= Point(0, 0)
border_points = [(-2, -2),
(1, 1),
(3, -1),
(3, 3.5),
(4, 1),
(5, 1),
(4, 3.5),
(5, 6),
(3, 4),
(3, 5),
(-0.5, 1),
(-3, 1),
(-1, -0.5),
]
border_points_polygon = Polygon(border_points)
main(start_point, border_points_polygon)
1) Copy DLLs from "Externals\ffmpeg\bin" to your project's output directory (where executable stays); 2) Make sure your project is built for x86 target (runs in 32-bit mode).
Polymorphism is the ability to treat a class of object as if it is the parent class.
For instance, suppose there is a class called Animal, and a class called Dog that inherits from Animal. Polymorphism is the ability to treat any Dog object as an Animal object like so:
Dog* dog = new Dog;
Animal* animal = dog;
This code sends array of integer values
Initialize array List
List<Integer> test = new ArrayList<Integer>();
Add values to array List
test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);
Send the array list values to target activity
intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);
here you get values on targetActivty
Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
or shorter
function sortBy(field) {_x000D_
return function(a, b) {_x000D_
return (a[field] > b[field]) - (a[field] < b[field])_x000D_
};_x000D_
}_x000D_
_x000D_
let myArray = [_x000D_
{tabid: 6237, url: 'https://reddit.com/r/znation'},_x000D_
{tabid: 8430, url: 'https://reddit.com/r/soccer'},_x000D_
{tabid: 1400, url: 'https://reddit.com/r/askreddit'},_x000D_
{tabid: 3620, url: 'https://reddit.com/r/tacobell'},_x000D_
{tabid: 5753, url: 'https://reddit.com/r/reddevils'},_x000D_
]_x000D_
_x000D_
myArray.sort(sortBy('url'));_x000D_
console.log(myArray);
_x000D_
if("123".search(/^\d+$/) >= 0){
// its a number
}
php_flag display_errors on
To turn the actual display of errors on.
To set the types of errors you are displaying, you will need to use:
php_value error_reporting <integer>
Combined with the integer values from this page: http://php.net/manual/en/errorfunc.constants.php
Note if you use -1 for your integer, it will show all errors, and be future proof when they add in new types of errors.
Just update of @bfncs answer
I think around Chrome 43 the behavior was changed a little. You still need to enable Preserve log to see, but now redirect shown under Other tab, when loaded document is shown under Doc.
This always confuse me, because I have a lot of networks requests and filter it by type XHR, Doc, JS etc. But in case of redirect the Doc tab is empty, so I have to guess.
You can always use material button if you are using Material App as your main Widget.
Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Material(
borderRadius: BorderRadius.circular(30.0),//Set this up for rounding corners.
shadowColor: Colors.lightBlueAccent.shade100,
child: MaterialButton(
minWidth: 200.0,
height: 42.0,
onPressed: (){//Actions here//},
color: Colors.lightBlueAccent,
child: Text('Log in', style: TextStyle(color: Colors.white),),
),
),
)
Open cmd type adb shell
then press enter.
Type ls
to view files list.
All you need to do is pass the JspWriter object into your method as a parameter i.e.
void someOutput(JspWriter stream)
Then call it via:
<% someOutput(out) %>
The writer object is a local variable inside _jspService so you need to pass it into your utility method. The same would apply for all the other built in references (e.g. request, response, session).
A great way to see whats going on is to use Tomcat as your server and drill down into the 'work' directory for the '.java' file generated from your 'jsp' page. Alternatively in weblogic you can use the 'weblogic.jspc' page compiler to view the Java that will be generated when the page is requested.
SELECT DATENAME(Quarter, CAST(CONVERT(VARCHAR(8), datecolumn) AS DATETIME))
Set the columns Width
property to be a proportional width such as *
Warning: this will delete your files, make sure you have a backup or can revert the commit.
Delete all elements in repository:
$ git rm -r *
then:
$ git commit -m 'Delete all the stuff'
You can add account in the preference -> Accounts setting.
It seems that you already configure xCode4, then I think you can select your certificates for compiling in project-> Building Setting directly since your certificates are already in your keychain.
Maybe you can take a look at closure in JavaScript. Here is a working solution:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Test</title>_x000D_
</head>_x000D_
<body>_x000D_
<p class="button">Button 0</p>_x000D_
<p class="button">Button 1</p>_x000D_
<p class="button">Button 2</p>_x000D_
<script>_x000D_
var buttons = document.getElementsByClassName('button');_x000D_
for (var i=0 ; i < buttons.length ; i++){_x000D_
(function(index){_x000D_
buttons[index].onclick = function(){_x000D_
alert("I am button " + index);_x000D_
};_x000D_
})(i)_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
OpenJDK is OK for the most cases, but Oracle JDK can be required for some bank client applications (my case) - I can't use OpenJDK.
I'm surprised that I don't see any answer with the default method (repository without external PPAs) in Ubuntu 12.10+ for Oracle's JDK - I will try to describe it.
sudo apt-get install java-package
.tar.gz
archive:
make-jpkg jdk-YOUR_VERSION-linux-PLATFORM.tar.gz
This command will produce a .deb
package.sudo dpkg -i oracle-java8-jdk_8u40_amd64.deb
)It's the officially supported way from Debian developers for installing Oracle JDK, and I suppose it's very simple.
int x=550;
string s=" ";
string y=" ";
while (x>0)
{
s += x%2;
x=x/2;
}
Console.WriteLine(Reverse(s));
}
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
I was also looking for this, but didn't want to impersonate a user to simply acquire a path!
user_path=$(grep $username /etc/passwd|cut -f6 -d":");
Now in your script, you can refer to $user_path
in most cases would be /home/username
Assumes: You have previously set $username
with the value of the intended users username.
Source: http://www.unix.com/shell-programming-and-scripting/171782-cut-fields-etc-passwd-file-into-variables.html
Open MySql workbench.
To take database backup you need to create New Server Instance
(If not available) within Server Administration
.
Steps to Create New Server Instance
:
New Server Instance
option within Server Administrator
.After creating new server instance , it will be available in Server Administration
list. Double click on Server instance you have created OR Click on Manage Import/Export
option and Select Server Instance.
Now, From DATA EXPORT/RESTORE
select DATA EXPORT
option,Select Schema and Schema Object for backup.
You can take generate backup file in different way as given below-
Q.1) Backup file(.sql) contains both Create Table statements and Insert into Table Statements
ANS:
Q.2) Backup file(.sql) contains only Create Table Statements, not Insert into Table statements for all tables
ANS:
Select Skip Table Data(no-data)
option
Select Start Export Option
Q.3) Backup file(.sql) contains only Insert into Table Statements, not Create Table statements for all tables
ANS:
Tables
Panel- select no-create info-Do not write CREATE TABLE statement that re-create each dumped table
option.This opens up something like this
I reached the point that I set, up to max_iter=1200000
on my LinearSVC
classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False
and leaving max_iter
to its default.
With LogisticRegression(solver='lbfgs')
classifier, you should increase max_iter
. Mine have reached max_iter=7600
before the "ConvergenceWarning" disappears when training with large dataset's features.
if you want to create a new repository with the same project inside the github and the previous Remote is not allowing you to do that in that case First Delete That Repository on github then you simply need to delete the .git folder C:\Users\Shiva\AndroidStudioProjects\yourprojectname\.git delete that folder,(make sure you click on hidden file because this folder is hidden )
Also click on the minus(Remove button) from the android studio Setting->VersionControl click here for removing the Version control from android And then you will be able to create new Repository.
One thing you can do is this:
$(this)[0].value = "Something";
This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.
You can create an extension function or just use setCompoundDrawablesWithIntrinsicBounds
directly.
fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}
If you need to resize the drawable, you can use this extension function.
textView.leftDrawable(R.drawable.my_icon, R.dimen.icon_size)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
To get really fancy, create a wrapper that allows size and/or color modification.
textView.leftDrawable(R.drawable.my_icon, colorRes = R.color.white)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int = 0, @ColorInt color: Int = 0, @ColorRes colorRes: Int = 0) {
val drawable = drawable(id)
if (sizeRes != 0) {
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
}
if (color != 0) {
drawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
} else if (colorRes != 0) {
val colorInt = ContextCompat.getColor(context, colorRes)
drawable?.setColorFilter(colorInt, PorterDuff.Mode.SRC_ATOP)
}
this.setCompoundDrawables(drawable, null, null, null)
}
lodash provides a shorthand method to check if undefined or null:
_.isNil(yourVariable)
jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""
def getTargetIds(jsonData):
data = json.loads(jsonData)
for dest in data['to']['data']:
print("to_id:", dest.get('id', 'null'))
Try it:
>>> getTargetIds(jsonData)
to_id: 1543
to_id: null
Or, if you just want to skip over values missing ids instead of printing 'null'
:
def getTargetIds(jsonData):
data = json.loads(jsonData)
for dest in data['to']['data']:
if 'id' in to_id:
print("to_id:", dest['id'])
So:
>>> getTargetIds(jsonData)
to_id: 1543
Of course in real life, you probably don't want to print
each id, but to store them and do something with them, but that's another issue.
The Verilog code compiler you use will dictate what you have to do. If you use illegal syntax, you will get a compile error.
An output
must also be declared as a reg
only if it is assigned using a "procedural assignment". For example:
output reg a;
always @* a = b;
There is no need to declare an output
as a wire
.
There is no need to declare an input
as a wire
or reg
.
In my case even after following all of the above. I had to upgrade my project from .net 3.5 to .net 4 to authorize against our internal exchange 2010 mail server.
If you don't want to deal with @angular/forms
, you can just use an RxJS Subject
with change bindings.
<input [ngModel]='model' (ngModelChange)='changed($event)' />
import { Subject } from 'rxjs/Subject';
import { Component } from '@angular/core';
import 'rxjs/add/operator/debounceTime';
export class ViewComponent {
model: string;
modelChanged: Subject<string> = new Subject<string>();
constructor() {
this.modelChanged
.debounceTime(300) // wait 300ms after the last event before emitting last event
.distinctUntilChanged() // only emit if value is different from previous value
.subscribe(model => this.model = model);
}
changed(text: string) {
this.modelChanged.next(text);
}
}
This does trigger change detection. For a way that doesn't trigger change detection, check out Mark's answer.
.pipe(debounceTime(300), distinctUntilChanged())
is needed for rxjs 6.
Example:
constructor() {
this.modelChanged.pipe(
debounceTime(300),
distinctUntilChanged())
.subscribe(model => this.model = model);
}
Look at the Inner Exception and find out what object might have caused the problem, you might have changed its name.
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
This part has problems:
Card* cardArray;
void Deck() {
cardArray = new Card[NUM_TOTAL_CARDS];
int cardCount = 0;
for (int i = 0; i > NUM_SUITS; i++) { //Error
for (int j = 0; j > NUM_RANKS; j++) { //Error
cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
cardCount++;
}
}
}
cardArray
is a dynamic array, but not a member of Card
class. It is strange if you would like to initialize a dynamic array which is not member of the classvoid Deck()
is not constructor of class Deck since you missed the
scope resolution operator. You may be confused with defining the constructor and the function with name Deck
and return type void
.<
not >
otherwise, loop will never
be executed.Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.
But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.
static {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
// ip address of the service URL(like.23.28.244.244)
if (hostname.equals("23.28.244.244"))
return true;
return false;
}
});
}
If you happen to be using Java 8, there is a much slicker way of achieving the same result:
static {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}
Setting the index name can also be accomplished at creation:
pd.DataFrame(data={'age': [10,20,30], 'height': [100, 170, 175]}, index=pd.Series(['a', 'b', 'c'], name='Tag'))
The last thing on the Laravel Eloquent doc page is:
protected $appends = array('is_admin');
That can be used automatically to add new accessors to the model without any additional work like modifying methods like ::toArray()
.
Just create getFooBarAttribute(...)
accessor and add the foo_bar
to $appends
array.
Change the klik method as follows:
public void klik(object pea, EventArgs e)
{
Bitmap c = this.DrawMandel();
Button btn = pea as Button;
Graphics gr = btn.CreateGraphics();
gr.DrawImage(b, 150, 200);
}
I added binary before the column name and solve the charset error.
insert into tableA values(binary stringcolname1);
I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :
[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.
I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...
is the character entity reference (meant to be easily parseable by humans). 
is the numeric entity reference (meant to be easily parseable by machines).They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.
You can read more about character entity references in the offical W3C documents.
I tried many methods including defined here. What I got is,
Make sure the name of repository is valid. The best way is to copy the link from repository site and paste in git bash.
Make sure you have commited the selected files.
git commit -m "Your commit here"
If both steps don't work, try
git push -u -f origin master
Do not bind to a specific port. Instead, bind to port 0:
sock.bind(('', 0))
The OS will then pick an available port for you. You can get the port that was chosen using sock.getsockname()[1]
, and pass it on to the slaves so that they can connect back.
Many others have provided good info for sleeping. I agree with Wedge that a sleep seldom the most appropriate solution.
If you are sleeping as you wait for something, then you are better off actually waiting for that thing/event. Look at Condition Variables for this.
I don't know what OS you are trying to do this on, but for threading and synchronisation you could look to the Boost Threading libraries (Boost Condition Varriable).
Moving now to the other extreme if you are trying to wait for exceptionally short periods then there are a couple of hack style options. If you are working on some sort of embedded platform where a 'sleep' is not implemented then you can try a simple loop (for/while etc) with an empty body (be careful the compiler does not optimise it away). Of course the wait time is dependant on the specific hardware in this case. For really short 'waits' you can try an assembly "nop". I highly doubt these are what you are after but without knowing why you need to wait it's hard to be more specific.
We might confuse ourselves that a * b is a dot product.
But in fact, it is broadcast.
Dot Product : a.dot(b)
Broadcast:
The term broadcasting refers to how numpy treats arrays with different dimensions during arithmetic operations which lead to certain constraints, the smaller array is broadcast across the larger array so that they have compatible shapes.
(m,n) +-/* (1,n) ? (m,n) : the operation will be applied to m rows
Another way (which avoids extended switch-case statements) is to define arrays of file extensions for similar processing and use a function to check the extension result against an array (with comments):
// Define valid file extension arrays (according to your needs)
var _docExts = ["pdf", "doc", "docx", "odt"];
var _imgExts = ["jpg", "jpeg", "png", "gif", "ico"];
// Checks whether an extension is included in the array
function isExtension(ext, extnArray) {
var result = false;
var i;
if (ext) {
ext = ext.toLowerCase();
for (i = 0; i < extnArray.length; i++) {
if (extnArray[i].toLowerCase() === ext) {
result = true;
break;
}
}
}
return result;
}
// Test file name and extension
var testFileName = "example-filename.jpeg";
// Get the extension from the filename
var extn = testFileName.split('.').pop();
// boolean check if extensions are in parameter array
var isDoc = isExtension(extn, _docExts);
var isImg = isExtension(extn, _imgExts);
console.log("==> isDoc: " + isDoc + " => isImg: " + isImg);
// Process according to result: if(isDoc) { // .. etc }
In my case div position was fixed , adding left position was not enough it started working only after adding display block
left:0;
display:block;
You can also use a call to SCOPE_IDENTITY in SQL Server.
Another way around it that may/may not suit but surely the simplest:
td {
display: table-caption;
}
Git clone is the command you're looking for:
git clone [email protected]:username/repo.git
Update: And this is the official guide: https://help.github.com/articles/fork-a-repo
Take a look at: https://help.github.com/
It has really useful content
You could use remove()
. More information on jQuery remove().
$(this).children("ul").remove();
Note that this will remove all ul
elements that are children.
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.
Here are the options in question :
-T seconds
--timeout=seconds
Set the network timeout to seconds seconds. This is equivalent to specifying
--dns-timeout
,--connect-timeout
, and--read-timeout
, all at the same time.
And for those three options :
--dns-timeout=seconds
Set the DNS lookup timeout to seconds seconds.
DNS lookups that don't complete within the specified time will fail.
By default, there is no timeout on DNS lookups, other than that implemented by system libraries.
--connect-timeout=seconds
Set the connect timeout to seconds seconds.
TCP connections that take longer to establish will be aborted.
By default, there is no connect timeout, other than that implemented by system libraries.
--read-timeout=seconds
Set the read (and write) timeout to seconds seconds.
The "time" of this timeout refers to idle time: if, at any point in the download, no data is received for more than the specified number of seconds, reading fails and the download is restarted.
This option does not directly affect the duration of the entire download.
I suppose using something like
wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run
should make sure there is no timeout before longer than the duration of your script.
(Yeah, that's probably the most brutal solution possible ^^ )
The Easiest way to implement scrollbar using java swing is as below :
Add 'r' in starting of path:
path = r"D:\Folder\file.txt"
That works for me.
this might work for you...
$('.trhideclass1').hide();
<tr class="trhideclass1">
<td>Label</td>
<td>InputFile</td>
</tr>
As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.
For example in firefox preferences:
Notice the last option.
I use Laravel quite a bit and I simply do not believe the numbers it tells me because end-to-end rendering as measured by my browser shows LOWER total time from request to ready.
Further, I get slightly higher numbers on my machine at work, which does execute the page noticeably faster than my machine at home.
I don't know how those numbers are getting calculated, but they are not corroborated by observation, or browser tools like Firebug...
Laravel is not actually all that slow, especially when optimized. It is memory-hungry however. Even a heavy CMS like Drupal which is very slow, appears to have about 1/3rd the memory footprint of a bare bones Laravel request.
Thus to run Laravel in production, I would deploy to memory-optimized servers before CPU-optimized servers.
I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:
import numpy as np
from sklearn import linear_model
from sklearn import svm
classifiers = [
svm.SVR(),
linear_model.SGDRegressor(),
linear_model.BayesianRidge(),
linear_model.LassoLars(),
linear_model.ARDRegression(),
linear_model.PassiveAggressiveRegressor(),
linear_model.TheilSenRegressor(),
linear_model.LinearRegression()]
trainingData = np.array([ [2.3, 4.3, 2.5], [1.3, 5.2, 5.2], [3.3, 2.9, 0.8], [3.1, 4.3, 4.0] ])
trainingScores = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData = np.array([ [2.5, 2.4, 2.7], [2.7, 3.2, 1.2] ])
for item in classifiers:
print(item)
clf = item
clf.fit(trainingData, trainingScores)
print(clf.predict(predictionData),'\n')
Here is how removed special characters.
I simply applied regex
Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters
' Configure the regex object
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)
private boolean current;
public void setCurrent(boolean current){
this.current=current;
}
public boolean hasCurrent(){
return this.current;
}
If you are behind proxy and using eclipse, go to Window Menu --> Preferences --> General --> Network Connections
. Select the Active Providers as 'Manual'.
Under Proxy entries section, click on HTTPS, click Edit and add proxy host & port. If username and password are required, give that as well. It worked for me!
If you want your own chainable clickToggle jQuery Method you can do it like:
jQuery.fn.clickToggle = function(a, b) {_x000D_
return this.on("click", function(ev) { [b, a][this.$_io ^= 1].call(this, ev) })_x000D_
};_x000D_
_x000D_
// TEST:_x000D_
$('button').clickToggle(function(ev) {_x000D_
$(this).text("B"); _x000D_
}, function(ev) {_x000D_
$(this).text("A");_x000D_
});
_x000D_
<button>A</button>_x000D_
<button>A</button>_x000D_
<button>A</button>_x000D_
_x000D_
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
_x000D_
function a(){ console.log('a'); }
function b(){ console.log('b'); }
$("selector").click(function() {
return (this.tog = !this.tog) ? a() : b();
});
If you want it even shorter (why would one, right?!) you can use the Bitwise XOR *Docs operator like:
DEMO
return (this.tog^=1) ? a() : b();
That's all.
The trick is to set to the this
Object a boolean
property tog
, and toggle it using negation (tog = !tog
)
and put the needed function calls
in a Conditional Operator ?:
In OP's example (even with multiple elements) could look like:
function a(el){ $(el).animate({width: 260}, 1500); }
function b(el){ $(el).animate({width: 30}, 1500); }
$("selector").click(function() {
var el = this;
return (el.t = !el.t) ? a(el) : b(el);
});
ALSO: You can also store-toggle like:
DEMO:
$("selector").click(function() {
$(this).animate({width: (this.tog ^= 1) ? 260 : 30 });
});
but it was not the OP's exact request for he's looking for a way to have two separate operations / functions
Note: this will not store the current Toggle state but just inverse our functions positions in Array (It has it's uses...)
You simply store your a,b functions inside an array, onclick you simply reverse the array order and execute the array[1]
function:
function a(){ console.log("a"); }
function b(){ console.log("b"); }
var ab = [a,b];
$("selector").click(function(){
ab.reverse()[1](); // Reverse and Execute! // >> "a","b","a","b"...
});
Create a nice function toggleAB()
that will contain your two functions, put them in Array, and at the end of the array you simply execute the function [0 // 1
] respectively depending on the tog
property that's passed to the function from the this
reference:
function toggleAB(){
var el = this; // `this` is the "button" Element Obj reference`
return [
function() { console.log("b"); },
function() { console.log("a"); }
][el.tog^=1]();
}
$("selector").click( toggleAB );
Try the following commands at first (re-run again if needed):
$ git fsck --full
$ git gc
$ git gc --prune=today
$ git fetch --all
$ git pull --rebase
And then you you still have the problems, try can:
remove all the corrupt objects, e.g.
fatal: loose object 91c5...51e5 (stored in .git/objects/06/91c5...51e5) is corrupt
$ rm -v .git/objects/06/91c5...51e5
remove all the empty objects, e.g.
error: object file .git/objects/06/91c5...51e5 is empty
$ find .git/objects/ -size 0 -exec rm -vf "{}" \;
check a "broken link" message by:
git ls-tree 2d9263c6d23595e7cb2a21e5ebbb53655278dff8
This will tells you what file the corrupt blob came from!
to recover file, you might be really lucky, and it may be the version that you already have checked out in your working tree:
git hash-object -w my-magic-file
again, and if it outputs the missing SHA1 (4b945..) you're now all done!
assuming that it was some older version that was broken, the easiest way to do it is to do:
git log --raw --all --full-history -- subdirectory/my-magic-file
and that will show you the whole log for that file (please realize that the tree you had may not be the top-level tree, so you need to figure out which subdirectory it was in on your own), then you can now recreate the missing object with hash-object again.
to get a list of all refs with missing commits, trees or blobs:
$ git for-each-ref --format='%(refname)' | while read ref; do git rev-list --objects $ref >/dev/null || echo "in $ref"; done
It may not be possible to remove some of those refs using the regular branch -d or tag -d commands, since they will die if git notices the corruption. So use the plumbing command git update-ref -d $ref instead. Note that in case of local branches, this command may leave stale branch configuration behind in .git/config. It can be deleted manually (look for the [branch "$ref"] section).
After all refs are clean, there may still be broken commits in the reflog. You can clear all reflogs using git reflog expire --expire=now --all. If you do not want to lose all of your reflogs, you can search the individual refs for broken reflogs:
$ (echo HEAD; git for-each-ref --format='%(refname)') | while read ref; do git rev-list -g --objects $ref >/dev/null || echo "in $ref"; done
(Note the added -g option to git rev-list.) Then, use git reflog expire --expire=now $ref on each of those. When all broken refs and reflogs are gone, run git fsck --full in order to check that the repository is clean. Dangling objects are Ok.
Below you can find advanced usage of commands which potentially can cause lost of your data in your git repository if not used wisely, so make a backup before you accidentally do further damages to your git. Try on your own risk if you know what you're doing.
To pull the current branch on top of the upstream branch after fetching:
$ git pull --rebase
You also may try to checkout new branch and delete the old one:
$ git checkout -b new_master origin/master
To find the corrupted object in git for removal, try the following command:
while [ true ]; do f=`git fsck --full 2>&1|awk '{print $3}'|sed -r 's/(^..)(.*)/objects\/\1\/\2/'`; if [ ! -f "$f" ]; then break; fi; echo delete $f; rm -f "$f"; done
For OSX, use sed -E
instead of sed -r
.
Other idea is to unpack all objects from pack files to regenerate all objects inside .git/objects, so try to run the following commands within your repository:
$ cp -fr .git/objects/pack .git/objects/pack.bak
$ for i in .git/objects/pack.bak/*.pack; do git unpack-objects -r < $i; done
$ rm -frv .git/objects/pack.bak
If above doesn't help, you may try to rsync or copy the git objects from another repo, e.g.
$ rsync -varu git_server:/path/to/git/.git local_git_repo/
$ rsync -varu /local/path/to/other-working/git/.git local_git_repo/
$ cp -frv ../other_repo/.git/objects .git/objects
To fix the broken branch when trying to checkout as follows:
$ git checkout -f master
fatal: unable to read tree 5ace24d474a9535ddd5e6a6c6a1ef480aecf2625
Try to remove it and checkout from upstream again:
$ git branch -D master
$ git checkout -b master github/master
In case if git get you into detached state, checkout the master
and merge into it the detached branch.
Another idea is to rebase the existing master recursively:
$ git reset HEAD --hard
$ git rebase -s recursive -X theirs origin/master
See also: