text:
Q: Add dropdown to products and display the value on Woocommerce cart I'm having trouble adding a custom dropdown to the cart meta and displaying it in the cart. The code below works for a number field that is also on the single product page, but not for the dropdown for some reason. Does anyone know why?
The code is as follows:
// Dropdowns-in-ends starts here
add_action( 'woocommerce_before_add_to_cart_button', 'func_dropdown_in_ends');
function func_dropdown_in_ends() {
    printf(
        '
I andre enden av tauet<id = id_dropdown_one_end name=dropdown_one_end>
        <select>
        <option value="0">Ingenting</option>
        <option value="250">Øye       250,-</option>
        <option value="350">Sjakkel   350,-</option>
        <option value="400">Spleis    400,-</option>
        </select>
'
    );
}

//Add dropdown_one_end to cart meta when user clicks add to cart
add_filter( 'woocommerce_add_cart_item_data', 'func_add_dropdown_ene_enden', 10, 4 );
function func_add_dropdown_ene_enden( $cart_item_data, $product_id, $variation_id) {
    if( ! empty( $_POST['dropdown_ene_one_end'] ) ) {
        // Add the item data
        $cart_item_data['one_end'] = $_POST['dropdown_one_end'];
    }
    return $cart_item_data;
}

// Show dropdown_one_end in cart
add_filter( 'woocommerce_cart_item_name', 'func_cart_item_name_ene_enden', 10, 3 );
function func_cart_item_name_ene_enden( $name, $cart_item, $cart_item_key ) {
    if( isset( $cart_item['one_end'] ) ) {
        $name .= sprintf(
            '
I ene enden: %s
',
            esc_html( $cart_item['one_end'])
        );
    }
    return $name;
}

EDIT: As I see it the dropdown has an 'option', but also an option value. Do I have to reference them individually to get things to work?

A: There are some errors and mistakes in you code… Try the following code instead (commented):
// Display a custom dropdown in single product pages before add_to_cart button
add_action( 'woocommerce_before_add_to_cart_button', 'display_dropdown_in_ends');
function display_dropdown_in_ends() {
    echo '

        I andre enden av tauet
        <select id ="id_dropdown_one_end" name="dropdown_one_end">
            <option value="0">Ingenting</option>
            <option value="250">Øye       250,-</option>
            <option value="350">Sjakkel   350,-</option>
            <option value="400">Spleis    400,-</option>
        </select>

';
}

// Add dropdown value as custom cart item data, on add to cart
add_filter( 'woocommerce_add_cart_item_data', 'add_dropdown_value_to_cart_item_data', 10, 4 );
function add_dropdown_value_to_cart_item_data( $cart_item_data, $product_id, $variation_id) {
    if( isset($_POST['dropdown_one_end']) && ! empty($_POST['dropdown_one_end']) ) {
        // Add the dropdown value as custom cart item data
        $cart_item_data['one_end'] = esc_attr($_POST['dropdown_one_end']);
        $cart_item_data['unique_key'] = md5(microtime().rand()); // Make each added item unique
    }
    return $cart_item_data;
}

// Cart page: Display dropdown value after the cart item name
add_filter( 'woocommerce_cart_item_name', 'display_dropdown_value_after_cart_item_name', 10, 3 );
function display_dropdown_value_after_cart_item_name( $name, $cart_item, $cart_item_key ) {
    if( is_cart() && isset($cart_item['one_end']) ) {
        $name .= '
'.__("I ene enden:") . ' ' . esc_html($cart_item['one_end']) . '
';
    }
    return $name;
}

// Checkout page: Display dropdown value after the cart item name
add_filter( 'woocommerce_checkout_cart_item_quantity', 'display_dropdown_value_after_cart_item_quantity', 10, 3 );
function display_dropdown_value_after_cart_item_quantity( $item_qty, $cart_item, $cart_item_key ) {
    if( isset($cart_item['one_end']) ) {
        $item_qty .= '
'.__("I ene enden:") . ' ' . esc_html($cart_item['one_end']) . '
';
    }
    return $item_qty;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.
On cart page:

On checkout page:


text:
Q: Converting a datetime string to timestamp in Javascript Question in brief:
What is the easiest way to convert date-month-year hour(24):minute to timestamp?
due to more views add clear question on the top, so that no need to go through background & all if need quick help.

Background :
I have a simple html table and I used jquery sorter to sort my table columns.
Everything is working fine except a date column which is having following format of data,
17-09-2013 10:08
date-month-year hour(24):minute

This column is sorting(alphabetically) but not as I expected(date wise). I tried to use a custom parser as follows,
$.tablesorter.addParser({
    id: 'date_column',  // my column ID
    is: function(s) {
        return false;
    },
    format: function(s) {
        var timeInMillis = new Date.parse(s);
        return timeInMillis;
    },
    type: 'numeric'
});

Problem :
it fails due to new Date.parse(s) .
Question :
what is the easiest way to convert date-month-year hour(24):minute to timestamp? then I can skip var timeInMillis = new Date.parse(s); line.
Thanks
Edited :
Sorry about the confusion about milliseconds, actually it should be the timestamp which is a number that represents the current time and date.

A: Seems like the problem is with the date format.
 var d = "17-09-2013 10:08",
 dArr = d.split('-'),
 ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000

A: Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.
var dateString = '17-09-2013 10:08',
    dateTimeParts = dateString.split(' '),
    timeParts = dateTimeParts[1].split(':'),
    dateParts = dateTimeParts[0].split('-'),
    date;

date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);

console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400

You could also use a regular expression with capturing groups to parse the date string in one line.
var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);

console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]

A: Date.parse() isn't a constructor, its a static method.
So, just use
var timeInMillis = Date.parse(s);

instead of
var timeInMillis = new Date.parse(s);

A: For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:
function convertDate(date) {

    // # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
    var dateTimeParts = date.split(' ');

    // # this assumes time format has NO SPACE between time and am/pm marks.
    if (dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {

        var theTime = dateTimeParts[1];

        // # strip out all except numbers and colon
        var ampm = theTime.replace(/[0-9:]/g, '');

        // # strip out all except letters (for AM/PM)
        var time = theTime.replace(/[[^a-zA-Z]/g, '');

        if (ampm == 'pm') {

            time = time.split(':');

            // # if time is 12:00, don't add 12
            if (time[0] == 12) {
                time = parseInt(time[0]) + ':' + time[1] + ':00';
            } else {
                time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
            }

        } else { // if AM

            time = time.split(':');

            // # if AM is less than 10 o'clock, add leading zero
            if (time[0] < 10) {
                time = '0' + time[0] + ':' + time[1] + ':00';
            } else {
                time = time[0] + ':' + time[1] + ':00';
            }
        }
    }
    // # create a new date object from only the date part
    var dateObj = new Date(dateTimeParts[0]);

    // # add leading zero to date of the month if less than 10
    var dayOfMonth = (dateObj.getDate() < 10 ? ("0" + dateObj.getDate()) : dateObj.getDate());

    // # parse each date object part and put all parts together
    var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;

    // # finally combine re-formatted date and re-formatted time!
    var date = new Date(yearMoDay + 'T' + time);

    return date;
}

Usage:
date = convertDate('11/15/2016 2:00pm');

A: It is just as simple:
   var today = new Date(); // Thu Apr 28 2022 21:51:23 GMT+0530
   var todaysTimestamp = new Date().getTime();   // 1651162883379

redpajama_set_name: RedPajamaStackExchange


text:
Q: New Relic - Query that shows the relationship between APIs and memory consumption in a period does anyone know any query that shows the relationship between APIs and memory consumption in a period?
Example between 2022-10-17 10:00:00 AM and 2022-10-17 11:00:00 AM
 API  | Memory Consumption
__________________________
   X  |  1.5 GB
   Y  |  1 GB
   T  |  0.5 GB

A: A process uses memory. An api can be represented by >1 processes. In the garbage collected world, a process may consume and then release memory as collection cycles are async with api usage. A tool like the infrastructure agent is best placed to monitor the usage of memory for a process, but different languages have different methods of starting Apis so some knowledge of the process/language used for an api may be required.


text:
Q: How to understand DFA (Finite Automata)?
Indicate the state that the DFA will end in after processing each of the following input strings. Note: the input labeled "The empty string" is literally the empty string—a string with no letters in it—not the letters 'T', 'h', 'e', ' ', 'e', and so forth.

For the string = abcba, do I end in state 2?
Also, what is that double circle means?

A: Yes, after abcba, you end in state 2.
The double-circle usually indicates an accepting state -- in the DFA for a regular expression, the string you've received so far matches the regular expression iff you're in an accepting state.
If a regular expression matches the empty string then the start state will also be an accepting state, as is the case here.

A: Good Evening ! yes after reading
 abcba

you wil reach on (2) state..
double circle shows the Final State . i-e shows acceptance of string the Destination
empty string or Lemda is accepted from a DFA it means that initial and final state is same for that DFA (language)


text:
Q: How can I change the SHA256 to SHA1 of apk signer I have apk file signed by SHA256.
Step1) I deleted the sign,
zip -d ./myapp.apk 'META-INF/*'

step2) Check sign was correctly deleted
keytool -list -printcert -jarfile ./myapp.apk

Step3) I re-signed my application with SHA1
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore android.keystore ./my.apk mykey

Step4) Check
keytool -list -printcert -jarfile ./takiyamaAR.apk

However it shows
 MD5:  19:3F:E4:D8:BB:BB:0A:85:85:CB:99:F2:37:54:24:EB
 SHA1: AD:1D:26:E9:A5:74:14:76:F4:EA:36:D2:7F:F6:9E:E9:92:CB:B2:74
 SHA256: A6:07:46:9C:3A:FD:38:A0:7D:9C:35:91:AD:E7:83:3F:AD:C4:84:C1:AE:36:C5:BD:A0:AE:F3:62:D9:8C:57:FF
  Signature algorithm name: SHA256withRSA
 version: 3

It looks like still SHA256.
I surely signed with SHA1 on Step3.
How can I use SHA1 instead of SHA256?


text:
Q: Change Bootstrap badge-danger upon disconnection New to programming and i am fiddeling with something i cant get working.
The issue is:
I vant to change bootstrap badge-danger to badge-success depending on the connection status.
The script i am using is:

With:

The network is: (state unknown)

I have a feeling that the solution is fairly simple. :P
I have tried to place:
Disconnected

On difrent places in the code but no luck.

A:

function updateIndicator() {
  let indicator = document.getElementById('indicator')
  indicator.className = navigator.onLine ? 'badge badge-pill badge-success' : 'badge badge-pill badge-danger';
  indicator.textContent = navigator.onLine ? 'online' : 'offline';
}
<link rel="stylesheet"  href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"/>

The network is: (state unknown)

You can also listen online with windows event
window.addEventListener('online',updateIndicator);
window.addEventListener('offline',updateIndicator);


text:
Q: How to execute external Angular schematic and use its result in subsequent rules? I would like to call Angular's ng-new schematic first, and then my Rule needs to operate on the results.
so something like:
 chain([
                    externalSchematic('@schematics/angular', 'ng-new', options),
                    schematic('someRule', options)
])

but this doesn't work. My rule needs the angular.json ngNew is supposed to create and since that obviously doesn't exist when my rule starts, the the rule fails.
So is there way to wait to accomplish either or the following:
a) wait for the external schematic to complete and then run the other schematic
b) make the 2nd schematic use the tree returned by the 1st schematic?
So like:
chain([
      externalSchematic('@schematics/angular', 'ng-new', options),
      mergeWith(apply(source(/* tree created by ng-new */), [
        schematic('someStuff', options)
      ])
    )])

A: I am not sure why the innitial approach isn't workin for you but you can get the angular-cli.json file content after running the ng-new schematic by using one of the functions provided by the @angular/schematics/utilities/config.d.ts file.
export declare function getWorkspacePath(host: Tree): string;
export declare function getWorkspace(host: Tree): WorkspaceSchema;
export declare function addProjectToWorkspace<TProjectType extends ProjectType = ProjectType.Application>(workspace: WorkspaceSchema, name: string, project: WorkspaceProject<TProjectType>): Rule;
export declare function updateWorkspace(workspace: WorkspaceSchema): Rule;
export declare const configPath = "/.angular-cli.json";
export declare function getConfig(host: Tree): CliConfig;
export declare function getAppFromConfig(config: CliConfig, appIndexOrName: string): AppConfig | null;

In this case, getWorkspace will give you the content of angular-cli.json file.


text:
Q: Azure API Management returns an InternalServerError while PUT'ing a Swagger definition I'm trying to import a Swagger definition via Azure API Managment's REST API following the steps on this blog and the reference documentation. However, I'm getting a 500 error in response, with the body:
{
  "error": {
    "code": "InternalServerError",
    "message": "Request processing failed due to internal error.",
    "details": null
  }
}

My request works for a GET, but not for a PUT. Can anyone point out what's wrong with my request or potential setup issues I should look into?
This is the request I'm sending:
PUT /apis/{app-id}?api-version=2014-02-14-preview&import=true HTTP/1.1
Host: {tenant}.management.azure-api.net
Authorization: SharedAccessSignature uid={uid}&ex={ex}&sn={sn}
Content-Type: application/vnd.swagger.link+json
If-Match: *
Cache-Control: no-cache
{
    "link": "{app}.cloudapp.azure.com:8165/swagger/docs/0"
}

A: "link" value should contain schema, i.e. start with "http://" or "https://". We'll address this issue to provide more meaningful error message.


text:
Q: Nested resources with independent views model name error in Ruby on Rails In routes:
resources :users do
  resources :service_exps
end

user model:
has_many :service_exps

service_exps model:
belongs_to :user

In service_exps controller new action:
def new
  user = User.find(params[:user_id])
  @service_exp = user.service_exps.build
  render :layout => false
end

In service_exps form:
= form_for ([@service_exp.user, @service_exp]), :remote => true do |s|
 .modal-body
  .row
    .span
      = s.label :org_name
      = s.text_field :org_name, :class => "span3"
  .row
    .span
      = s.label :position
      = s.text_field :position, :class => "span3"
  .actions
    = s.submit 'Save',:class => "btn btn-info"

It give error
 undefined method `user' for nil:NilClass

Please give any suggestion to solve this. Thanks!

A: These type of errors are pretty easy to debug. The error msg says everything. You are calling a method (in this case 'user') on a nil object.
Follow these steps:

*

*Find the file and line no from the error msg.

*Find the object which is nil.

*Confirm that the object is initialized properly

A: Firstly:@service_exp = user.service_exps.build will assign an array of objects to @service_exp - due to a user who has_many :service_exps.
In your view, you doing @service_exp.user - calling user on an array of objects which wont work. Something like @service_exp.first.user would though, when calling user on a specific object in the array. Or remove the .user from form_for


text:
Q: App not appear in Notification Center in Setting, only restart the phone works I'm troubled by this problem a long time. Please help me.
When first install my app, I register the notification by this code:
     [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound];

Then my app will appear in Notification Center in Setting.
But when I uninstall my app, then download it from the App Store, open it ,and register the notification, but it will not appear in the Notification Center in Setting, only I reboot the phone.
And I find other apps are ok. Why? What I should do?
Wait for your help. Thanks.


text:
Q: How to copy selected applications one grid view to another gridview could you please guide me, I am going correct way or not??
1.Getting installed applications in 1 st grid view.(Done)
2.select favorite apps from gridview 1 st grid view. (Here im getting array list[whats up,faceboot])(DONE)
3.May I know ,How to bind array list data to another custom grid view.
public void onClick(DialogInterface dialog, int whichButton) {
                    ArrayList<AppList> mArrayProducts = clad.getCheckedItems();
                    String[] outputStrArr = new String[mArrayProducts.size()];
                    //values.add(outputStrArr);
                    Toast.makeText(getApplicationContext(),"Selected Items:"+mArrayProducts,Toast.LENGTH_LONG).show();
                }
Can u please help me.

A: List<String> mArrayProducts = clad.getCheckedItems();
final QuickLinksGridViewAdaptor selected_apps = new QuickLinksGridViewAdaptor(HomeActivity.this, mArrayProducts);
gv_shortcut.setAdapter(selected_apps);


text:
Q: C# how to change a int number in the text file The text file format is this
11.11.15/8.00pm;Movie1;30
i want to change the the last int number and save the text file when someone purchase the movie ticket.
This is how I print out the information on the text file
public static void nowShowing()
        {

            Console.WriteLine("Date/time\tMovie\tSeats left");
            foreach (var seat in File.ReadLines(@"C:\test.txt").Skip(1).Select(x => new MovieSeat(x)))
                Console.WriteLine(string.Join("\t", seat.Date, seat.Name, seat.Number));

        }

A: Something like the below will give you the ability to decrement your availability.
internal class MovieEntryParser
{
    internal static string DecrementAvailability( string input )
    {
        string[] details = input.Split( ';' );

        // relevant error checking

        int availability = int.Parse( details[ 2 ] ); // use try parse

        availability--;

        return string.Format( "{0};{1};{2}", details[ 0 ], details[ 1 ], availability );
    }
}


text:
Q: $f$ is differentiable when $f^2$ is differentiable My textbook claims that for a continuous function $f$, if $f^2$ is differentiable, then $f$ is differentiable at x whenever $f(x) \neq 0$. The claim is given without proof. I also found the following question on math stack exchange that makes the same claim.
Can someone help me by pointing to a proof (or give a proof)?

A: Suppose $f(x_0) \ne 0$. Then $f(x) \ne 0$ for $x$ near by $x_0$, since f is continuous. Now we have
$$\frac{f(x)-f(x_0)}{x-x_0}=\frac{f^2(x)-f^2(x_0)}{x-x_0}\frac{1}{f(x)+f(x_0)}$$
for $x$ near by $x_0$.

A: $$\displaystyle\frac{f(a+h)-f(a)}h=\frac{f^2(a+h)-f^2(a)}{h(f(a+h)+f(a))}$$
$$\displaystyle ⇒\frac{(f^2(a))'}{2f(a)}$$
by $\displaystyle (f^2(a))'=2f(a)f'(a)$
Then
$$\displaystyle \frac{f(a+h)-f(a)}h=f'(a)$$
So If $f^2(x)$ is differentiable, $f(x)$ is differentiable, too.


text:
Q: CSS 3D Carousel Elements Don't Respect TranslateZ Why doesn't the center element (with the lowest translateZvalue) always appear on top?
http://codepen.io/robgordon/pen/BKzVOp

hello

hello

hello

$height: 200px;

.carousel {
  display: block;
  position: relative;
  width: 100%;
  height: $height;
  perspective: 800px;
}

.item {
  height: $height;
  width: 50%;
  display: block;
  position: absolute;
  transform-style: perspective-3d;
  transition: all 500ms linear;
  backface-visibility: hidden;

  &:nth-child(1) {
    background: red;

  }
  &:nth-child(2) {
    background: green;

  }
  &:nth-child(3) {
    background: blue;

  }

  &.one {
    transform: translateX(0%) translateZ(-100px);
  }
  &.two {
    transform: translateX(50%) translateZ(0px);
  }
  &.three {
    transform: translateX(100%) translateZ(-100px);
  }
}

Number.prototype.mod = function(n) {
    return ((this%n)+n)%n;
};

setInterval(function() {
  var left = $('.one'),
    center = $('.two'),
     right = $('.three');
  $(left).removeClass('one').addClass('two');
  $(center).removeClass('two').addClass('three');
  $(right).removeClass('three').addClass('one');
}, 2000);

A: perspective-3d isn't a valid value for transform-style; it should be preserve-3d, and this should go on the container, in your case .carousel

Number.prototype.mod = function(n) {
    return ((this%n)+n)%n;
};

setInterval(function() {
  var left = $('.one'),
    center = $('.two'),
     right = $('.three');
  $(left).removeClass('one').addClass('two');
  $(center).removeClass('two').addClass('three');
  $(right).removeClass('three').addClass('one');
}, 2000);
.carousel {
  display: block;
  position: relative;
  width: 100%;
  height: 200px;
  perspective: 800px;
  transform-style: preserve-3d; /* <---- need this on container for 3d */
}

.item {
  height: 200px;
  width: 50%;
  display: block;
  position: absolute;
  /* transform-style: perspective-3d; <---- not valid value */
  transition: all 500ms linear;
  backface-visibility: hidden;
}

.item:nth-child(1) {
    background: red;

  }
.item:nth-child(2) {
    background: green;

  }
.item:nth-child(3) {
    background: blue;

  }

.item.one {
    transform: translateX(0%) translateZ(-100px);
  }
.item.two {
    transform: translateX(50%) translateZ(0px);
  }
.item.three {
    transform: translateX(100%) translateZ(-100px);
  }

hello

hello

hello


text:
Q: Haskell: Unexpected output for expression [0, 0.1 .. 1] When evaluating the expression:
*main> [0, 0.1 .. 1]

I was actually expecting:
 [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]

But I was quite shocked to see the output be
[0.0,0.1,0.2,0.30000000000000004,0.4000000000000001,0.5000000000000001,0.6000000000000001,0.7000000000000001,0.8,0.9,1.0]

Why does Haskell produce that result upon evaluation?

A: Refer to this other post.  As it states, floating point numbers aren't precise in the CPU.

A: This is a result of the imprecision of floating point values, it isn't particular to Haskell.  If you can't deal with the approximation inherent in floating point then you can use Rational at a high performance cost:
> import Data.Ratio
Data.Ratio> [0,1%10.. 1%1]
[0 % 1,1 % 10,1 % 5,3 % 10,2 % 5,1 % 2,3 % 5,7 % 10,4 % 5,9 % 10,1 % 1]

Just to hammer the point home, here's Python:
>>> 0.3
0.29999999999999999

And here's C:
void main() { printf("%0.17f\n",0.3); }

$ gcc t.c 2>/dev/null ; ./a.out
0.29999999999999999


text:
Q: Cannot find MySQL when trying to load a database I'm trying to load a database into MySQL. I'm on a Mac, and I can see the MySQL server running in the system preferences. Also, when I issue the shell command mysql I'm entered into the interactive mode of mysql. However, when I try to load a database from the shell:
mysql -f --user root --password mypassword < database.sql

it gives me back zsh: command not found: mysql. Putting sudo in front does not make a difference. How can this be?


text:
Q: Is there an idiom that means "the more powerful you are the more enemies you have" or something similar? It's difficult to find an idiom on Google for a certain idea, but I honestly couldn't find anything even after looking for idioms and a keyword like "power".

A: There's a saying with a similar meaning:

The harder they come, the harder they fall.

This means that the more force you use against someone or something, the more you'll suffer in the end. Or another interpretation might be that it's dangerous to wield a lot of power because it can be turned against you.


text:
Q: Comparing ArrayList String element in jstl 1.2 I'm trying to create a table, where when the "key" is equal to "name", the value is a link to another page otherwise it should print the value as text.I have the following keys: [name, category, schema]. It's an ArrayList
<c:when test='#{(results.keys.get(loopVal.index)).equals("name")}'>

In my table the column "name" should have values as a link. But it doesn't work, as if the c:when returns false. But i checked "results.keys.get(loopVal.index)" and it prints the keys correctly.
I have tried comparing with equals(), with ==, and eq. I also have the correct jstl library     xmlns:c="http://java.sun.com/jsp/jstl/core"
I can't find the problem, maybe it has something to do with comparing a list element? or am I overlooking something really obvious?
Here is a larger snippet of my code:
<ui:repeat value="#{results.keys}" var="key" varStatus="loopVal">
                <td id="#{results.keys.get(loopVal.index)}_#{instance.getId()}" class="view">
                <c:choose>
                    <c:when test='#{(results.keys.get(loopVal.index)).equals("name")}'>
                        <h:link value="#{values.get(loopVal.index)}" outcome="search">
                        <f:param name="type" value="#{values.get(loopVal.index)}" />
                    </h:link>
                    </c:when>
                    <c:otherwise>
                        #{values.get(loopVal.index)}
                    </c:otherwise>
                </c:choose>
                </td>
            </ui:repeat>

A: You should use c:forEach instead of ui:repeat:
<c:forEach items="#{results.keys}" var="key" varStatus="loopVal">
...
</c:forEach>

Have a look at this post by BalusC about the difference between tag handlers (like c:forEach) and normal JSF components (like ui:repeat).


text:
Q: Good Practices for Web Development Project Management I realize that the phrase "good practices" is a bit dubious and overused, but I think it applies to my question.
I have some good web development experience, but I would like to hear what are some good basic practices when doing freelance work vis-à-vis project management.
For example, I have the target domain, mydomain.com. Should I do all of my testing at a subdomain, i.e. dev.mydomain.com, protected by .htaccess or some other means?
I am familiar with SVN, but not for web development. What's the best way to version control a website?
I have set up two databases, mydb_dev and mydb_rel. Does it make sense to do all of my work on _dev then transfer the structure to _rel? What happens after the first release?
If you can answer some of these questions or link me to a good resource it would be great. My searches so far have only yielded HTML tutorials!

A: What I would generally suggest is the following. The team should have 3 kind of "deploy" environments:

*

*development environment: This is where developers work and can publish

*test environment: This is where tests are done, also showing possibly to the customer. Only working products should be deployed here.

*production environment: The final deployment of the running and used product

Here's something that treats this concept. What I would suggest is that the "test environment" (or pre-release environment) lies on the same server with the same configuration as the final "production environment".
To what concerns version control I would use it just for versioning source code. You can use whatever version control (or even configuration management tool) you like. Here it is a good practice to do branching, so whenever you release a product (deploy it to the production environment) you create a branch with a corresponding version number to it. In parallel you continue to develop on the main branch. This has the advantage that you can do possible bugfixing that may happen to your release and you can redeploy the branched copy without redeploying new features that in the mean time have been added on the main development branch. Search the web for best practices on branching, there is a lot of stuff around. I wouldn't however use SVN or something for versioning your website directly..at least I've never heard of such a practice. Better way would be to create backup copies of your production environment in a daily fashion on the server somehow...

A: What we do.

*

*Use a framework that allows testing outside a deployed web server.  We develop and test on laptops.  Some folks use Glassfish running under Eclipse for testing.  Other use Django, which runs stand-alone.  We have databases on our laptops for development and testing.  We use configuration files to be sure that we're using the "development" names for databases, directories, etc.

*Do integration testing on a VM.  Our hosting is Red Hat Enterprise Linux-based, so we have Fedora VM's that we use for testing with Apache and MySQL (or Oracle) and that whole technology stack.  We have integration test databases in the VM environment.  We use configuration files to be sure that we're using the "test" names for databases, directories, etc.

*We use products that have very tidy deployment.  Glassfish/Java applications are deployed with WAR or EAR files.  Django applications use Python's setup.py installer.  That way we can install into production, fiddle with the database, and we're up and running.  We use configuration files to be sure that we're using the "production" names for databases, directories, etc.
The first release involves building the database the first time.  We provide a script (or in the case of Django, we run the manage.py syncdb command) to build the database.
When making schema changes, we either have scripts or instructions.  We have to do it in test and again in production.
When deploying to the visible to the world production, we do this.

*

*We have a VM in our hosting environment that's "staging".  We get this to work.  It's not visible to the internet.   We checkout our components, install them, run the DB schema change script (or do the manual steps if it's complicated).  Usually, we work on a copy of the production database.

*We then clone that VM to create the production VM.  We change the production configuration to use the upgraded copy of the production database.
We don't have a database named "prod", that's hard to work with.  We have "prod_3" in production, "prod_4" in staging when we're doing our upgrade.  Then we change the configuration file to use "prod_4".  "prod_3" can hang around until we need the disk space to create "prod_5".

A: A few tips I've found helpful in my own work:

*

*I maintain a personal wiki page for each project that contains all project-related data. Since it's just for my personal consumption, I can organize each one organically as needed.

*Keep a questions log (on the wiki page or elsewhere) that crop up throughout the course of the project. Rather than bombarding your client with random emails or accidentally forgetting to ask a question in a timely fashion, keeping a log will let you send one coherent and compiled email every few days with project-related questions.

*Do all development locally (MAMP, XAMPP, etc). This way your client is never accessing the website when you're working on it, therefore bypassing unnecessary confusion (why I am getting blank screens now?!? They were working 5 minutes ago!!).

*Push from local development to your staging server via Capistrano. This can be done again for production. Much easier to keep track of any build scripts (minifiying JS, for example) and is much more efficient than FTP

*Use SVN to manage all assets - content, templates, comps, your working site, database exports, etc. A well-organized repo won't get out of hand if you set it up right from the start. Never hurts having an extra backup, even if you know you're never going to touch a file again.

A: As for version control, I'd say put everything under control that isn't dynamically created. For example, if you're application generates a bunch of .txt files on the fly, you don't need to version those, but anything that is created just once, needs to be under version control.
As for your choice of version control system, I'd recommend something other than SVN (probably Git or Mercurial), but that's more just my personal preference than any substantial reason.


text:
Q: Exit Function Not Working - VBA I am trying to exit the function if either the value is equal to the value I'm looking for, or if the row is equal to the row I'm looking for.
But every time I use Exit Function, it doesn't work. And if I replace it with End Function it tells me that I don't have an End to my If statement. And I'm getting lost.
Function recursion(whereItEnds As Integer, lookingFor As Variant, currentMarker As Range, I As Integer, wsEverything As Worksheet) As Integer
    Dim col As Integer
    Dim newMarker As String
    newMarker = currentMarker.Value
    Dim currentMarker1 As Range
    recursion = 2
    col = 2
    If (StrComp(lookingFor, newMarker, vbTextCompare) = 0) Then
        Exit Function
    End If

    While (IsEmpty(wsEverything.Cells(col, "B").Value) = False)
        If (StrComp(wsEverything.Cells(col, "B").Value, newMarker, vbTextCompare) = 0) Then
            wsEverything.Cells.Range("A" & col, "F" & col).Copy
            Worksheets("Review").Cells.Range("A" & I).PasteSpecial
            Worksheets("Review").Cells.Range("G" & I).Value = col
            I = I + 1
            Set currentMarker1 = wsEverything.Cells(col, "E")

            If (col = whereItEnds) Then
                Exit Function
            End If
            recursion = recursion(whereItEnds, lookingFor, currentMarker1, I, wsEverything)
        End If
        col = col + 1
    Wend
End Function

I'm almost completely out of ideas as to why neither works.
EDIT: It hits the if statements, it goes into those codes. but when debugging, it touches "exit function" but then it just keeps going. i just want it to end the statement. This is pulling data off another long sheet and putting it on a second sheet. it is checking for child parent circular errors. where a parent in the future is dependent on the child that originally was dependent on it.

A: Is this what you want?
Before (Sheet1):

After (Review Sheet):

Option Explicit

Public Sub TestRecursion()

    Dim result As Variant, ws As Worksheet

    Set ws = Sheet1

    result = Recursion(ws.Cells(2, 8), ws.Cells(2, 2), ws.Cells(2, 5), 2, ws)

End Sub

Public Function Recursion(ByVal whereItEnds As Long, lookingFor As Variant, _
                          ByRef currentMarker As Range, ByVal i As Long, _
                          ByRef wsEverything As Worksheet) As Long

    Dim col As Long, newMarker As String, currentMarker1 As Range

    newMarker = currentMarker.Value
    Recursion = 2
    col = 2

    If StrComp(lookingFor, newMarker, vbTextCompare) = 0 Then Exit Function

    While Len(wsEverything.Cells(col, "B").Value2) > 0

        If StrComp(wsEverything.Cells(col, "B").Value2, newMarker, vbTextCompare) = 0 Then

            wsEverything.Cells.Range("A" & col, "F" & col).Copy
            Worksheets("Review").Cells.Range("A" & i).PasteSpecial
            Worksheets("Review").Cells.Range("G" & i).Value = col
            i = i + 1

            Set currentMarker1 = wsEverything.Cells(col, "E")

            If col = whereItEnds Then Exit Function

            Recursion = Recursion(whereItEnds, lookingFor, currentMarker1, i, wsEverything)
        End If
        col = col + 1
    Wend
End Function

If so, you can provide more context explaining the logic for the expected result
Probably a less convoluted solution can be found for this


text:
Q: Find the last column of a sheet using the sheets variable name I'm trying to use a variable named sheet to find the last column of this sheet. My formula seems to work if I name the sheet but doesn't when I use the variable name to reference it.
Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")

Dim LastCol As Integer

''-------------------------------------------------''

LastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
MsgBox LastCol

This should result in column 8 being displayed but for some reason is returning 1. If I replace the 'ws' with the actual name of the sheet (as below) it works correctly.
LastCol = Worksheets("Sheet1").Cells(1, Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column

I'm confused as to why this isn't showing the same result.

A: Three possible solutions:
Option Explicit

Sub test()

    Dim LastColumn As Long
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Sheet1")

    'Method 1
    With ws
        LastColumn = .Cells(7, .Columns.Count).End(xlToLeft).Column '<- Change number save to the row number you want to get the last column
    End With

    'Method 2
    With ThisWorkbook.Worksheets("Sheet1")
        LastColumn = .Cells(7, .Columns.Count).End(xlToLeft).Column
    End With

    'Method 3
    LastColumn = ThisWorkbook.Worksheets("Sheet1").Cells(7, ThisWorkbook.Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column

End Sub


text:
Q: Escaping single quote in stored oracle procedure I have a stored procedure which reads value from the table and then using update query it appends a prefix in it and update the table.
But the issue that I am getting the value in table contains single quote(') so when I use it in update query is not working.
How can I escape this single quote by two single quotes?
Briefly I want to check...:
 1. if single quote exists in the value fetched from table.
 2. if yes, then replace single quote with double quote else do nothing
How can this be achievd?

A: To escape a single ' you use another '. For example a string containing a single ' looks like this:
''''

Two ' as start and finish of the string and a ' to escape the ' you actually want.
Similar question:
How to handle a single quote in Oracle SQL


text:
Q: AutoMapper Flattening an Extension method I'm looking for the simplest / most elegant way to flatten a source object utilizing extension methods of the source object.
Source:
class Source
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
}

Extension method I'd like to elegantly map:
static class SourceExtensions
{
    public static int GetTotal(this Source source)
    {
        return source.Value1 + source.Value2;
    }
}

Destination:
class Destination
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public int Total { get; set; }
}

Is there a better way than this (one where I don't have to call out every extension method)?
using NamespaceContainingMyExtensionMethods;
...
Mapper.CreateMap<Source, Destination>()
    .ForMember(destination => destination.Total,
        opt => opt.ResolveUsing(source => source.GetTotal()));

Something like:
Mapper.CreateMap<Source, Destination>()
    .ResolveUsingExtensionsInNamespace("NamespaceContainingMyExtensionMethods");

I know I can use an inheritance heirarchy on the source objects, but in my situation, it isn't ideal.
I've researched:
Does AutoMapper's convention based mappings work with LINQ extension methods? and https://github.com/AutoMapper/AutoMapper/issues/34

A: Added commit to my fork and make a pull request for this. Works like a charm!
commit: https://github.com/claycephus/AutoMapper/commit/e1aaf9421c63fb15daca02607d0fc3dff871fbd1
pull request: https://github.com/AutoMapper/AutoMapper/pull/221
Configure it by specifying assemblies to search:
Assembly[] extensionMethodSearch = new Assembly[] { Assembly.Load("Your.Assembly") };
Mapper.Initialize(config => config.SourceExtensionMethodSearch = extensionMethodSearch);
Mapper.CreateMap<Source, Destination>();

A: Clay stuff is still there but it has been refactored over time.  For those searching for this in automapper, you should use:
var config = new MapperConfiguration(cfg => {
    cfg.IncludeSourceExtensionMethods(typeof(SourceExtensions));
    cfg.CreateMap<Source, Destination>();
});
var mapper = config.CreateMapper();


text:
Q: Delete directory on clean I have a C#/TypeScript project which uses webpack to bundle the TypeScript code into a directory bundles.
The directory bundles is created by webpack, which is triggered as a post-build event on the project.
I would like the bundles directory (or all of its children) to be deleted when I clean the project or solution. How can I do this?

A: User CleanPlugin for webpack. Here is my config for my server side code in node (see the plugins section uses clean-webpack-plugin):
plugins: [
    new CleanPlugin([ buildPath ], { root: projectRootPath }),
    // rest of plugins
],

The whole config
var webpack = require("webpack");
var path = require("path");
var CleanPlugin = require('clean-webpack-plugin');

var projectRootPath = path.resolve(__dirname, '../');
var buildPath = path.join(projectRootPath, './build');

module.exports = {
  target: "node",
  cache: false,
  context: projectRootPath,
  devtool: "source-map",
  entry: [ "./server/server.prod.js" ],
  output: {
    path: path.join(__dirname, "../build"),
    filename: "server.prod.js"
  },
  plugins: [
    new CleanPlugin([ buildPath ], { root: projectRootPath }),
  ],
  module: {
    rules: [
      { test: /\.js$/, enforce: "pre", loader: 'eslint-loader', exclude: /node_modules/ },
      {
        test: /\.js$/,
        enforce: "post",
        exclude: /node_modules/,
        use: [ { loader: 'babel-loader' } ]
      }
    ]
  },
  externals: nodeModules, // nodeModules is an array variable
  resolve: {
    modules: [
      path.resolve('./server'),
      path.resolve('./client'),
      path.resolve('./node_modules')
    ],
    extensions: [ ".json", ".js" ]
  }
};


text:
Q: Permute transposition and derivative + Norm question I have two questions:

*

*In general, what are the conditions to permute transposition  and derivative:
$$[x^{\prime}(t)]^{T}=[x^{T}(t)]^{\prime}$$

*Is it correct to writ:  $\quad$ $\mathbb{R}^{n}=\mathbb{M}_{n}(\mathbb{R}).\mathbb{R}^{n}$
so if: $\quad$ $x=Py$
then  $\quad$$\|x\|_{\mathbb{R}^{n}}=\left\|P y\right\|_{\mathbb{R}^{n}}<\|P\|_{\mathbb{M}_{n}}\|y\|_{\mathbb{R}^{n}}$
Thank you for your justifications and explanations

A: *

*In finite dimensional row and column vectors, transposition is linear (and bounded, continuous) and limits interchange with this operation. In more general vector spaces, you would have to define what transposition or something similar is, and in rare situations that operation might not be bounded=continuous.

*Yes. As long as the matrix norm is associated to the vector norm. There are many different vector space norms and associated and unassociated matrix norms, and not for every combination do you get that inequality (which is not strict in general for the standard situation of associated norms).


text:
Q: Solving: Monitor settings default not compatible with laptop screen with Linux Mint Live DVD I am talking a friend through the process of installing linux on his laptop. He chose mint as he liked the look of the GUI. However when he ran the live DVD he saw this:

I recognise that this is a screen default incompatibility but without hands on access I am not sure what to suggest to him. If I was physically present I would be happy to poke about at stuff, or even to customise the live DVD any way that you might care to suggest. However, I will need to talk my friend through whatever fix we come up with which means I need to be able to explain it over the phone and he (not an expert) needs to be able to then do it.
What is the least complex solution to this problem?
Are there bios settings or some other minor edits that can be carried out to the ISO image?


text:
Q: Microsoft Graph Subscriptions - Exchange Online resources are not supported for MSA requests I think I have sort of the same problem as Microsoft Graph Subscriptions - Method not Allowed and the question is answered and there is this comment Microsoft Graph Subscriptions - Method not Allowed
Request https://graph.microsoft.com/v1.0/subscriptions
{
   "changeType": "created,updated,deleted",
   "notificationUrl":"https://c5e719ba.ngrok.io/api/ms/watch",
   "resource": "me/events",
    "expirationDateTime":"2016-12-07T02:23:45.9356913Z",
}

Response Header
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: application/json
Server: Microsoft-IIS/8.5
request-id: 9bd7a103-5ec0-4ed5-b20d-f8fb4cc75b88
client-request-id: 9bd7a103-5ec0-4ed5-b20d-f8fb4cc75b88
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"North Europe","Slice":"SliceA","ScaleUnit":"000","Host":"AGSFE_IN_4","ADSiteName":"DUB"}}
Duration: 261.5354
X-Powered-By: ASP.NET
Date: Tue, 06 Dec 2016 23:11:45 GMT

Response
{
    "error": {
        "code": "",
        "message": "Exchange Online resources are not supported for MSA requests.",
        "innerError": {
            "request-id": "9bd7a103-5ec0-4ed5-b20d-f8fb4cc75b88",
            "date": "2016-12-06T23:11:46"
        }
    }
}

But I'm not sure what should I do to make it work, I'm not using azure, but it seems that if I use Azure Active Directory B2C it should work, if this is what I really must do I think it's a hassle not being able to use all the microsoftgraph without using an azure service. (I can live without getting the profile photo This operation in version 1.0 supports only a user's work or school mailboxes and not personal mailboxes.).
I don't have an office365 account so I don't know if this won't be a problem if the user that uses my application sign in with an office 365 account.. because if it works with a home/commercial account I could verify if the account it's from MSA or home/commercial as a workaround I could do something like this https://github.com/microsoftgraph/msgraph-sdk-android/issues/26 and if I know that it's an MSA account I could ask the user to use another account in order to use the app...
So the question is: in order to make it work with a MSA (live) account do I've to use Azure Active Directory B2C?

A: Edit: Subscriptions for MSA (Live accounts) can now be created on the graph "beta" version for "me/messages" and "me/contacts".
We also support such MSA/live subscriptions for OneDrive resources like "me/drive/root".


text:
Q: How do I know If client wants to send the data or recieve the data from server when I am trying to send the data from the server, my client side is not able to receive the data. The server is able to write the data to the JSON file. I think because I am executing the code for sending and receiving the data on the server inside the main method every time regardless of what request I am receiving from the client. Is there any built-in method in Java that helps us know what the client request is and execute the codes on the server depending on the request rather than executing the code for both read and write request. I hope You guys understand.
public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = new ServerSocket(666);
    FileReader fileReader = new FileReader("MYJSON.json");
    BufferedReader buff = new BufferedReader(fileReader);

  while(true) {
     Socket socket = serverSocket.accept();

      InputStreamReader inputStreamReader = new
      InputStreamReader(socket.getInputStream());
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String str = bufferedReader.readLine();
      writeJson(str);

        String str;
        OutputStreamWriter outputStreamWriter = new
        OutputStreamWriter(socket.getOutputStream());
        PrintWriter printWriter = new PrintWriter(outputStreamWriter);
        str = buff.readLine();
        printWriter.write(str);
        printWriter.flush();
        printWriter.close();

     }
    }


text:
Q: How my bot can ask to users or bot need reply from users to send message intelegraf node.js bot? bot.command("greeting", (ctx) => ctx.reply("Hello users, what's your name?");

ctx.reply("Hello Alex nice to meet you!")

A: No matter which social bot you are using (viber, telegram, telegraf etc) it requires user to be subscribed on its incoming list and then you will be able to use ctx.message.chat.id to send message on specific registered user.
telegraf example:
bot.on('text', (ctx) => {
  // Explicit usage
  ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`)

  // Using context shortcut
  ctx.reply(`Hello ${ctx.state.role}`)
})

Moreover if there is a first time a user is sends a word to bot, there is a need to do the following.
bot.hears('/Hi', (ctx)=> ctx.reply('Hello ' + getName(ctx.message.from))

function getName(user) {
    return user.first_name || user.last_name;
}

If the bot receives a "Hi" it will reply with "Hello -user name-"


text:
Q: python: logging:: get the current time in a custom timezone I am trying the following code to log using the timezone 'America/New_York'
the time is shown correct, but the %z and %Z are not showing the right time Zone
from datetime import datetime
from pytz import timezone
import logging

def timetz(*args):
    tz = timezone('America/New_York')
    print(tz)
    dt = datetime.now(tz)
    print(dt)
    return dt.timetuple()

logger = logging.getLogger()

formatter = logging.Formatter(fmt='%(asctime)s::%(levelname)-8s\n%(message)s',datefmt='%Y-%m-%d %H:%M:%S %p %Z %z')
formatter.converter = timetz
formatter.default_msec_format = '%s.%03d'

handler= logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
logger.error('test')

I get
2021-03-05 14:53:04 PM UTC +0000::ERROR
test

But i should get
2021-03-05 14:53:04 PM EST -0500::ERROR
test

The %z and %Z are not working


text:
Q: Implementation Add Connection of Visual Studio I want to create Connect To DataBase form(Something like Visual Studio 2012 Add Connection
I find this code to find Connected server
  private void FillServerComboBox()
    {
            DataTable ServersTable = new DataTable();
            SqlDataSourceEnumerator servers = SqlDataSourceEnumerator.Instance;
            ServersTable = servers.GetDataSources();

            object[] obj = new object[ServersTable.Rows.Count];
            for (int i = 0; i < ServersTable.Rows.Count; i++)
            {
                obj[i] = string.Format("{0}\\{1}", ServersTable.Rows[i]["ServerName"].ToString(), ServersTable.Rows[i]["InstanceName"].ToString());
            }
            serversComboBox.DataSource = obj;
    }

And I find "Master.dbo.sp_Databases" procedure to list databases on remote server. But I do not have permission on MasterTable. How does "Add Connection Form" work on Visual Studio?
But it does not work. Please guide me on that!

A: I found an asnwer
      SqlConnection _SqlConnection = new SqlConnection(ConnectionString);
        _SqlConnection.Open();
        DataTable dt1 =   _SqlConnection.GetSchema("Tables");

and
      SqlConnection _SqlConnection = new SqlConnection(ConnectionString);
        _SqlConnection.Open();
        DataTable dt1 =   _SqlConnection.GetSchema("DataBases");


text:
Q: What was the implication of Quaternions in modern (21th) physics and usage in electrodynamics in 19th century? I'm doing a study about number theory in physics where I put some focus into the usage of Quaternions.  See: https://en.wikipedia.org/wiki/Quaternion#Use_in_physics
Right now I conclude that the quaternion carried the fundamental implication towards the space-time structure in GR minkowski space.
However, I also read that the quaternions had an important role in electrodynamics in the 19th century before the appearance of Maxwell equation.
My question was that:

*

*Could you tell my why quaternions were so important for electrodynamics before maxwell?

*I read that as the advancing of modern physics, the role of quaternions had become a little bit "fading away", could you explain a bit why that was the case?

*What's the popular view of quaternions in recent year? Do we have a more fundamental understanding towards it?


text:
Q: Problem with dynamic scroll views iphone I was looking for an answer to my problem all over the net but with no succes. I am using a view with a toolbar with 3 buttons. In a view is a scrollview. Whenever i tap one of the buttons, scrollview is populated with a number of labels and textviews with dynamic size and position. depending on the ammount of text that was parsed. The size of scroll view (height) is also dynamicly changed depending on the size of its subviews. It all works good when i just switch toolbar buttons without previously scrolling the view. But if i scroll a view to the bottom, and then by clicking button i change positions and size of text and labels, the scrollview is acting strange and is not returning to its previous position (content offset 0, 0). I was wondering if there is a good waz to make this work more smootly. Thanks!

A: Why don't you simply set the contentOffset of the scroll view at the same time you are settings its new content, i.e.
// populate your scrollView and set its contentSize
// ...
[yourScrollView setContentOffset:CGPointZero animated:YES];


text:
Q: Take a List as an Input in socket programming I want to receive a List as input, Java is showing me no error in:
List<String> A;
 ObjectOutputStream ins = new ObjectOutputStream(soc.getOutputStream());
  ins.writeObject(A);

The above code executes without error, however this doesn't:
List<String> ls;
    ObjectInputStream in = new ObjectInputStream(soc.getInputStream());
       in.readObject(ls);

If I can send a List<>, why cant I accept it? Any reasons and suggestions for the output code?

A: readObject doesn't take any parameters. You want:
List<String> list = (List<String>) in.readObject();

(Of course, this isn't really type-safe, and the compiler should at least raise warnings. How you deal with that is a separate matter.)

A: There is no readObject method with input parameter.
You need to cast the readObject to type of the object you are trying to read.
List ls=  (List)in.readObject();


text:
Q: Return all columns belonging to a record in a key value table when matching multiple values I'm trying to do what seems simple, but my SQL skills are limited :)
I have one table in MySQL containing key value pairs like this:
 ID    |  Record_ID  |    Key    |  Value
  1    |       1     |   type    |  person
  2    |       1     |   name    |  Henrik
  3    |       1     |  skills   |  Not any sql skills
  4    |       1     |   date    |  Today
 ...
 100   |      12     |   type    |  something else
 101   |      12     |  format   |  text
 102   |      13     |   type    |  color
 103   |      13     |   size    |  127

I would like to perform a search that matches something like:
key=type, value=person
AND
key=name, value like Henrik%
AND
key=skills, value LIKE %sql%
And all rows belonging to Record_ID = 1 should be returned.
Please note: each record types has a fixed number of key value pairs, e.g. the person record always has 4 pairs.
When the user performs a search: type is always set, but the other values may or may not be included in the search condition.

A: Using a self join:
SELECT DISTINCT t.*
   FROM TABLE t
   JOIN TABLE t2 ON t2.record_id = t.record_id
                     AND (    (t2.key = 'type' AND t2.value = 'person')
                              OR (t2.key = 'name' AND t2.value LIKE 'Henrik%')
                              OR (t2.key = 'skills' AND t2.value LIKE '%sql%')  )

Using IN:
SELECT t.*
   FROM TABLE t
  WHERE t.record_id IN (SELECT x.record_id
                                    FROM TABLE x
                                   WHERE (    (t2.key = 'type' AND t2.value = 'person')
                              OR (t2.key = 'name' AND t2.value LIKE 'Henrik%')
                              OR (t2.key = 'skills' AND t2.value LIKE '%sql%') )


text:
Q: Spring Controller Url I have question about controllers. Always when i working with controller im start to declare @RequestMapping for example if have UserController then is @RequestMapping("/user");
What if i want to declare another path in this same controller? For example im have @GetMapping("/info") and i will get info about user, but what if i want to declare on this same controller path localhost:8080/topic/blablabla? Is another solution than delete @RequestMapping from controller and make on every Get/PostMapping another path?

A: Defining a @RequestMapping at the controller level; it means narrowing it down to your criteria.

You can use the @RequestMapping annotation to map requests to controllers methods. It has various attributes to match by URL, HTTP method, request parameters, headers, and media types. You can use it at the class level to express shared mappings or at the method level to narrow down to a specific endpoint mapping. Read More

It is good you want to do, sometimes I need it too but as far as I research it is not supported now.


text:
Q: Creating a local rpmforge/repoforge mirror? I make good use of RPMforge for my production CentOS systems. I have local repositories for the main CentOS distribution and updates, however, recent automated kickstart installs are starting to hang on downloads from slower RPMforge mirrors. I've tried limiting to specific RPMforge mirrors and also using the yum fastestmirror plugin. I'd like to establish a local RPMforge repository, but don't know if this is a common practice. I'd be interested in mirroring the EL5 and EL6 repositories.
Does anyone here do this in their own environments? How much space should be budgeted for such a mirror? Or is this idea overkill?
Edit:
Some installation-time debugging seems to show that many of the RPMforge mirrors are outdated or inaccessible. I did find some references to mrepo as a potential solution, though.

A: We are mirroring RPMForge form this server:
mirror="rsync://ftp-stud.fht-esslingen.de/dag"
It's quite fast and reliable.For EL5 it takes 13G, I assume it would be the same for 6
It's common practice but it depends how many machines do you have. We are serving our internal mirrort to 3000+ hosts, so it absolutely makes sense


text:
Q: What gradle task is invoked when android studio build variant changes? I'm trying to configure kotlin in my project, and I've found that my kotlin functions are mangled when they have visibility scope of internal. Having names mangled are all fine except that the mangled names include build variants. So in my Java code I have to write kotlinFunction$module_debug or kotlinFunction$module_release.
The problem is, when I switch the build variant, the suffix should be changed too. For example, I was coding in build variant debug, so I wrote kotlinFunction$module_debug, and then when I switch to build variant release, all my method references break and I have to change all kotlin references to kotlinFunction$module_release. This is OK, we can automate this easily, so I wrote a simple script to do this.
However, the problem I face now is that I do not know when to trigger this script. I assume build variant change triggers some gradle action, but my below code did not work.
task javaUnMangle(type: Exec) {
    def variants = ["debug", "release", "local_ci"]
    for (String variant in variants) {
        if (gradle.startParameter.taskRequests.any {it.args.any {it.toLowerCase().contains(variant.toString())}}) {
            commandLine "python3", "java_kotlin_internal_call_flavor_changer.py", variant
            return
        }
    }
}

project.afterEvaluate {
    preBuild.dependsOn javaUnMangle
}

any tips or feedbacks are appreciated.
Note: Making all functions public is not an option for us as we develop libraries. Thank you.


text:
Q: How does object vs primitive passing work in java (in the context of collections)? So i've read this link: here. But i'm still not 100% clear on the topic.
If i had an arbitrary collection say:
public Set<Integer> hello () {
    Set<Integer> hi = new HashSet<Integer>();
    hi.add(3);

    doWork(hi);
    return hi;
}

static void doWork(Set<Integer> set) {
    set.add(1);
    return;
}

would athis.hello() call return [1] or [1, 3]
What if instead we did something like:
public Set<Integer> hello () {
    Set<Integer> hi = new HashSet<Integer>();
    hi.add(3);

    doWork(hi);
    return hi;
}

static void doWork(Set<Integer> set) {
    Set<Integer> temp = set;
    temp.add(1);
    return;
}

Also, since I'm still not entirely clear on the difference between how it passes primitives and objects - does the fact that it's a set of integers (a primitive type) effect anything?
(I suppose that a Set is an Object so this isn't an issue with Collections)
What if we had something even a little more complicated like
Class Dog {
    String name;
    Dog(String name) {
        this.name = name;
    }

    public void setName(String newName) {
        name = newName;
    }
}

public Set<Dog> hello () {
    Set<Dog> hi = new HashSet<Dog>();
    hi.add(new Dog("Woof");

    doWork(hi);
    return hi;
}

static void doWork(Set<Dog> set) {
    Set<Dog> temp = set;

    for (Dog d : temp)
        d.setName("Bark");
        d = new Dog("Ruff");
        d.setName("Charles");

    return;
}

What would the dog's name be, and what happens to the other dog names?

A: It will return [1, 3] because you are passing the same set.
In the 2nd case it will again return [1, 3], because the same object is referenced.
In short: you have the same object passed around, and you modify its state (in the case of a collection, the state is the elements inside the collection)

A: It will return [1,3]. Try printing out the collection with System.out.println(Set)
Because, after you created the Set hi inside the hello function and added 3. You have passed the same Set to doWork(Set) function, which add 3 to the passed Set, as java passes object reference(the reference of instance of Set) by value.

A: it will return [1,3], your are making change in the same object

A: Both cases will return [1,3].
Even creating the temporary variable Set<Integer> temp = set; you are calling a method that sets a value for temp and set, because they refer the same object.

A: In both senarios, when doWork(hi) is invoked, you are assigning the argument hi to the parameter Set<Integer> set, similar to the following:
Set<Integer> set = hi;

What does that mean? it means that both set and hi are now referring to the same object in the memory:
-------
| set | ----> [HashSet instance]
-------               ^
                      |
-------               |
| hi  | ---------------
-------

In the first scenario, when set.add(1) is invoked, a 1 is added to the set via the reference set. Now hi, can see that 1 as well since it has a link to the same object in the memory.
In the second scenario, you create a third reference temp by this assignment:
Set<Integer> temp = set;

Now, all the three references are referring to the same object in the memory:
-------                             --------
| set | ----> [HashSet instance] <--| temp |
-------               ^             --------
                      |
-------               |
| hi  | ---------------
-------

and when you add 1 to the set via temp:
temp.add(1);

this will be reflected to the other 3 references.

A: First of all, "objects" are not values in Java; hence you cannot "pass" an "object". The only types in Java are reference types and primitive types. Passing works the exact same way for all types, reference types and primitive types. References are pointers to objects.
Collections in the Collections Framework are designed to be collections of references only. This is because to have collections of primitives, it would need to be implemented separately for each primitive type, and separately from reference types. However, one implementation works for all reference types because they are all subtypes of Object. Set, List, Collection, etc. are all collections of references. You have a Set<Integer> which is a collection of Integer values; Integer is a reference type, not a primitive type. Also, only a reference type can be a type argument in generics (what goes in the < >). You may be confusing it with int, which is a primitive type. All primitives types have a corresponding "wrapper" class; Integer is the one for int.
So Set is a reference type and hi, set, etc. are reference variables. You pass a reference to another function, and Java is pass-by-value always, so inside the function set is a copy of the passed reference; but of course it points to the same object as the passed reference. If it makes changes to the object using that reference, the reference in the original scope can see it.


text:
Q: Calling fragment from another fragment issue I am new to Android , I have a Fragment in which I have a Button and on the Button click I want to display another Fragment in place of this Fragment in the same Activity. My code for changing Fragment is like this:
 btnMainSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment generateRequistionFrag=new generate_material_requisition();

                if (generateRequistionFrag != null) {
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, generateRequistionFrag).commit();

                }
            }
        });

I am getting error like this:
  Process: kanix.highrise.com.highrise, PID: 3427
    java.lang.ClassCastException: kanix.highrise.com.highrise.MainActivity@3992b1e7 must implement OnFragmentInteractionListener
            at kanix.highrise.com.highrise.generate_material_requisition.onAttach(generate_material_requisition.java:83)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:853)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)

I tried to implement OnFragmentInteractionListener but not working.
My full fragment code from where I want to switch to other fragement is like this:
 * Created by Mubashir.gul on 13/05/2015.
 */
public class MaterialRequisition extends Fragment {
    Spinner drpProj,drpMaterial,drpTask;
    ProgressDialog pbar;
    private ImageButton btncal;
    private Calendar cal;
    private int day;
    private int month;
    private int year;
    private EditText etcal;

    EditText etQuantity,etSrProject,etSrMaterial,etSrTask;
    List<CItem> lstItm;
    CItem Itm;
    Activity myactivity;
    Button btnSearchProject,btnSearchMaterial,btnSearchTask,btnMainSearch;
    String ProID,MatrID,TaskID;
    public MaterialRequisition(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final View rootView = inflater.inflate(R.layout.fragment_material_requisition, container, false);
//code for calender
        btncal = (ImageButton)rootView. findViewById(R.id.btnimgcal);

        etcal = (EditText) rootView.findViewById(R.id.etDate);
        etcal.setKeyListener(null);//setting edittext non editable
        etQuantity = (EditText) rootView.findViewById(R.id.etQuantity);
        drpProj = (Spinner) rootView.findViewById(R.id.drpProject);
        drpMaterial = (Spinner) rootView.findViewById(R.id.drpMaterial);
        drpTask = (Spinner) rootView.findViewById(R.id.drpTask);
        btnSearchProject =(Button)rootView.findViewById(R.id.btnSearchProject);
        btnSearchMaterial =(Button)rootView.findViewById(R.id.btnSearchMaterial );
        btnSearchTask =(Button)rootView.findViewById(R.id.btnSearchTask );
        btnMainSearch=(Button)rootView.findViewById(R.id.btnMainSearch);

        etSrProject=(EditText)rootView.findViewById(R.id.etSearchProject);
        etSrMaterial=(EditText)rootView.findViewById(R.id.etSearchMaterial);
        etSrTask=(EditText)rootView.findViewById(R.id.etSearchTask);
        myactivity=this.getActivity();//getting parent activity in a variable for use in async task
        etQuantity.setKeyListener(null);//setting edittext non editable

//loading projects
        btnSearchProject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ProjectAsync PAsync=new ProjectAsync();
                PAsync.execute(etSrProject.getText().toString());
            }
        });

      btnSearchMaterial.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              if (!drpProj.getSelectedItem().toString().equals("Select Project") ) {

                  MaterialAsync MAsync = new MaterialAsync();
                  MAsync.execute("64");
              }
              else
              {

                  Toast.makeText(myactivity,"Please select project first!",Toast.LENGTH_SHORT);

              }
          }
      });

        btnSearchTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!drpProj.getSelectedItem().toString().equals("Select Project") ) {

                    ListTaskAsync taskasync = new ListTaskAsync();
                    taskasync.execute(ProID);
                }
                else
                {

                    Toast.makeText(myactivity,"Please select project first!",Toast.LENGTH_SHORT);

                }
            }
        });

        btnMainSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment generateRequistionFrag=new generate_material_requisition();

                if (generateRequistionFrag != null) {
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, generateRequistionFrag).commit();

                }
            }
        });

        btncal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment newFragment = new SelectDateFragment();
                newFragment.show(getFragmentManager(), "DatePicker");
            }
        });
//code for calender

       //call to async task

        lstItm=new ArrayList<CItem>();
        Itm=new CItem( "-1", "Select Project" );
        lstItm.add(Itm);
        if(lstItm.size()>0) {
            ArrayAdapter<CItem> adapterProj = new ArrayAdapter<CItem>(myactivity, android.R.layout.simple_spinner_item, lstItm);

            drpProj.setAdapter(adapterProj);
        }

        lstItm=new ArrayList<CItem>();
        Itm=new CItem( "-1", "Select Material" );
        lstItm.add(Itm);

        if(lstItm.size()>0) {
            ArrayAdapter<CItem> adapterMater = new ArrayAdapter<CItem>(myactivity, android.R.layout.simple_spinner_item, lstItm);

            drpMaterial.setAdapter(adapterMater);
        }

        lstItm=new ArrayList<CItem>();
        Itm=new CItem( "-1", "Select Task" );
        lstItm.add(Itm);

        if(lstItm.size()>0) {
            ArrayAdapter<CItem> adapterMater = new ArrayAdapter<CItem>(myactivity, android.R.layout.simple_spinner_item, lstItm);

            drpTask.setAdapter(adapterMater);
        }

        drpProj.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             //  if (drpMaterial.getCount() > 0)
             //      drpMaterial.setAdapter(null);
               if (!drpProj.getSelectedItem().toString().equals("Select Project"))
               {

                   MaterialAsync MAsync=new MaterialAsync();
                   MAsync.execute("64");

               }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //loading task list

        Button btnSave=(Button)rootView.findViewById(R.id.btnSave);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(getActivity().getApplicationContext(), "Saving please wait!", Toast.LENGTH_LONG).show();
                Toast.makeText(getActivity().getApplicationContext(), "Saved successfully!", Toast.LENGTH_SHORT).show();

            }
        });

        //getting selected project
        drpProj.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                CItem itm=(CItem)parent.getItemAtPosition(position);
                ProID=itm.getId();

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        drpMaterial.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

            });

        return rootView;
    }

A: That interface should be implemented on the activity like
MainActivity extends Activity implements "Interface_Name"{
// and give the actual implementation of method OnFragmentInteractionListener
}

Now what your problem is i guess you are not initailising the variable properly , provide more code so that we can have insight on it and help you !
Also go to your onAttach method of fragment and comment it out for a try because i dont see you are using this call back any where , this might help you too !

A: Fragment generateRequistionFrag=new generate_material_requisition();

That's not the right way to get a new instance of your fragment so please remove
new generate_material_requisition()

Please in your Fragment class create a method getInstance() that return a new YouFragment instance
public static YourFragment getInstance() {
    return new Yourfragment;
}

and then when you need a new instance of that simply make:
YourFragment  fragment = YourFragment.getInstance()

A: You need to replace
Fragment generateRequistionFrag=new generate_material_requisition();

for
 generate_material_requisition generateRequistionFrag=new generate_material_requisition();


text:
Q: Test Class not Covering Throwing an Error
public class status {
    public Candidates__c applicant;
    public Blob resume {get; set;}
    public String contentType {get; set;}
    public String fileName {get; set;}

    public status(ApexPages.StandardController stdController) {
        this.applicant = (Candidates__c)stdController.getRecord();
    }
    public PageReference saveApplication() {
        try {
            insert(applicant);
        } catch (System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }
        if (resume != null) {
            Attachment attach = new Attachment();
            attach.Body = resume;
            attach.Name = filename;
            attach.ContentType = contentType;
            attach.ParentID = applicant.id;
            try {
                insert(attach);
            } catch (System.DMLException e) {
                ApexPages.addMessages(e);
                return null;
            }
        }
        //PageReference p = new ApexPages.StandardController(applicant).view();
        PageReference p = Page.Resume_Parsing;
        p.setRedirect(true);
        return p;
    }
}

Test Class:
@isTest
public class Teststatus {

    public  static testMethod void teststatus() {
        Candidates__c opp = new Candidates__c(First_Name__c = 'test12', Email__c = 'testfdc@gmail.com', Last_Name__c = 'fff', Phone__c = '9999999999');
        insert opp;

        Attachment myAttach1 = new Attachment();
        myAttach1.ParentId = opp.id;
        myAttach1.name = 'Resume_Parsing.pdf';

        myAttach1.body = blob.valueof('test');

        insert myAttach1;

        status atc = new status(new ApexPages.StandardController(opp));
        system.debug('%%%%%' + atc);
        PageReference pageRef = Page.Resume_Parsing;
        pageRef.getParameters().put('id', String.valueOf(opp.Id));
        Test.setCurrentPage(pageRef);
        Blob b;

        ApexPages.currentPage().getParameters().put('id', opp.id);
        status atc1 = new status(new ApexPages.StandardController(myAttach1));

        atc.saveApplication();

        return;
    }

}

Error Message System.TypeException: Invalid conversion from runtime type SOBJECT:Attachment to SOBJECT:Candidates__c
    Stack Trace Class.status.: line 8, column 1
    Class.Teststatus.teststatus: line 26, column 1

A: The trouble is in this line
status atc1 = new status(new ApexPages.StandardController(myAttach1));
because you passes a myAttach1 which has type Attachment but your controller expects Candidates__c record here.


text:
Q: AnyObject does not have a member named "sort" I have an array var savedDataArray: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("savedDataArray")G which I want to sort ascending
Im checking if its empty, then unwrapping it, however i'm still getting the "does not have a member named" error?
if savedDataArray?.count>0{
            savedDataArray!.sort{$0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
        }

error Any object does not have a member named "sort"
So then i tried reversing the array and big surprise the same error for .reverse
I thought by checking if the array is nil, then force unwrapping, these errors wouldnt be relevant

A: Don't access the array as an "AnyObject". Try pulling it as an Array object.
var savedDataArray: Array<String>? = NSUserDefaults.standardUserDefaults().objectForKey("savedDataArray") as? Array<String>;

Substitute the "String" type for whatever you're pulling the objects in your Array as. This allows you to use the "sort" member.


text:
Q: getting php variable from an object in which one of its properties has $ sign so I acquired a json object from an API and json decoded it...
but then the returned object is of the following:
stdClass Object
(
    [id] => stdClass Object
        (
            [$t] => some string
        )
)

And as you can see there is a property with a $ sign in it
but when I do $object->id->$t  <--that returns error since it thinks $t is a variable
how would I go about fetching that variable with $ sign?

A: Encapsulate it as a single-quoted string:
echo $object->id->{'$t'};

Note that you cannot use double quotes for the same reason you cannot use $object->id->$t: PHP will attempt to interpolate $t. However, you could use double quotes if you escape the dollar sign:
echo $obj->id->{"\$t"};

You can see it working in this simple demo.


text:
Q: Block-based animation with animated images I have been trying create simple "block-based animation". I am using an array of images "images" here. I used this method:
 [UIView animateWithDuration:3.0
                       delay:0.0f
                     options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveLinear
                  animations:^{ imageview.animationImages = images; }
                  completion:nil];

However no change happens when I alter the values of parameters animateWithDuration: and delay: I want to slow down the animation but no change happens even when I change these values to 20-30. Please help.

A: To change images in a UIImageView, you don't have to put it inside an animation block. You have to use UIImageView's animationImages and animationDuration properties, as well as probably - startAnimating and - stopAnimating methods of the UIImageView.

A: Add array of images to

animationImages

of UIImageView

and give some animationDuration


text:
Q: laravel 5 issue with slashes in query I am using Laravel 5 and I am facing issues with query when I have slashes(forward or backward)
publications table structure:
CREATE TABLE IF NOT EXISTS `publications` (
`id` bigint(20) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `title` varchar(512) NOT NULL,
  `type` varchar(512) NOT NULL,
  `company` varchar(512) NOT NULL,
  `author` varchar(512) NOT NULL,
  `firm` varchar(512) NOT NULL,
  `address` text NOT NULL,
  `sector_id` bigint(20) NOT NULL DEFAULT '0',
  `date_from` timestamp NULL DEFAULT NULL,
  `date_to` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `region_id` bigint(20) NOT NULL DEFAULT '0',
  `file_name` varchar(512) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created_by` bigint(20) NOT NULL,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_by` bigint(20) NOT NULL,
  `is_active` tinyint(1) NOT NULL DEFAULT '1',
  `category_id` bigint(20) NOT NULL,
  `sub_category_id` bigint(20) NOT NULL,
  `manually_verified` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

Data:
INSERT INTO `publications` (`id`, `user_id`, `title`, `type`, `company`, `author`, `firm`, `address`, `sector_id`, `date_from`, `date_to`, `region_id`, `file_name`, `created_at`, `created_by`, `updated_at`, `updated_by`, `is_active`, `category_id`, `sub_category_id`, `manually_verified`) VALUES
(3, 7, 'test publication 3', 'test 1', 'test 1', 'test author 1', 'test 1', 'test3', 1, '2015-06-09 11:54:18', '2015-06-29 18:30:00', 0, 'files/testing/testing.pdf', '2015-06-06 05:58:10', 7, '2015-06-13 03:31:45', 7, 0, 4, 1, 0),
(4, 7, 'test publication 4', 'test 2', 'test 2', 'test author 2', 'test 2', 'test2', 1, '2015-06-09 11:54:23', '2015-06-29 18:30:00', 0, 'test1.pdf', '2015-06-06 05:58:10', 7, '2015-06-05 23:58:10', 7, 1, 4, 1, 0),
(5, 7, 'test 5', 'test', 'test', 'test', 'test', 'test', 1, '2015-06-09 11:54:09', '2015-06-29 18:30:00', 0, 'files/Bugzilla-uermanual.pdf', '2015-06-06 05:58:10', 7, '2015-06-13 03:19:21', 7, 0, 4, 1, 1);

Laravel 5
$arr = array( 'file_paths' => Array ( 'files/testing/testing.pdf', 'files/Bugzilla-uermanual.pdf' ) );
Query
    $this->publications
        ->where(['category_id'=>$search_cat_id])
        ->where(function ($query) use ($arr){
                foreach ($arr['file_paths'] as $key=>$value){
                    $query->orWhere('file_name', DB::connection()->getPdo()->quote($value));
                }
            })
        ->get();
    print_r($publications_records);

I don't get any result. If I execute the query which was generated by laravel it is getting executed.
Below is the query generated by Laravel and if I execute this in MySQL I get results.
select * from `publications`
where (`category_id` = 4) and
(`file_name` = 'files/testing/testing.pdf'
    or `file_name` = 'files/Bugzilla-uermanual.pdf')
order by `id` desc

A: Try this:
$arr = ['files/testing/testing.pdf', 'files/Bugzilla-uermanual.pdf'];
$publications_records = $this->publications()
    ->where('category_id', $search_cat_id)
    ->where(function ($query) use ($arr){
        foreach ($arr as $value){
            $query->orWhere('file_name', $value);
        }
    })
    ->get();
dd($publications_records, DB:getQueryLog());

If the above code doesnt work. Please edit your question and paste the output


text:
Q: Converting a strong reference to weak reference to self How do you convert this to a weak reference to self?
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.handleMessage(_:)), name: "NewMessage", object: nil)

NSNotificationCenter.defaultCenter().removeObserver(self, name: "NewMessage", object: nil)

Also, a related question--when does the view controller actually get destroyed? I'm assuming when you tab in and out of different views, view controllers still stay alive right? i.e. They don't get destroyed on viewDidDisappear.

A: this  is the function in viewcontroller where it actually get out of the momory so here you can remove observer
                deinit {
                    // you code

                }

and for making weak reference of self you can use
                weak var this = self


text:
Q: Cordova POST data with AngularJS I was trying to POST my login credentials for one of my app built with Cordova and AngularJS. When I login from my browser, it works fine but when test the same in Android (also tested in iOS too, fails on both), the login fails and I get the following headers while debugging.
I saw the differences in these two headers, as in emulator the origin is
Origin: file://. It also has a warning sign for emulator saying "Provisional headers are shown"
Why is it failing in emulator and devices but works fine in browsers? Does cordova does anything internally while wrapping up the POST call?
I really don't understand why is it happening in emulators/devices but works fine in browsers.
In Browser - works fine
Remote Address:xx.xx.x.xxx:xxxx
Request URL:http://myEndpoint
Request Method:POST
Status Code:200 OK

Request Headers view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:166
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:myHost:xxxx
Origin:http://myComputerName.org:xxxxx
Referer:http://myComputerName.org:xxxxx/myAppName/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36

Form Dataview parsed
grant_type=mypassword&client_id=1234&client_secret=1234&username=userName&password=mypassword

Response Headersview source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://myComputerName.org:xxxxx
Content-Type:application/json;charset=UTF-8
Date:Thu, 12 Mar 2015 15:25:53 GMT
Server:Apache-Coyote/1.1
Set-Cookie:
Transfer-Encoding:chunked

======================================================================
In My Android Emulator --> Failed to login
Request URL:http://myEndpoint

Request Headers
Provisional headers are shown
Accept:application/json, text/plain, */*
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:file://
User-Agent:Mozilla/5.0 (Linux; Android 5.0; sdk_phone_armv7 Build/LRX09D) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:1234

Form Dataview parsed
grant_type=mypassword&client_id=1234&client_secret=1234&username=myUserName&password=mypassword


text:
Q: Concatenate various .txt and .html files to one .txt file in R I'm trying to write a script that automatically concatenates all files from specific folders automatically to one .txt file but I'm having problems because I'm trying to merge them into one big data frame before writing it into a txt file and I'm getting errors because column names didn't match, so I used smartbind, but not I'm getting an error for "double row names".
Here's my code:
library(gtools)

dir<-"/Users/max/Desktop/NISAT_All/Regions"

subdir_list<-list.dirs(dir, recursive=F)
subdir_list<-list.dirs(subdir_list,  recursive=F)
as.matrix(subdir_list)
subdirs_General <- subdir_list[ grepl("General", subdir_list) ]
as.matrix(subdirs_General)
subdir_list <- subdir_list[ !grepl("General", subdir_list) ]
subdir_list<-list.dirs(subdir_list,  recursive=F)
as.matrix(subdir_list)

for (subdir in subdir_list){

  setwd(subdir)

  subdir <-list.files(subdir, recursive=T)
  files <- subdir[ grepl("Armed Groups and Small Guns", subdir) ]
  files <- c(files, subdir[ grepl("Arms Embargoes", subdir) ])
  files <- c(files, subdir[ grepl("Black Market", subdir) ])
  files <- c(files, subdir[ grepl("Brokering", subdir) ])
  files <- c(files, subdir[ grepl("Landmines", subdir) ])
  files <- c(files, subdir[ grepl("MANPADS", subdir) ])
  files <- c(files, subdir[ grepl("Production", subdir) ])
  files <- c(files, subdir[ grepl("Stockpile Security and Destruction", subdir) ])
  files <- c(files, subdir[ grepl("UN Processes", subdir) ])
  files <- c(files, subdir[ grepl("United Nations", subdir) ])
  files <- c(files, subdir[ grepl("Weapons Collection and Amnesties", subdir) ])

  dataframe <- data.frame()

  for (file in files){

      df_temp <- read.delim(file)
      dataframe <- smartbind(dataframe, df_temp, sep="\n")

  }
  #then write your final file
  write.table(dataframe,"MergedFiles.txt",sep="\n", row.names = F, eol = "\r")
  rm(dataframe)

}

on the picture you can see how the files usually look like, I just wanna merge them into one
Can anyone help?

A: Suppose I have two text files to merge:
test1.txt
I'm not a pheasant plucker, I'm a pheasant plucker's son

test2.txt
and I'm only plucking pheasants til the pheasant plucker comes.

I just specify the names of the files I want to merge, and create an empty variable that will contain the merged contents:
files_to_combine <- c(path.expand("~/test1.txt"), path.expand("~/test2.txt"))
combined <- ""

Now I just use readLines() to get the contents and paste them together.
for (i in seq_along(files_to_combine))
{
  combined <- paste0(combined,  readLines(files_to_combine[i], "\n")
}

Finally, I write the result back to disk like this:
writeLines(combined, path.expand("~/test3.txt"))

Now in my home directory I have this file:
test3.txt
I'm not a pheasant plucker, I'm a pheasant plucker's son
and I'm only plucking pheasants til the pheasant plucker comes.


text:
Q: How to distinguish overfitting and underfitting from the ROC AUC curve? For model selection, one of the metric is (AUC Area Under Curve) which tell us how the models are performing and based on AUC value we can choose the best model.
But how to distinguish whether a model is overfitting or underfitting from the AUC curve or AUC value of Training, test and desired AUC values?

A: Alone, the ROC curve (or AUC) of the final model on the training set will not provide any information (unless you know something about the performance of the optimal classifier). By definition, the training set cannot be used to evaluate overfitting/underfitting, as it cannot measure the generalization performance of the model. However, comparing the ROC curves of the training set and the validation set can help. The size of the gap between the training and validation metrics is an indicator of overfitting when the gap is large, and indicates underfitting when there is no gap. Everything in between is subject to interpretation, but a good model should produce a small gap.
Measuring the gap between the training and validation ROC curves should be done by measuring the area between the curves. Keep in mind that the difference between the AUCs does not compute the same quantities.
Monitoring the ROC curves (and the gap) during the learning phase can bring additional information as you can see the gap size progression.


text:
Q: How can the font Open Baskerville be used with plain TeX? I downloaded the font Open Baskerville from here, but I don't know how to use it.  How can it be loaded in plain TeX?  I can use any of tex, pdftex or xetex.  (I am using texlive on Linux.)

A: The program otfinfo shows no feature in the OTF font file, which makes it pretty unusable with XeTeX unless a mapping file is prepared for adding f-ligatures or other ones.
However, the distribution comes with a features.fea file that allows to get ligatures with LuaTeX.
I unzipped the downloaded archive and moved to the created directory; I changed the name of
OpenBaskerville-0.0.75.otf

into the more sensible OpenBaskerville.otf; then I moved the file features.fea from the folder OpenBaskerville-0.0.75.ufo into the working directory, renaming it to OpenBaskerville.fea.
Finally I prepared the following file
\input luaotfload.sty

\font\OBx="[OpenBaskerville.otf]":featurefile=OpenBaskerville.fea;+liga
\font\OBxS="[OpenBaskerville.otf]":featurefile=OpenBaskerville.fea;+liga;+dlig;+swsh
\font\OBxviii="[OpenBaskerville.otf]":featurefile=OpenBaskerville.fea;+liga at 18pt

\OBx

{\OBxviii A section title}

\medskip

Ligatures such as firefly and flagstaff
but not gictast

\OBxS

Ligatures such as firefly and flagstaff
but also gictast

\bye

and processed it with luatex, obtaining

Unfortunately the font seems to be at a very preliminary stage and has no italic companion font. Artificially slanting it would be a sin against the memory of Baskerville and his beautiful italic fonts.


text:
Q: How to get my devices bluetooth Mac address in android I need to know my phone's MAC address programmatically;
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
String mac = btAdapter.getAddress();

It returns "02:00:00:00:00:00"
How can I get my phone's right mac address?


text:
Q: How to hide address bar on showmodaldialog
Possible Duplicate:
How can I hide the address bar in a modal dialog?

hello guys,
how to hide address bar (location bar ) on showmodaldialog..
code:
                           var dialogFeatures = 'center:yes; dialogWidth:600px; location:no;dialogHeight:400px; edge:raised; help:no; resizable:no; scroll:no; status:no; statusbar:no; toolbar:no; menubar:no; addressbar:no; titlebar:no;';
                            newwindow2=window.showModalDialog('Combo?start1='+calEvent.start+'&end1='+calEvent.end+'&ownerType='+<%= ApplicationConstants.OWNER_TYPE_CALENDAR %>,'app',dialogFeatures);


text:
Q: For a single Sqlite row, faster to do 5 UPDATEs or build a python dict, then 1 Update? I have several million rows in a Sqlite database that need 5 columns updated. Each row/column value is different, so I have to update each row individually.
Because of the way I'm looping through JSON from an external API, for each row, I have the option of either:
1) do 5 UPDATE operations, one for value.
2) build a temporary dict in python, then unpack it into a single UPDATE operation that updates all 5 columns at once.
Basically I'm trading off Python time (slower language, but in memory) for SQLite time (faster language, but on disk).
Which is faster?

A: Building a dict doesn't really take that much memory. It's much more efficient since you'll only need to do one operation - and let SQLite handle it. Well, python is going to clean the dict anyway, so this is definitely the way to go.
But as @JoranBeasley mentioned in the comment.. You never know until you try.
Hope this helps!


text:
Q: Dataframe Nested Loop - set_value variable inputs Hoping someone may be able to point me in the right direction as I am new to Python.
I am doing a small project to get to grips with data analysis in Python using some football data. I have two dataframes, one with player information  and another with match information (match_df). The match_df has 22 columns with a player ID for each player in the match. I would like to swap the player_ID data in the match_df for the player's skill rating. I have written a function to look up a player and a date and return the rating (find_player_skill). I want to apply this to every relevant column in the dataframe but can't work out how to use the apply function because the arguments depend on the dataframe row. Therefore I think the easiest way is to use set_value on each element of the dataframe as below.
The problem is that I haven't managed to get this to execute (although I haven't tried running for hours on end). I assume there is a way to do the same thing in a reasonable time with different code or a souped up version. I have tried running the code on a small sample (3 rows) which was quick and then 1000 rows which didn't complete in 30 mins or so.
#change player ID's to skill data, currently runs very slowly
for i in range(len(match_df['match_date'])):
    match_date = match_df['match_date'].iloc[i]
    match_index = match_df.iloc[i].name
    for pl_lab in ['h1','h2','h3','h4','h5','h6','h7','h8','h9','h10', 'h11',\
                   'a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11']:
        player_ID = match_df[pl_lab].iloc[i]
        player_skill = find_player_skill(player_ID, match_date)
        match_df.set_value(match_index,pl_lab,player_skill)

Any suggestions much appreciated.
EDIT: It is also worth saying that I thought about debugging the code and downloaded Pycharm for this but some of the earlier code that I wrote seemed to run very slowly (I wrote everything in iPython initially)

A: here is a manipulation you can do, assuming df is the dataframe of match where columns 0 to 2 is the player ID:
df = pd.DataFrame([['c' , 'a', 'b'], ['b', 'c', 'a']])
 df
Out[70]:
   0  1  2
0  c  a  b
1  b  c  a

df_player = pd.DataFrame([['a', 100], ['b', 230], ['c', 200]],columns=['ID', 'skill']).set_index('ID')

    skill
ID
a     100
b     230
c     200

dic = df_player.to_dict()['skill']

df.apply(lambda x: [dic[n] if n in dic.keys() else n for n in x], axis=1)
Out[69]:
     0    1    2
0  200  100  230
1  230  200  100


text:
Q: How to fix Gradle in android studio? I use android studio 3.6 32 bit
but my Gradle is not working:
Gradle sync failed: Could not find crash.jar (com.android.tools.analytics-library:crash:26.6.1).
Searched in the following locations:
https://dl.google.com/dl/android/maven2/com/android/tools/analytics-library/crash/26.6.1/crash-26.6.1.jar
Consult IDE log for more details (Help | Show Log) (54 s 595 ms)
I installed Gradle online and offline but it is not working


text:
Q: What exactly does `iwconfig wlan1 essid "myWifi"` do? I'm working on an embedded device with a limited amount of programs for managing the network.
I ended up using the command:
iwconfig wlan1 essid "myWifi" key "s:password"

At times this works but I have to run dhclient wlan1 after.
Can someone break down this iwconfig command?
It seems that running the command above doesn't actually cause my interface to make a connection. It just tells it what to connect to when it does connect?
Also how should I go about logging the results of using this command?

Edit: this seems to be the source (though the version doesn't seem up to date)

A: The command:
iwconfig wlan1 essid "myWifi" key "s:password"

will associate the wifi device with the Access Point
The command :
dhclient wlan1

is used to get an IP address through DHCP
You can assign an IP address manually (without using dhclient command):
ifconfig wlan1  xxx.xxx.xxx.xxx